-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.py
More file actions
735 lines (657 loc) · 27.8 KB
/
serve.py
File metadata and controls
735 lines (657 loc) · 27.8 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
#!/usr/bin/env python3
"""
Matrix Travel App — Local Server
Serves the web app and provides a JSON API for auto-saving data to disk.
Usage:
python3 serve.py [port]
Default port: 8765
Endpoints:
GET / — serves index.html
GET /api/data — returns matrix-data.json (or 404 if none)
POST /api/data — writes request body to matrix-data.json
POST /api/photos/ID — saves full-size image for photo ID
POST /api/photos/ID/thumb — saves thumbnail for photo ID
DELETE /api/photos/ID — deletes both image files for photo ID
"""
import base64
import json
import os
import re
import sys
import webbrowser
import threading
import time
import ssl
import urllib.request
import urllib.error
import logging
import socket
from http.server import HTTPServer, SimpleHTTPRequestHandler, ThreadingHTTPServer
# Create an SSL context for downloading vendor files
# (some Python installs on macOS lack default certificates)
def _make_ssl_ctx():
try:
return ssl.create_default_context()
except Exception:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
return ctx
def _urlopen(url, **kwargs):
req = kwargs.pop('req', None) or urllib.request.Request(url)
try:
return urllib.request.urlopen(req, context=_make_ssl_ctx(), **kwargs)
except urllib.error.URLError:
# Fallback: skip certificate verification
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
return urllib.request.urlopen(req, context=ctx, **kwargs)
def _download(url, dest):
with _urlopen(url) as resp:
with open(dest, 'wb') as f:
f.write(resp.read())
import argparse
import shutil
import tempfile
APP_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_FILE = os.path.join(APP_DIR, "matrix-data.json")
PHOTOS_DIR = os.path.join(APP_DIR, "matrix-photos")
TILES_DIR = os.path.join(APP_DIR, "matrix-tiles")
VENDOR_DIR = os.path.join(APP_DIR, "vendor")
MAX_TILES_MB = 500
LOG_FILE = os.path.join(APP_DIR, "matrix-requests.log")
# Set up file logger for tile/GET requests
MAX_LOG_LINES = 10000
_req_logger = logging.getLogger('requests')
_req_logger.setLevel(logging.INFO)
_req_handler = logging.FileHandler(LOG_FILE)
_req_handler.setFormatter(logging.Formatter('%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S'))
_req_logger.addHandler(_req_handler)
_req_logger.propagate = False
def _rotate_log():
"""Keep only the last MAX_LOG_LINES lines in the request log."""
try:
if not os.path.exists(LOG_FILE):
return
size = os.path.getsize(LOG_FILE)
if size < 1_000_000: # Only rotate above 1MB
return
with open(LOG_FILE, 'r') as f:
lines = f.readlines()
if len(lines) > MAX_LOG_LINES:
with open(LOG_FILE, 'w') as f:
f.writelines(lines[-MAX_LOG_LINES:])
except OSError:
pass
DEPS_FILE = os.path.join(APP_DIR, "dependencies.json")
# Google Fonts to download (woff2 for modern browsers)
GOOGLE_FONTS_CSS_URL = "https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300;400;500;600;700&display=swap"
def _load_dependencies():
"""Load vendor dependencies from dependencies.json."""
deps_file = os.path.join(APP_DIR, "dependencies.json")
with open(deps_file, "r") as f:
deps = json.load(f)
vendor_files = {}
for dep in deps["vendor"]:
version = dep["version"]
for filename, url_template in dep["files"].items():
vendor_files[filename] = url_template.replace("{{version}}", version)
return deps["vendor"], vendor_files
def setup_vendor():
"""Download external dependencies to vendor/ for offline use."""
os.makedirs(VENDOR_DIR, exist_ok=True)
deps, vendor_files = _load_dependencies()
# Print dependency versions
print(" Dependencies:")
for dep in deps:
print(f" {dep['name']} v{dep['version']}")
print()
needed = []
for name, url in vendor_files.items():
if not os.path.exists(os.path.join(VENDOR_DIR, name)):
needed.append((name, url))
fonts_css_path = os.path.join(VENDOR_DIR, "fonts.css")
fonts_dir = os.path.join(VENDOR_DIR, "fonts")
need_fonts = not os.path.exists(fonts_css_path)
if not needed and not need_fonts:
return # Everything already downloaded
print(" Downloading vendor dependencies for offline support...")
for name, url in needed:
dest = os.path.join(VENDOR_DIR, name)
try:
print(f" Fetching {name}...")
_download(url, dest)
except Exception as e:
print(f" Warning: Could not download {name}: {e}")
print(f" The app will fall back to CDN URLs when online.")
if need_fonts:
try:
print(" Fetching Google Fonts...")
os.makedirs(fonts_dir, exist_ok=True)
# Request with woff2 user-agent to get woff2 format
req = urllib.request.Request(GOOGLE_FONTS_CSS_URL, headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
})
with _urlopen(GOOGLE_FONTS_CSS_URL, req=req) as resp:
css_text = resp.read().decode("utf-8")
# Download each font file referenced in the CSS
font_urls = re.findall(r'url\((https://fonts\.gstatic\.com/[^)]+)\)', css_text)
for i, font_url in enumerate(font_urls):
font_filename = f"font_{i}.woff2"
font_path = os.path.join(fonts_dir, font_filename)
try:
_download(font_url, font_path)
css_text = css_text.replace(font_url, f"fonts/{font_filename}")
except Exception:
pass # Keep original URL as fallback
with open(fonts_css_path, "w") as f:
f.write(css_text)
print(f" Downloaded {len(font_urls)} font files.")
except Exception as e:
print(f" Warning: Could not download fonts: {e}")
print(" Vendor setup complete.")
# Match /api/photos/{id} and /api/photos/{id}/thumb
PHOTO_RE = re.compile(r"^/api/photos/([a-zA-Z0-9_-]+)(/thumb)?$")
# Allowed tile origins for the proxy
TILE_ALLOWED_HOSTS = {'tiles.openfreemap.org', 'server.arcgisonline.com'}
# Video export streaming state: session_id -> {path, file, mime}
_video_sessions = {}
_video_lock = threading.Lock()
# Content-Type by extension
TILE_CONTENT_TYPES = {
'.pbf': 'application/x-protobuf',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.json': 'application/json',
}
def ensure_photos_dir():
os.makedirs(PHOTOS_DIR, exist_ok=True)
_evict_lock = threading.Lock()
def _evict_tiles_if_needed(force=False):
"""Remove oldest tiles when disk cache exceeds MAX_TILES_MB.
When force=True, removes all tiles regardless of size (manual cache clear)."""
if not _evict_lock.acquire(blocking=False):
return 0 # Another eviction is running
try:
if not os.path.isdir(TILES_DIR):
return 0
files = []
total = 0
for root, _, fnames in os.walk(TILES_DIR):
for fn in fnames:
if fn.endswith('.tmp') or fn.startswith('.'):
continue
fp = os.path.join(root, fn)
try:
st = os.stat(fp)
total += st.st_size
files.append((st.st_mtime, st.st_size, fp))
except OSError:
pass
limit = MAX_TILES_MB * 1024 * 1024
if not force and total <= limit:
return 0
before_mb = total / (1024 * 1024)
if force:
_req_logger.info(f'TILE EVICTION: forced cache clear, removing all {len(files)} files ({before_mb:.1f}MB)')
else:
_req_logger.info(f'TILE EVICTION: cache at {before_mb:.1f}MB exceeds {MAX_TILES_MB}MB limit, beginning eviction')
# Sort by modification time (oldest first) and evict
files.sort()
evicted = 0
for mtime, size, fp in files:
if not force and total <= limit * 0.8: # Evict down to 80% to avoid thrashing
break
try:
os.remove(fp)
total -= size
evicted += 1
except OSError:
pass
after_mb = total / (1024 * 1024)
if evicted:
_req_logger.info(f'TILE EVICTION: removed {evicted} files, {before_mb:.1f}MB → {after_mb:.1f}MB (limit {MAX_TILES_MB}MB)')
# Remove empty directories left behind after eviction (e.g. old versioned tile sets
# like 20260422_001001_pt that are no longer needed after their tiles were evicted).
# Walk bottom-up so child dirs are removed before parents.
for root, dirs, fnames in os.walk(TILES_DIR, topdown=False):
if root == TILES_DIR:
continue # Never remove TILES_DIR itself
real_files = [f for f in fnames if not f.startswith('.')]
if not real_files and not dirs:
# Remove hidden files (.DS_Store etc.) before rmdir
for hf in fnames:
try: os.remove(os.path.join(root, hf))
except OSError: pass
try:
os.rmdir(root)
except OSError:
pass
return evicted
finally:
_evict_lock.release()
class MatrixHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=APP_DIR, **kwargs)
# Paths that browsers request automatically; return 204 to suppress 404 noise
_SILENT_PATHS = {'/favicon.ico', '/apple-touch-icon.png', '/apple-touch-icon-precomposed.png'}
def end_headers(self):
# Prevent browser from caching app files and fonts so edits/swaps take effect immediately.
# Vendor libs (MapLibre, Supercluster, exif-js) are versioned and safe to cache.
path = self.path.split('?')[0]
is_vendor_lib = path.startswith('/vendor/') and not path.startswith('/vendor/fonts')
if not is_vendor_lib and not path.startswith('/api/'):
self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
super().end_headers()
def do_GET(self):
try:
if self.path == "/api/data":
self._serve_data()
elif self.path.startswith("/api/tiles/proxy?"):
self._proxy_tile()
elif self.path.startswith("/api/video/download?"):
self._download_video()
elif self.path in self._SILENT_PATHS:
self.send_response(204)
self.end_headers()
else:
super().do_GET()
except (ConnectionResetError, BrokenPipeError):
pass # Client disconnected mid-response (refresh, SW abort, etc.)
def do_POST(self):
try:
if self.path == "/api/data":
self._save_data()
elif self.path.startswith("/api/tiles/cache?"):
self._cache_tile()
elif self.path == "/api/video/start":
self._video_start()
elif self.path.startswith("/api/video/chunk?"):
self._video_chunk()
elif self.path.startswith("/api/video/finalize?"):
self._video_finalize()
elif self.path.startswith("/api/video/abort?"):
self._video_abort()
else:
m = PHOTO_RE.match(self.path)
if m:
self._save_photo(m.group(1), is_thumb=bool(m.group(2)))
else:
self.send_error(404)
except (ConnectionResetError, BrokenPipeError):
pass
def do_DELETE(self):
try:
if self.path.rstrip('/') == '/api/tiles/clear':
self._clear_tile_cache()
return
m = PHOTO_RE.match(self.path)
if m and not m.group(2):
self._delete_photo(m.group(1))
else:
self.send_error(404)
except (ConnectionResetError, BrokenPipeError):
pass
def _serve_data(self):
if not os.path.exists(DATA_FILE):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{}')
return
with open(DATA_FILE, "rb") as f:
data = f.read()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def _save_data(self):
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length)
try:
json.loads(body)
except json.JSONDecodeError:
self.send_response(400)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"error":"invalid JSON"}')
return
tmp = DATA_FILE + ".tmp"
with open(tmp, "wb") as f:
f.write(body)
os.replace(tmp, DATA_FILE)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"ok":true}')
def _save_photo(self, photo_id, is_thumb=False):
ensure_photos_dir()
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length)
content_type = self.headers.get("Content-Type", "")
if "json" in content_type:
# Expect {"dataUrl": "data:image/jpeg;base64,..."}
try:
obj = json.loads(body)
data_url = obj.get("dataUrl", "")
except json.JSONDecodeError:
self.send_response(400)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"error":"invalid JSON"}')
return
# Parse data URL
match = re.match(r"data:image/(\w+);base64,(.+)", data_url, re.DOTALL)
if not match:
self.send_response(400)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"error":"invalid data URL"}')
return
ext = match.group(1)
if ext == "jpeg":
ext = "jpg"
image_bytes = base64.b64decode(match.group(2))
else:
# Raw binary upload
image_bytes = body
ext = "jpg"
suffix = "_thumb" if is_thumb else ""
filename = f"{photo_id}{suffix}.{ext}"
filepath = os.path.join(PHOTOS_DIR, filename)
tmp = filepath + ".tmp"
with open(tmp, "wb") as f:
f.write(image_bytes)
os.replace(tmp, filepath)
# Remove old files with different extensions (e.g. _thumb.jpg when saving _thumb.webp)
prefix = f"{photo_id}{suffix}."
for fname in os.listdir(PHOTOS_DIR):
if fname.startswith(prefix) and fname != filename and not fname.endswith('.tmp'):
os.remove(os.path.join(PHOTOS_DIR, fname))
rel_path = f"matrix-photos/{filename}"
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"ok": True, "path": rel_path}).encode())
def _delete_photo(self, photo_id):
removed = []
if os.path.exists(PHOTOS_DIR):
for fname in os.listdir(PHOTOS_DIR):
if fname.startswith(f"{photo_id}.") or fname.startswith(f"{photo_id}_thumb."):
fpath = os.path.join(PHOTOS_DIR, fname)
os.remove(fpath)
removed.append(fname)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"ok": True, "removed": removed}).encode())
def _send_tile(self, data, content_type):
"""Send tile response, silently ignoring client disconnects."""
try:
self.send_response(200)
self.send_header('Content-Type', content_type)
self.send_header('Content-Length', str(len(data)))
self.send_header('Cache-Control', 'public, max-age=31536000, immutable')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(data)
except (ConnectionResetError, BrokenPipeError):
pass # Client disconnected (e.g. user panned away, SW timeout)
def _proxy_tile(self):
"""Serve tile from disk cache only. Returns 404 if not cached."""
from urllib.parse import urlparse, parse_qs
qs_start = self.path.index('?')
params = parse_qs(self.path[qs_start + 1:])
url = params.get('url', [None])[0]
if not url:
self.send_error(400, "Missing url parameter")
return
parsed = urlparse(url)
if parsed.hostname not in TILE_ALLOWED_HOSTS:
self.send_error(403, "Origin not allowed")
return
rel_path = parsed.hostname + parsed.path
tile_path = os.path.join(TILES_DIR, rel_path)
ext = os.path.splitext(tile_path)[1]
content_type = TILE_CONTENT_TYPES.get(ext, 'application/octet-stream')
if os.path.isfile(tile_path):
with open(tile_path, 'rb') as f:
data = f.read()
self._send_tile(data, content_type)
return
# Not on disk — return 404 so SW fetches directly from origin
self.send_response(404)
self.end_headers()
def _cache_tile(self):
"""Save tile data to disk cache (called by SW after fetching from origin)."""
from urllib.parse import urlparse, parse_qs
qs_start = self.path.index('?')
params = parse_qs(self.path[qs_start + 1:])
url = params.get('url', [None])[0]
if not url:
self.send_error(400, "Missing url parameter")
return
parsed = urlparse(url)
if parsed.hostname not in TILE_ALLOWED_HOSTS:
self.send_error(403, "Origin not allowed")
return
length = int(self.headers.get("Content-Length", 0))
data = self.rfile.read(length)
rel_path = parsed.hostname + parsed.path
tile_path = os.path.join(TILES_DIR, rel_path)
try:
if not os.path.isdir(tile_path):
os.makedirs(os.path.dirname(tile_path), exist_ok=True)
tmp = tile_path + '.tmp'
with open(tmp, 'wb') as f:
f.write(data)
os.replace(tmp, tile_path)
except OSError:
pass
threading.Thread(target=_evict_tiles_if_needed, daemon=True).start()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"ok":true}')
def _video_start(self):
"""Start a new video export session, return session ID."""
from urllib.parse import parse_qs
length = int(self.headers.get('Content-Length', 0))
body = json.loads(self.rfile.read(length)) if length else {}
mime = body.get('mime', 'video/webm')
ext = 'webm' if 'webm' in mime else 'mp4'
session_id = f"vid_{int(time.time() * 1000)}"
path = os.path.join(APP_DIR, f"matrix-video-{session_id}.{ext}")
with _video_lock:
_video_sessions[session_id] = {'path': path, 'file': open(path, 'wb'), 'mime': mime}
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'ok': True, 'id': session_id}).encode())
def _video_chunk(self):
"""Append a video chunk to the session file."""
from urllib.parse import parse_qs
qs = parse_qs(self.path.split('?', 1)[1])
session_id = qs.get('id', [None])[0]
length = int(self.headers.get('Content-Length', 0))
data = self.rfile.read(length)
with _video_lock:
session = _video_sessions.get(session_id)
if session and session.get('file'):
session['file'].write(data)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(b'{"ok":true}')
def _video_finalize(self):
"""Close the video file and prepare it for download."""
from urllib.parse import parse_qs
qs = parse_qs(self.path.split('?', 1)[1])
session_id = qs.get('id', [None])[0]
with _video_lock:
session = _video_sessions.get(session_id)
if not session:
self.send_error(404, 'Session not found')
return
if session.get('file'):
session['file'].close()
session['file'] = None
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'ok': True, 'id': session_id}).encode())
def _download_video(self):
"""Stream the completed video file to the browser for download."""
from urllib.parse import parse_qs
qs = parse_qs(self.path.split('?', 1)[1])
session_id = qs.get('id', [None])[0]
with _video_lock:
session = _video_sessions.get(session_id)
if not session or not os.path.isfile(session['path']):
self.send_error(404, 'Video not found')
return
path = session['path']
size = os.path.getsize(path)
filename = os.path.basename(path).replace(f"-{session_id}", '')
self.send_response(200)
self.send_header('Content-Type', session['mime'])
self.send_header('Content-Length', str(size))
self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
self.end_headers()
with open(path, 'rb') as f:
while chunk := f.read(1024 * 1024):
self.wfile.write(chunk)
# Cleanup session and temp file
with _video_lock:
_video_sessions.pop(session_id, None)
try:
os.remove(path)
except OSError:
pass
def _video_abort(self):
"""Abort a video session and delete the temp file."""
from urllib.parse import parse_qs
qs = parse_qs(self.path.split('?', 1)[1])
session_id = qs.get('id', [None])[0]
with _video_lock:
session = _video_sessions.pop(session_id, None)
if session:
if session.get('file'):
try: session['file'].close()
except: pass
try: os.remove(session['path'])
except: pass
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(b'{"ok":true}')
def _clear_tile_cache(self):
"""Wipe the entire matrix-tiles directory and recreate it empty for a clean state."""
try:
removed = 0
if os.path.isdir(TILES_DIR):
# Count files before wiping (excluding hidden files)
for root, _, fnames in os.walk(TILES_DIR):
removed += sum(1 for f in fnames if not f.startswith('.'))
shutil.rmtree(TILES_DIR)
os.makedirs(TILES_DIR, exist_ok=True)
_req_logger.info(f'TILE CACHE CLEARED: wiped matrix-tiles directory ({removed} files removed)')
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'ok': True, 'removed': removed}).encode())
except Exception as e:
print(f'Error clearing tile cache: {e}')
try:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'ok': False, 'error': str(e)}).encode())
except Exception:
pass
def log_message(self, format, *args):
_req_logger.info(format % args)
def open_browser():
time.sleep(0.8)
webbrowser.open(f"http://localhost:{PORT}")
def _run_tests(port):
"""Start server with isolated temp data dir, run Playwright tests, cleanup."""
global DATA_FILE, PHOTOS_DIR, LOG_FILE
test_dir = tempfile.mkdtemp(prefix='matrix-test-')
DATA_FILE = os.path.join(test_dir, 'matrix-data.json')
PHOTOS_DIR = os.path.join(test_dir, 'matrix-photos')
LOG_FILE = os.path.join(test_dir, 'matrix-requests.log')
print(f"\n Matrix — Test Runner")
print(f" Test data dir: {test_dir}")
# Generate test fixture images
fixture_script = os.path.join(APP_DIR, 'tests', 'fixtures', 'generate-test-images.py')
if os.path.exists(fixture_script):
subprocess.run([sys.executable, fixture_script], check=True)
# Setup vendor deps
try:
setup_vendor()
except Exception:
pass
# Start server in background
server = ThreadingHTTPServer(("127.0.0.1", port), MatrixHandler)
server_thread = threading.Thread(target=server.serve_forever, daemon=True)
server_thread.start()
print(f" Test server running on http://localhost:{port}")
tests_dir = os.path.join(APP_DIR, 'tests')
# Install dependencies if needed
if not os.path.exists(os.path.join(tests_dir, 'node_modules')):
print(" Installing Playwright...")
subprocess.run(['npm', 'install'], cwd=tests_dir, check=True)
subprocess.run(['npx', 'playwright', 'install', 'chromium'], cwd=tests_dir, check=True)
# Run tests
print()
result = subprocess.run(['npx', 'playwright', 'test'], cwd=tests_dir)
# Cleanup
server.shutdown()
shutil.rmtree(test_dir, ignore_errors=True)
sys.exit(result.returncode)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Matrix Local Server')
parser.add_argument('port', nargs='?', type=int, default=8765, help='Port number (default: 8765)')
parser.add_argument('--run-tests', action='store_true', help='Run Playwright integration tests')
args = parser.parse_args()
PORT = args.port
DATA_FILE = os.path.join(APP_DIR, "matrix-data.json")
PHOTOS_DIR = os.path.join(APP_DIR, "matrix-photos")
LOG_FILE = os.path.join(APP_DIR, "matrix-requests.log")
if args.run_tests:
import subprocess
_run_tests(PORT)
else:
print(f"\n Matrix Travel App")
try:
setup_vendor()
except Exception as e:
print(f" Warning: Vendor setup failed: {e}")
print(f" The app will use CDN URLs when online.")
ThreadingHTTPServer.allow_reuse_address = True
server = ThreadingHTTPServer(("0.0.0.0", PORT), MatrixHandler)
print(f" Open: http://localhost:{PORT}")
try:
lan_ip = socket.gethostbyname(socket.gethostname())
if lan_ip and not lan_ip.startswith('127.'):
print(f" LAN: http://{lan_ip}:{PORT}")
except Exception:
pass
print(f" Data file: {DATA_FILE}")
print(f" Photos dir: {PHOTOS_DIR}")
print(f" Tiles cache: {TILES_DIR} (max {MAX_TILES_MB}MB)")
print(f" Request log: {LOG_FILE}")
# Trim tile cache and rotate log on startup
_rotate_log()
threading.Thread(target=_evict_tiles_if_needed, daemon=True).start()
print(f" Press Ctrl+C to stop\n")
threading.Thread(target=open_browser, daemon=True).start()
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nShutting down.")
server.server_close()