gba server, jellyfin
This commit is contained in:
@@ -4,15 +4,34 @@
|
||||
Saves and favourites are keyed by the Remote-User header (set by Authelia
|
||||
via Caddy forward_auth), so each authenticated user gets their own data.
|
||||
|
||||
Offline mode: a Service Worker caches static assets and ROMs in the browser
|
||||
after first play. Saves made while offline are queued in IndexedDB and synced
|
||||
to the server automatically when connectivity is restored.
|
||||
Offline mode (PWA): a Service Worker makes the app installable and playable
|
||||
offline. The design is deliberately *network-first* so online behaviour is
|
||||
identical to having no Service Worker at all — the cache is only ever read
|
||||
when the network is genuinely unreachable, so offline support cannot break
|
||||
online play.
|
||||
|
||||
- App shell + EmulatorJS static assets (/static/...) are cached in a
|
||||
build-scoped cache (`emujs-shell-<BUILD_ID>`). BUILD_ID changes whenever
|
||||
this file or the EmulatorJS asset path changes, so a redeploy transparently
|
||||
invalidates stale assets — no manual cache-version bump needed.
|
||||
- ROMs are large, so they are NOT cached automatically. The launcher has a
|
||||
per-game "download for offline" button that persists the ROM (and its
|
||||
thumbnail) in a separate, build-independent cache (`emujs-roms`).
|
||||
- Saves made while offline are queued in IndexedDB and synced to the server
|
||||
automatically when connectivity returns.
|
||||
|
||||
Note: a game can only be *played* offline if (a) its ROM was downloaded, and
|
||||
(b) its emulator core was cached — cores are cached automatically the first
|
||||
time you play any game of that system while online.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import urllib.parse
|
||||
import zipfile
|
||||
import zlib
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from string import Template
|
||||
|
||||
@@ -24,6 +43,23 @@ PORT = int(os.environ.get("PORT", "8085"))
|
||||
|
||||
SAFE_RE = re.compile(r"^[A-Za-z0-9 _\-\.\(\)\[\]',!?:&+#]+$")
|
||||
|
||||
|
||||
def _compute_build_id() -> str:
|
||||
"""A short id that changes whenever this server file or the static asset
|
||||
path changes. Used to name the Service Worker's shell cache so redeploys
|
||||
invalidate stale cached assets automatically."""
|
||||
h = hashlib.sha256()
|
||||
try:
|
||||
with open(__file__, "rb") as f:
|
||||
h.update(f.read())
|
||||
except Exception:
|
||||
pass
|
||||
h.update(STATIC_DIR.encode())
|
||||
return h.hexdigest()[:12]
|
||||
|
||||
|
||||
BUILD_ID = _compute_build_id()
|
||||
|
||||
ROM_SYSTEMS = {
|
||||
".gb": "gameboy",
|
||||
".gbc": "gameboy_color",
|
||||
@@ -73,14 +109,75 @@ MIME_TYPES = {
|
||||
".ico": "image/x-icon",
|
||||
}
|
||||
|
||||
|
||||
def _png_icon(size: int, bg: tuple, fg: tuple) -> bytes:
|
||||
"""Generate a solid PWA icon (dark square + centred accent circle) as PNG,
|
||||
using only the standard library. Computed once at startup."""
|
||||
cx = cy = size / 2.0
|
||||
r2 = (size * 0.32) ** 2
|
||||
bg_px = bytes(bg)
|
||||
fg_px = bytes(fg)
|
||||
raw = bytearray()
|
||||
for y in range(size):
|
||||
raw.append(0) # PNG filter type 0 (none) per scanline
|
||||
dy = y + 0.5 - cy
|
||||
dy2 = dy * dy
|
||||
for x in range(size):
|
||||
dx = x + 0.5 - cx
|
||||
raw += fg_px if (dx * dx + dy2) <= r2 else bg_px
|
||||
|
||||
def chunk(typ: bytes, data: bytes) -> bytes:
|
||||
crc = zlib.crc32(typ + data) & 0xffffffff
|
||||
return struct.pack(">I", len(data)) + typ + data + struct.pack(">I", crc)
|
||||
|
||||
sig = b"\x89PNG\r\n\x1a\n"
|
||||
ihdr = struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0) # 8-bit truecolor RGB
|
||||
idat = zlib.compress(bytes(raw), 9)
|
||||
return sig + chunk(b"IHDR", ihdr) + chunk(b"IDAT", idat) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
ICON_PNG = _png_icon(256, (26, 26, 46), (233, 69, 96))
|
||||
|
||||
MANIFEST_JSON = json.dumps({
|
||||
"name": "Game Library",
|
||||
"short_name": "Games",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"orientation": "landscape",
|
||||
"background_color": "#1a1a2e",
|
||||
"theme_color": "#1a1a2e",
|
||||
"icons": [{
|
||||
"src": "/icon-256.png",
|
||||
"sizes": "256x256",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable",
|
||||
}],
|
||||
})
|
||||
|
||||
# HTML <head> fragment that makes a page installable as a PWA.
|
||||
PWA_HEAD = """\
|
||||
<link rel="manifest" href="/manifest.json">
|
||||
<meta name="theme-color" content="#1a1a2e">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<meta name="apple-mobile-web-app-title" content="Games">
|
||||
<link rel="apple-touch-icon" href="/icon-256.png">"""
|
||||
|
||||
# ── Service Worker ─────────────────────────────────────────────────────────────
|
||||
SW_JS = """\
|
||||
const CACHE_NAME = 'emulatorjs-v4';
|
||||
# Network-first everywhere so online play behaves exactly as it would with no
|
||||
# Service Worker; the cache is only read when the network is unreachable.
|
||||
SW_JS = ("""\
|
||||
const SHELL_CACHE = 'emujs-shell-""" + BUILD_ID + """';
|
||||
const ROM_CACHE = 'emujs-roms'; // build-independent, holds downloaded ROMs
|
||||
const APP_SHELL = ['/', '/manifest.json', '/icon-256.png', '/static/loader.js'];
|
||||
|
||||
self.addEventListener('install', function(event) {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME).then(function(cache) {
|
||||
return cache.addAll(['/static/loader.js', '/']);
|
||||
caches.open(SHELL_CACHE).then(function(cache) {
|
||||
// allSettled: a single missing asset must not abort the whole install.
|
||||
return Promise.allSettled(APP_SHELL.map(function(u) { return cache.add(u); }));
|
||||
})
|
||||
);
|
||||
self.skipWaiting();
|
||||
@@ -89,117 +186,102 @@ self.addEventListener('install', function(event) {
|
||||
self.addEventListener('activate', function(event) {
|
||||
event.waitUntil(
|
||||
caches.keys().then(function(keys) {
|
||||
return Promise.all(
|
||||
keys.filter(function(k) { return k !== CACHE_NAME; })
|
||||
.map(function(k) { return caches.delete(k); })
|
||||
);
|
||||
})
|
||||
return Promise.all(keys.map(function(k) {
|
||||
if (k !== SHELL_CACHE && k !== ROM_CACHE) return caches.delete(k);
|
||||
}));
|
||||
}).then(function() { return self.clients.claim(); })
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
// Cache a response only if it is a same-origin 200. This avoids poisoning the
|
||||
// cache with Authelia auth redirects or error pages.
|
||||
function cacheable(res) {
|
||||
return res && res.status === 200 && res.type === 'basic';
|
||||
}
|
||||
|
||||
function networkFirst(req, cacheName) {
|
||||
return fetch(req).then(function(res) {
|
||||
if (cacheable(res)) {
|
||||
var copy = res.clone();
|
||||
caches.open(cacheName).then(function(c) { c.put(req, copy).catch(function(){}); });
|
||||
}
|
||||
return res;
|
||||
}).catch(function() {
|
||||
return caches.open(cacheName).then(function(c) {
|
||||
return c.match(req).then(function(hit) {
|
||||
return hit || new Response('', { status: 503 });
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function cacheFirst(req, cacheName) {
|
||||
return caches.open(cacheName).then(function(c) {
|
||||
return c.match(req).then(function(hit) {
|
||||
if (hit) return hit;
|
||||
return fetch(req).then(function(res) {
|
||||
if (cacheable(res)) c.put(req, res.clone()).catch(function(){});
|
||||
return res;
|
||||
}).catch(function() { return new Response('', { status: 503 }); });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
self.addEventListener('fetch', function(event) {
|
||||
var url = new URL(event.request.url);
|
||||
var req = event.request;
|
||||
if (req.method !== 'GET') return; // saves/favourites writes: untouched
|
||||
var url = new URL(req.url);
|
||||
if (url.origin !== self.location.origin) return;
|
||||
var path = url.pathname;
|
||||
|
||||
if (path === '/sw.js' || path === '/manifest.json') return;
|
||||
// The SW itself and dynamic save endpoints: pure passthrough.
|
||||
if (path === '/sw.js' || path.startsWith('/saves/')) return;
|
||||
|
||||
if (path.startsWith('/saves/')) {
|
||||
// Individual ROM file: served from the download cache when present (offline
|
||||
// play), otherwise straight to network with NO implicit caching (ROMs are
|
||||
// large — caching is opt-in via the launcher's download button).
|
||||
if (path.startsWith('/roms/') && path !== '/roms/') {
|
||||
event.respondWith(
|
||||
fetch(event.request).catch(function() {
|
||||
return new Response('', { status: 503 });
|
||||
caches.open(ROM_CACHE).then(function(c) {
|
||||
return c.match(req).then(function(hit) { return hit || fetch(req); });
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Static assets and individual ROM files: cache-first.
|
||||
// Use arrayBuffer() instead of clone() to avoid an iOS Safari bug where
|
||||
// a cloned response body can be empty when the original stream is consumed.
|
||||
if (path.startsWith('/static/') || (path.startsWith('/roms/') && path !== '/roms/')) {
|
||||
event.respondWith(
|
||||
caches.match(event.request).then(function(cached) {
|
||||
if (cached) return cached;
|
||||
return fetch(event.request).then(function(response) {
|
||||
if (!response.ok) return response;
|
||||
var status = response.status;
|
||||
var headers = new Headers(response.headers);
|
||||
return response.arrayBuffer().then(function(body) {
|
||||
caches.open(CACHE_NAME).then(function(cache) {
|
||||
cache.put(event.request,
|
||||
new Response(body, { status: status, headers: headers })
|
||||
).catch(function(e) {
|
||||
console.warn('[SW] cache.put failed (quota?):', event.request.url, e);
|
||||
});
|
||||
});
|
||||
return new Response(body, { status: status, headers: headers });
|
||||
});
|
||||
}).catch(function() {
|
||||
return new Response('', { status: 503 });
|
||||
});
|
||||
})
|
||||
);
|
||||
// EmulatorJS static assets are immutable within a build, and SHELL_CACHE is
|
||||
// build-scoped, so cache-first is safe and fast (no staleness across builds).
|
||||
if (path.startsWith('/static/')) {
|
||||
event.respondWith(cacheFirst(req, SHELL_CACHE));
|
||||
return;
|
||||
}
|
||||
|
||||
// Player pages: network-first so new deployments always take effect.
|
||||
// Cache is used only as offline fallback.
|
||||
if (path.startsWith('/play/')) {
|
||||
event.respondWith(
|
||||
fetch(event.request).then(function(response) {
|
||||
var status = response.status, headers = new Headers(response.headers);
|
||||
return response.arrayBuffer().then(function(body) {
|
||||
caches.open(CACHE_NAME).then(function(cache) {
|
||||
cache.put(event.request, new Response(body, { status: status, headers: headers }));
|
||||
});
|
||||
return new Response(body, { status: status, headers: headers });
|
||||
});
|
||||
}).catch(function() {
|
||||
return caches.match(event.request).then(function(cached) {
|
||||
return cached || new Response('Offline', { status: 503 });
|
||||
});
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Thumbnails: cache on first successful fetch
|
||||
// Thumbnails: small and stable — cache-first in the persistent ROM cache so
|
||||
// downloaded games still show artwork offline.
|
||||
if (path.startsWith('/thumbnails/')) {
|
||||
event.respondWith(
|
||||
caches.match(event.request).then(function(cached) {
|
||||
if (cached) return cached;
|
||||
return fetch(event.request).then(function(response) {
|
||||
if (!response.ok) return response;
|
||||
var status = response.status, headers = new Headers(response.headers);
|
||||
return response.arrayBuffer().then(function(body) {
|
||||
caches.open(CACHE_NAME).then(function(cache) {
|
||||
cache.put(event.request, new Response(body, { status: status, headers: headers }));
|
||||
});
|
||||
return new Response(body, { status: status, headers: headers });
|
||||
});
|
||||
}).catch(function() { return new Response('', { status: 404 }); });
|
||||
})
|
||||
);
|
||||
event.respondWith(cacheFirst(req, ROM_CACHE));
|
||||
return;
|
||||
}
|
||||
|
||||
// ROM listing, favorites, launcher: network-first, cache fallback (small text responses)
|
||||
event.respondWith(
|
||||
fetch(event.request).then(function(response) {
|
||||
var status = response.status, headers = new Headers(response.headers);
|
||||
return response.arrayBuffer().then(function(body) {
|
||||
caches.open(CACHE_NAME).then(function(cache) {
|
||||
cache.put(event.request, new Response(body, { status: status, headers: headers }));
|
||||
});
|
||||
return new Response(body, { status: status, headers: headers });
|
||||
});
|
||||
}).catch(function() {
|
||||
return caches.match(event.request).then(function(cached) {
|
||||
return cached || new Response('', { status: 503 });
|
||||
});
|
||||
})
|
||||
);
|
||||
// App shell, ROM listing, favourites, player pages, icons/manifest:
|
||||
// network-first with a cache fallback so the library is browsable offline.
|
||||
if (path === '/' || path === '/roms/' || path === '/favorites' ||
|
||||
path.startsWith('/play/') || path === '/manifest.json' ||
|
||||
path.startsWith('/icon')) {
|
||||
event.respondWith(networkFirst(req, SHELL_CACHE));
|
||||
return;
|
||||
}
|
||||
// Everything else: default network handling.
|
||||
});
|
||||
""")
|
||||
|
||||
# ── Shared JS: Service Worker registration ─────────────────────────────────────
|
||||
_SW_REG = """\
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js').catch(function(e) {
|
||||
console.warn('SW registration failed', e);
|
||||
});
|
||||
}
|
||||
"""
|
||||
|
||||
# ── Shared JS: IndexedDB offline save queue ────────────────────────────────────
|
||||
@@ -277,12 +359,39 @@ async function syncPendingSaves() {
|
||||
}
|
||||
"""
|
||||
|
||||
# ── Shared JS: Service Worker registration ─────────────────────────────────────
|
||||
_SW_REG = """\
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js').catch(function(e) {
|
||||
console.warn('SW registration failed', e);
|
||||
});
|
||||
# ── Shared JS: name of the build-scoped shell cache (mirrors the Service Worker)
|
||||
# so pages can populate it directly, bypassing SW-interception timing gaps.
|
||||
_SHELL_CACHE_JS = "var SHELL_CACHE = 'emujs-shell-" + BUILD_ID + "';\n"
|
||||
|
||||
# ── Shared JS: persist the EmulatorJS assets a game actually loaded ─────────────
|
||||
# Relying on the Service Worker to cache the core (mgba-*.data etc.) during play
|
||||
# is unreliable — on the first visit the SW is not yet controlling the page, so
|
||||
# those fetches are never seen. Instead we read the real URLs the browser loaded
|
||||
# from Resource Timing and write them into the shell cache directly from the page.
|
||||
_CACHE_STATIC_JS = """\
|
||||
async function cacheLoadedStatic() {
|
||||
if (!('caches' in window) || !navigator.onLine) return;
|
||||
try {
|
||||
var cache = await caches.open(SHELL_CACHE);
|
||||
var urls = performance.getEntriesByType('resource')
|
||||
.map(function(e) { return e.name; })
|
||||
.filter(function(u) {
|
||||
var x; try { x = new URL(u); } catch(_) { return false; }
|
||||
return x.origin === location.origin && x.pathname.indexOf('/static/') === 0;
|
||||
});
|
||||
urls.push(location.pathname); // the /play/<name> document itself
|
||||
var seen = {};
|
||||
for (var i = 0; i < urls.length; i++) {
|
||||
var u = urls[i];
|
||||
if (seen[u]) continue;
|
||||
seen[u] = 1;
|
||||
try {
|
||||
if (await cache.match(u)) continue;
|
||||
var r = await fetch(u);
|
||||
if (r && r.status === 200) await cache.put(u, r.clone());
|
||||
} catch(_) {}
|
||||
}
|
||||
} catch(_) {}
|
||||
}
|
||||
"""
|
||||
|
||||
@@ -294,6 +403,7 @@ LAUNCHER_HTML = ("""\
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Game Library</title>
|
||||
""" + PWA_HEAD + """
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: system-ui, sans-serif; background: #1a1a2e; color: #eee;
|
||||
@@ -303,10 +413,7 @@ LAUNCHER_HTML = ("""\
|
||||
display: none; background: #c0392b; color: #fff; text-align: center;
|
||||
padding: .5rem; font-size: .9rem; margin: -1.5rem -1rem 1rem;
|
||||
}
|
||||
#dbg-bar {
|
||||
font-size: .7rem; color: #9ab; margin-bottom: .75rem; font-family: monospace;
|
||||
background: #0d1527; border-radius: 6px; padding: .4rem .75rem;
|
||||
}
|
||||
body.offline #offline-banner { display: block; }
|
||||
#search {
|
||||
width: 100%; padding: .7rem 1rem; font-size: 1rem;
|
||||
background: #16213e; border: 1px solid #0f3460; border-radius: 8px;
|
||||
@@ -323,9 +430,11 @@ LAUNCHER_HTML = ("""\
|
||||
.card {
|
||||
background: #16213e; border-radius: 10px; overflow: hidden; position: relative;
|
||||
text-decoration: none; color: #eee; display: block;
|
||||
transition: transform .15s, background .15s;
|
||||
transition: transform .15s, background .15s, opacity .15s;
|
||||
}
|
||||
.card:hover { background: #0f3460; transform: translateY(-2px); }
|
||||
/* When offline, dim games that are not downloaded (cannot be played). */
|
||||
body.offline .card:not(.avail) { opacity: .35; pointer-events: none; }
|
||||
.thumb-wrap { width: 100%; aspect-ratio: 3/4; background: #0d1527;
|
||||
display: flex; align-items: center; justify-content: center; overflow: hidden; }
|
||||
.thumb-wrap img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
@@ -335,31 +444,28 @@ LAUNCHER_HTML = ("""\
|
||||
display: -webkit-box; -webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical; overflow: hidden; }
|
||||
.card-sys { font-size: .65rem; color: #9ab; margin-top: .2rem; text-transform: uppercase; }
|
||||
.star {
|
||||
position: absolute; top: .4rem; right: .4rem; z-index: 1;
|
||||
.star, .dl {
|
||||
position: absolute; top: .4rem; z-index: 1;
|
||||
background: rgba(0,0,0,.55); border: none; border-radius: 50%;
|
||||
width: 2rem; height: 2rem; font-size: 1rem; line-height: 1; cursor: pointer;
|
||||
color: #888; display: flex; align-items: center; justify-content: center; padding: 0;
|
||||
transition: background .15s, color .15s;
|
||||
}
|
||||
.star:hover { background: rgba(0,0,0,.85); }
|
||||
.star { right: .4rem; }
|
||||
.dl { left: .4rem; }
|
||||
.star:hover, .dl:hover { background: rgba(0,0,0,.85); }
|
||||
.star.fav { color: #f5c518; }
|
||||
.cache-dot {
|
||||
display: none; position: absolute; bottom: .4rem; left: .4rem;
|
||||
width: .55rem; height: .55rem; border-radius: 50%; background: #2ecc71;
|
||||
title: "Cached for offline";
|
||||
}
|
||||
.dl.done { color: #2ecc71; }
|
||||
.empty { color: #555; grid-column: 1 / -1; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="offline-banner">Offline — saves will sync when reconnected</div>
|
||||
<div id="offline-banner">Offline — showing downloaded games; saves will sync when reconnected</div>
|
||||
<h1>Game Library</h1>
|
||||
<div id="dbg-bar">SW: checking… | Online: checking…</div>
|
||||
<input id="search" type="search" placeholder="Search…" autocomplete="off" spellcheck="false">
|
||||
<div class="grid" id="grid"><p class="empty">Loading…</p></div>
|
||||
<script>
|
||||
""" + _IDB_JS + """
|
||||
""" + _IDB_JS + _SHELL_CACHE_JS + """
|
||||
var allGames = [];
|
||||
var favSet = new Set();
|
||||
|
||||
@@ -383,13 +489,14 @@ function card(g) {
|
||||
+ '<div class="card-title">' + esc(g.title) + '</div>'
|
||||
+ '<div class="card-sys">' + esc(g.system) + '</div>'
|
||||
+ '</div>'
|
||||
+ '<button class="dl" data-name="' + esc(g.name) + '" data-title="' + esc(g.title) + '"'
|
||||
+ ' onclick="toggleDownload(event,this)" title="Download for offline">⬇</button>'
|
||||
+ '<button class="star' + (isFav ? ' fav' : '') + '"'
|
||||
+ ' data-name="' + esc(g.name) + '"'
|
||||
+ ' onclick="toggleFav(event,this)"'
|
||||
+ ' title="' + (isFav ? 'Remove from favourites' : 'Add to favourites') + '">'
|
||||
+ (isFav ? '★' : '☆')
|
||||
+ '</button>'
|
||||
+ '<span class="cache-dot" title="Cached for offline"></span>'
|
||||
+ '</a>';
|
||||
}
|
||||
|
||||
@@ -414,7 +521,7 @@ function render(q) {
|
||||
others.forEach(function(g) { html += card(g); });
|
||||
|
||||
document.getElementById('grid').innerHTML = html;
|
||||
updateCacheStatus();
|
||||
refreshOffline();
|
||||
}
|
||||
|
||||
async function toggleFav(e, btn) {
|
||||
@@ -427,46 +534,73 @@ async function toggleFav(e, btn) {
|
||||
await fetch('/favorites/' + encodeURIComponent(name), { method: adding ? 'POST' : 'DELETE' });
|
||||
}
|
||||
|
||||
function setDownloaded(btn, done) {
|
||||
btn.textContent = done ? '✓' : '⬇';
|
||||
btn.classList.toggle('done', done);
|
||||
btn.title = done ? 'Downloaded — tap to remove' : 'Download for offline';
|
||||
var cardEl = btn.closest('.card');
|
||||
if (cardEl) cardEl.classList.toggle('avail', done);
|
||||
}
|
||||
|
||||
async function toggleDownload(e, btn) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!('caches' in window)) { alert('Offline caching is not supported in this browser.'); return; }
|
||||
var name = btn.dataset.name;
|
||||
var title = btn.dataset.title;
|
||||
var romReq = '/roms/' + encodeURIComponent(name);
|
||||
var cache = await caches.open('emujs-roms');
|
||||
var have = await cache.match(romReq);
|
||||
var playReq = '/play/' + encodeURIComponent(name);
|
||||
if (have) {
|
||||
await cache.delete(romReq);
|
||||
await cache.delete('/thumbnails/' + encodeURIComponent(title));
|
||||
try { var sh = await caches.open(SHELL_CACHE); await sh.delete(playReq); } catch(_) {}
|
||||
setDownloaded(btn, false);
|
||||
return;
|
||||
}
|
||||
btn.disabled = true;
|
||||
btn.textContent = '…';
|
||||
try {
|
||||
await cache.add(romReq);
|
||||
try { await cache.add('/thumbnails/' + encodeURIComponent(title)); } catch(_) {}
|
||||
// Cache the player document too so the page renders offline. The emulator
|
||||
// core itself is cached separately, when the game is first played online.
|
||||
try { var shell = await caches.open(SHELL_CACHE); await shell.add(playReq); } catch(_) {}
|
||||
setDownloaded(btn, true);
|
||||
} catch(err) {
|
||||
alert('Download failed: ' + err);
|
||||
setDownloaded(btn, false);
|
||||
}
|
||||
btn.disabled = false;
|
||||
}
|
||||
|
||||
async function refreshOffline() {
|
||||
if (!('caches' in window)) return;
|
||||
try {
|
||||
var cache = await caches.open('emujs-roms');
|
||||
var keys = await cache.keys();
|
||||
var have = new Set(
|
||||
keys.map(function(r) { return decodeURIComponent(new URL(r.url).pathname); })
|
||||
.filter(function(p) { return p.indexOf('/roms/') === 0 && p !== '/roms/'; })
|
||||
.map(function(p) { return p.slice('/roms/'.length); })
|
||||
);
|
||||
document.querySelectorAll('.dl[data-name]').forEach(function(btn) {
|
||||
setDownloaded(btn, have.has(btn.dataset.name));
|
||||
});
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
function updateOnline() {
|
||||
document.body.classList.toggle('offline', !navigator.onLine);
|
||||
if (navigator.onLine) syncPendingSaves();
|
||||
}
|
||||
|
||||
document.getElementById('search').addEventListener('input', function() {
|
||||
render(this.value);
|
||||
});
|
||||
|
||||
async function updateCacheStatus() {
|
||||
if (!('caches' in window)) return;
|
||||
try {
|
||||
const cache = await caches.open('emulatorjs-v4');
|
||||
const keys = await cache.keys();
|
||||
const cached = new Set(
|
||||
keys.map(function(r) {
|
||||
return decodeURIComponent(new URL(r.url).pathname);
|
||||
}).filter(function(p) {
|
||||
return p.startsWith('/roms/');
|
||||
}).map(function(p) {
|
||||
return p.slice('/roms/'.length);
|
||||
})
|
||||
);
|
||||
document.querySelectorAll('.card[data-rom]').forEach(function(card) {
|
||||
if (cached.has(card.dataset.rom)) {
|
||||
card.querySelector('.cache-dot').style.display = 'block';
|
||||
}
|
||||
});
|
||||
return cached;
|
||||
} catch(e) { return new Set(); }
|
||||
}
|
||||
|
||||
async function updateDbgBar() {
|
||||
var swReg = 'none', swCtrl = 'NO';
|
||||
if ('serviceWorker' in navigator) {
|
||||
var reg = await navigator.serviceWorker.getRegistration('/');
|
||||
if (reg) swReg = reg.active ? 'active' : (reg.installing ? 'installing' : 'waiting');
|
||||
if (navigator.serviceWorker.controller) swCtrl = 'YES';
|
||||
}
|
||||
var cached = await updateCacheStatus();
|
||||
var dbg = document.getElementById('dbg-bar');
|
||||
dbg.textContent = 'SW reg: ' + swReg + ' ctrl: ' + swCtrl
|
||||
+ ' | Online: ' + (navigator.onLine ? 'yes' : 'NO')
|
||||
+ ' | Cached ROMs: ' + (cached ? cached.size : '?');
|
||||
}
|
||||
window.addEventListener('online', updateOnline);
|
||||
window.addEventListener('offline', updateOnline);
|
||||
|
||||
Promise.all([
|
||||
fetch('/roms/').then(function(r) { return r.json(); }),
|
||||
@@ -475,19 +609,8 @@ Promise.all([
|
||||
allGames = results[0];
|
||||
favSet = new Set(results[1]);
|
||||
render(document.getElementById('search').value);
|
||||
updateDbgBar();
|
||||
});
|
||||
|
||||
window.addEventListener('online', function() {
|
||||
document.getElementById('offline-banner').style.display = 'none';
|
||||
syncPendingSaves();
|
||||
updateDbgBar();
|
||||
});
|
||||
window.addEventListener('offline', function() {
|
||||
document.getElementById('offline-banner').style.display = '';
|
||||
updateDbgBar();
|
||||
});
|
||||
if (!navigator.onLine) { document.getElementById('offline-banner').style.display = ''; }
|
||||
updateOnline();
|
||||
""" + _SW_REG + """\
|
||||
</script>
|
||||
</body>
|
||||
@@ -501,6 +624,7 @@ PLAYER_TMPL = Template("""\
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>$title</title>
|
||||
""" + PWA_HEAD + """
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { background: #000; }
|
||||
@@ -532,7 +656,7 @@ PLAYER_TMPL = Template("""\
|
||||
<script>
|
||||
const GAME = $game_json;
|
||||
const SAVE_URL = '/saves/' + encodeURIComponent(GAME.name);
|
||||
""" + _IDB_JS + """
|
||||
""" + _IDB_JS + _SHELL_CACHE_JS + _CACHE_STATIC_JS + """
|
||||
function showOfflineBanner(msg) {
|
||||
var b = document.getElementById('offline-banner');
|
||||
b.textContent = msg || 'Offline — saves will sync when reconnected';
|
||||
@@ -540,48 +664,8 @@ function showOfflineBanner(msg) {
|
||||
}
|
||||
function hideOfflineBanner() { document.getElementById('offline-banner').style.display = 'none'; }
|
||||
|
||||
async function preflightCheck() {
|
||||
void('1/4 start');
|
||||
try {
|
||||
var swReg = 'none', swCtrl = 'NO';
|
||||
if ('serviceWorker' in navigator) {
|
||||
void('2/4 SW reg…');
|
||||
const reg = await navigator.serviceWorker.getRegistration('/');
|
||||
if (reg) swReg = reg.active ? 'active' : (reg.installing ? 'installing' : 'waiting');
|
||||
if (navigator.serviceWorker.controller) swCtrl = 'YES';
|
||||
}
|
||||
|
||||
void('3/4 cache…');
|
||||
var romCached = false, romInfo = 'NOT in cache';
|
||||
if ('caches' in window) {
|
||||
const cache = await caches.open('emulatorjs-v4');
|
||||
const hit = await cache.match('/roms/' + encodeURIComponent(GAME.name));
|
||||
if (hit) {
|
||||
const cl = hit.headers.get('content-length');
|
||||
const sz = cl ? parseInt(cl) : -1;
|
||||
romCached = sz > 0;
|
||||
romInfo = sz > 0 ? 'cached ' + sz + 'B' : 'in cache but 0B (EMPTY!)';
|
||||
}
|
||||
}
|
||||
|
||||
void('4/4 done — SW: ' + swReg + '/' + swCtrl
|
||||
+ ' | ROM: ' + romInfo
|
||||
+ ' | Online: ' + (navigator.onLine ? 'yes' : 'NO')
|
||||
+ '\n' + GAME.name);
|
||||
|
||||
if (!navigator.onLine && !romCached) {
|
||||
showOfflineBanner('Not available offline — open this game while connected to download it.');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch(e) {
|
||||
void('preflight error: ' + e + '\n' + GAME.name);
|
||||
return true; // fail open — try to load EmulatorJS anyway
|
||||
}
|
||||
}
|
||||
|
||||
async function manualSave() {
|
||||
const btn = document.getElementById('save-btn');
|
||||
var btn = document.getElementById('save-btn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Saving...';
|
||||
await pushSave();
|
||||
@@ -591,31 +675,36 @@ async function manualSave() {
|
||||
|
||||
async function pushSave() {
|
||||
try {
|
||||
const data = window.EJS_emulator && window.EJS_emulator.gameManager.getSaveFile();
|
||||
var data = window.EJS_emulator && window.EJS_emulator.gameManager.getSaveFile();
|
||||
if (!data || data.byteLength === 0) return;
|
||||
if (navigator.onLine) {
|
||||
const r = await fetch(SAVE_URL, { method: 'PUT', body: data,
|
||||
headers: { 'Content-Type': 'application/octet-stream' } });
|
||||
if (r.ok) return;
|
||||
var r = await fetch(SAVE_URL, { method: 'PUT', body: data,
|
||||
headers: { 'Content-Type': 'application/octet-stream' } });
|
||||
if (r.ok) { await idbDelete(GAME.name); return; }
|
||||
}
|
||||
// Offline or server rejected — queue locally to sync later.
|
||||
await idbPut(GAME.name, new Uint8Array(data));
|
||||
} catch(e) { console.warn('save failed, stored locally', e); }
|
||||
}
|
||||
|
||||
async function pullSave() {
|
||||
try {
|
||||
let sav;
|
||||
var sav;
|
||||
if (navigator.onLine) {
|
||||
const r = await fetch(SAVE_URL);
|
||||
var r = await fetch(SAVE_URL);
|
||||
if (r.ok) sav = new Uint8Array(await r.arrayBuffer());
|
||||
}
|
||||
if (!sav) sav = await idbGet(GAME.name);
|
||||
if (!sav || sav.byteLength === 0) return;
|
||||
const gm = window.EJS_emulator.gameManager;
|
||||
const path = gm.getSaveFilePath();
|
||||
const parts = path.split('/');
|
||||
let cp = '';
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
// Fall back to an unsynced local save (offline, or newer than the server's).
|
||||
if (!sav || !sav.byteLength) {
|
||||
var local = await idbGet(GAME.name);
|
||||
if (local && local.byteLength) sav = local;
|
||||
}
|
||||
if (!sav || !sav.byteLength) return;
|
||||
var gm = window.EJS_emulator.gameManager;
|
||||
var path = gm.getSaveFilePath();
|
||||
var parts = path.split('/');
|
||||
var cp = '';
|
||||
for (var i = 0; i < parts.length - 1; i++) {
|
||||
if (!parts[i]) continue;
|
||||
cp += '/' + parts[i];
|
||||
if (!gm.FS.analyzePath(cp).exists) gm.FS.mkdir(cp);
|
||||
@@ -631,44 +720,44 @@ window.EJS_gameUrl = '/roms/' + encodeURIComponent(GAME.name);
|
||||
window.EJS_core = GAME.system;
|
||||
window.EJS_pathtodata = '/static/';
|
||||
window.EJS_onGameStart = function() {
|
||||
// Sync offline-queued saves first so server has latest, then pull.
|
||||
// Runs after EmulatorJS is ready so IDB access never blocks startup.
|
||||
// Push any offline-queued saves first so the server has the latest, then pull.
|
||||
// Runs after EmulatorJS is ready so IndexedDB access never blocks startup.
|
||||
(navigator.onLine ? syncPendingSaves().catch(function(){}) : Promise.resolve())
|
||||
.then(function() { return pullSave(); })
|
||||
.then(function() {
|
||||
void('running | Online: ' + (navigator.onLine ? 'yes' : 'NO') + '\n' + GAME.name);
|
||||
setInterval(pushSave, 30000);
|
||||
// Persist the core/assets this game just loaded so it plays offline next
|
||||
// time. Delayed pass catches anything fetched slightly after game start.
|
||||
cacheLoadedStatic();
|
||||
setTimeout(cacheLoadedStatic, 5000);
|
||||
window.addEventListener('pagehide', function() {
|
||||
const data = window.EJS_emulator && window.EJS_emulator.gameManager.getSaveFile();
|
||||
if (data && data.byteLength > 0)
|
||||
var data = window.EJS_emulator && window.EJS_emulator.gameManager.getSaveFile();
|
||||
if (!data || data.byteLength === 0) return;
|
||||
if (navigator.onLine) {
|
||||
navigator.sendBeacon(SAVE_URL, new Blob([data], { type: 'application/octet-stream' }));
|
||||
} else {
|
||||
idbPut(GAME.name, new Uint8Array(data)); // best-effort
|
||||
}
|
||||
});
|
||||
window.addEventListener('online', function() {
|
||||
hideOfflineBanner();
|
||||
cacheLoadedStatic();
|
||||
syncPendingSaves().catch(function(){}).then(function() { pullSave(); });
|
||||
preflightCheck();
|
||||
});
|
||||
window.addEventListener('offline', function() { showOfflineBanner(); preflightCheck(); });
|
||||
window.addEventListener('offline', function() { showOfflineBanner(); });
|
||||
if (!navigator.onLine) showOfflineBanner();
|
||||
});
|
||||
};
|
||||
|
||||
// Preflight: check cache and block if offline + ROM not cached.
|
||||
// loader.js loads immediately after — syncPendingSaves runs inside EJS_onGameStart
|
||||
// so IDB access never holds up the startup path.
|
||||
preflightCheck().then(function(ok) {
|
||||
if (!ok) return;
|
||||
var s = document.createElement('script');
|
||||
s.src = '/static/loader.js';
|
||||
document.body.appendChild(s);
|
||||
}).catch(function(e) {
|
||||
void('startup error: ' + e + '\n' + GAME.name);
|
||||
var s = document.createElement('script');
|
||||
s.src = '/static/loader.js';
|
||||
document.body.appendChild(s);
|
||||
});
|
||||
</script>
|
||||
if (!navigator.onLine) showOfflineBanner();
|
||||
|
||||
// Load EmulatorJS directly — no preflight gate. If the ROM or core is not
|
||||
// cached while offline, EmulatorJS surfaces its own error.
|
||||
var s = document.createElement('script');
|
||||
s.src = '/static/loader.js';
|
||||
document.body.appendChild(s);
|
||||
""" + _SW_REG + """\
|
||||
</script>
|
||||
</body>
|
||||
</html>""")
|
||||
|
||||
@@ -677,10 +766,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
def send_body(self, data: bytes, ct: str, status: int = 200):
|
||||
def send_body(self, data: bytes, ct: str, status: int = 200, extra_headers: dict = None):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", ct)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
for k, v in (extra_headers or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
@@ -762,14 +853,19 @@ class Handler(BaseHTTPRequestHandler):
|
||||
p = self.decoded_path()
|
||||
|
||||
if p == "/sw.js":
|
||||
body = SW_JS.encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/javascript")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Service-Worker-Allowed", "/")
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
self.send_body(
|
||||
SW_JS.encode(), "application/javascript",
|
||||
extra_headers={"Service-Worker-Allowed": "/", "Cache-Control": "no-cache"},
|
||||
)
|
||||
return
|
||||
|
||||
if p == "/manifest.json":
|
||||
self.send_body(MANIFEST_JSON.encode(), "application/manifest+json")
|
||||
return
|
||||
|
||||
if p == "/icon-256.png":
|
||||
self.send_body(ICON_PNG, "image/png",
|
||||
extra_headers={"Cache-Control": "max-age=604800"})
|
||||
return
|
||||
|
||||
if p in ("/", ""):
|
||||
|
||||
Reference in New Issue
Block a user