URLs (handled in MainActivity).
*
* In a plain browser (dev testing, unit harnesses) the fallbacks keep every
@@ -37,7 +42,11 @@ function resolveBridge() {
let bridge = resolveBridge();
export function isNative() {
- if (!bridge) bridge = resolveBridge();
+ // Re-resolve on every probe: the injected Capacitor bridge can appear
+ // AFTER this module is first imported (late bridge injection, test
+ // harnesses installing a fresh fake per case). Never goes back to null
+ // once a bridge has been seen.
+ bridge = resolveBridge() || bridge;
return !!(bridge && typeof bridge.openExternal === 'function');
}
@@ -128,11 +137,29 @@ export const native = {
return { versionName: '', versionCode: 0 };
},
- async downloadAndInstall(url, fileName) {
- if (isNative() && typeof bridge.downloadAndInstall === 'function') return bridge.downloadAndInstall({ url, fileName });
+ async downloadAndInstall(url, fileName, expectedVersionCode = 0) {
+ if (isNative() && typeof bridge.downloadAndInstall === 'function') {
+ return bridge.downloadAndInstall({ url, fileName, expectedVersionCode: Number(expectedVersionCode) || 0 });
+ }
throw new Error('In-app installation is available only in the Android app');
},
+ /**
+ * Live in-app-updater progress from the native downloader:
+ * { phase: 'download' | 'verify' | 'install', bytes, total } — REAL bytes
+ * (total is -1 when the server sends no length). Returns an unsubscribe
+ * function, like onLink; a no-op outside the Android app.
+ */
+ onUpdateProgress(fn) {
+ if (isNative() && typeof bridge.addListener === 'function') {
+ try {
+ const h = bridge.addListener('updateDownloadProgress', (ev) => fn(ev || {}));
+ return () => { try { h.remove && h.remove(); } catch { /* ignore */ } };
+ } catch { return () => {}; }
+ }
+ return () => {};
+ },
+
/** Save a direct .pdf to the device Downloads via DownloadManager. */
async download(url, fileName) {
const safe = httpUrl(url);
diff --git a/android-app/www/js/update.js b/android-app/www/js/update.js
index 249bd7d..d234fa5 100644
--- a/android-app/www/js/update.js
+++ b/android-app/www/js/update.js
@@ -12,11 +12,67 @@ export async function checkForUpdate({ force = false, ui = null } = {}) {
lastCheck = Date.now();
try { const installed = await native.getAppVersion(); const r = await fetch(`${WORKER_ORIGIN}/api/app-update`, { headers: { Accept: 'application/json' } }); const update = parseUpdate(await r.json(), Number(installed.versionCode)); if (update && ui) showUpdate(update, ui); return update; } catch { return null; }
}
+
+// The native layer now ALWAYS answers downloadAndInstall exactly once
+// (resolve or reject, even on internal errors). The watchdog below is the
+// belt-and-braces for a wedged bridge: the updater UI must never park on
+// "Downloading…" indefinitely. (Test hook lets the suite shrink the window.)
+let watchdogMs = 90000;
+export function _setUpdateWatchdogMs(ms) { watchdogMs = Number(ms) > 0 ? Number(ms) : 90000; }
+
+const mb = (b) => (b / 1e6).toFixed(2);
+const humanError = (e) => String((e && e.message) || e || 'Update failed').replace(/^[A-Z0-9_]+:\s*/, '') || 'Update failed';
+
function showUpdate(update, ui) {
const notes = update.releaseNotes.length ? `${update.releaseNotes.map(x => `- ${escapeHtml(x)}
`).join('')}
` : 'Bug fixes and improvements.
';
const buttons = update.mandatory ? '' : '';
ui.sheet({ title: 'Update Available', content: `DSMNRU PYQ v${escapeHtml(update.version)}
${notes}${buttons}
` });
document.querySelector('#update-later')?.addEventListener('click', () => ui.closeSheet());
- document.querySelector('#update-now')?.addEventListener('click', async () => { const b=document.querySelector('#update-now'); b.disabled=true; b.textContent='Downloading…'; try { await native.downloadAndInstall(update.downloadUrl, `dsmnru-pyq-${update.version}.apk`); } catch (e) { b.disabled=false; b.textContent='Try again'; ui.toast(e.message || 'Update failed', 'err'); } });
+ document.querySelector('#update-now')?.addEventListener('click', () => runInstall(update, ui));
+}
+
+/**
+ * One install attempt, driven by the native layer's REAL phases:
+ * Downloading… (actual bytes) → Verifying… → Starting installer… → then the
+ * button leaves the busy state for good. Every failure — download,
+ * verification, permission, or installer launch — resolves into a re-enabled
+ * retry button plus a toast, so the UI can never stick on "Downloading…".
+ */
+async function runInstall(update, ui) {
+ const b = document.querySelector('#update-now');
+ if (!b || b.dataset.busy === '1') return;
+ b.dataset.busy = '1';
+ b.disabled = true;
+ b.textContent = 'Downloading…';
+ let settled = false;
+ let watchdog = 0;
+ let stopProgress = () => {};
+ const stall = () => fail(new Error('UPDATE_WATCHDOG: update is taking too long — check your connection and try again'));
+ const arm = () => { clearTimeout(watchdog); watchdog = setTimeout(stall, watchdogMs); };
+ const settle = (after) => { if (settled) return; settled = true; clearTimeout(watchdog); stopProgress(); delete b.dataset.busy; if (after) after(); };
+ const fail = (e) => settle(() => {
+ b.disabled = false;
+ b.textContent = /INSTALL_PERMISSION_REQUIRED/.test(String((e && e.message) || '')) ? 'Enable installs & try again' : 'Try again';
+ ui.toast(humanError(e), 'err');
+ });
+ stopProgress = native.onUpdateProgress((ev) => {
+ if (settled || !ev) return;
+ if (ev.phase === 'download') b.textContent = ev.total > 0 ? `Downloading… ${mb(ev.bytes)} / ${mb(ev.total)} MB` : `Downloading… ${mb(ev.bytes)} MB`;
+ else if (ev.phase === 'verify') b.textContent = 'Verifying…';
+ else if (ev.phase === 'install') b.textContent = 'Starting installer…';
+ if (ev.phase) arm(); // native is alive — keep deferring the watchdog
+ });
+ arm();
+ try {
+ await native.downloadAndInstall(update.downloadUrl, `dsmnru-pyq-${update.version}.apk`, update.versionCode);
+ settle(() => {
+ // The system install screen is up (or the user was taken to the exact
+ // settings screen to allow installs). Reopening is instant — the
+ // verified APK stays cached — so a cancelled installer can be
+ // relaunched from this same button instead of a dead end.
+ b.disabled = false;
+ b.textContent = 'Open installer';
+ });
+ } catch (e) { fail(e); }
}
function escapeHtml(s) { return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }