Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(native): start without the server on Android and keep the offline start on iOS

Mauricec23518dae013
diff --git a/client/android/app/proguard-rules.pro b/client/android/app/proguard-rules.pro
index 79e4063a5..4d682b551 100644
--- a/client/android/app/proguard-rules.pro
+++ b/client/android/app/proguard-rules.pro
@@ -36,3 +36,10 @@
@android.webkit.JavascriptInterface <methods>;
}
-keep public class * extends com.getcapacitor.Plugin
+
+# The stored copy of the server's UI gets Capacitor's bridge the way the
+# server's own page does (TrekOfflineShell.withBridge reads it by reflection).
+-keepclassmembers class com.getcapacitor.Bridge {
+ private com.getcapacitor.JSInjector getJSInjector();
+}
+-keep class com.getcapacitor.JSInjector { public *; }
diff --git a/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java b/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java
index ba98aaf9c..ff9238f4c 100644
--- a/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java
+++ b/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java
@@ -34,7 +34,18 @@ public class MainActivity extends BridgeActivity {
// runs and on its own origin. BridgeActivity reads `config` while it
// builds the bridge inside super.onCreate().
boolean restarting = TrekServerStore.consumeRestart(this);
- TrekServerStore.recheckAfterUpdate(this);
+ // Without a network the server cannot answer: with a copy of its UI the
+ // app starts on that at once (TrekOfflineShell), as it does when the
+ // address screen found the server out of reach. The check an update asks
+ // for waits for a launch that can reach the server.
+ boolean offlineStart = TrekServerStore.consumeOfflineStart(this)
+ || (!TrekOfflineShell.hasNetwork(this) && TrekOfflineShell.hasCopy(this, TrekServerStore.getUrlOrPrevious(this)));
+ if (offlineStart && TrekOfflineShell.hasCopy(this, TrekServerStore.getUrlOrPrevious(this))) {
+ TrekServerStore.restoreForOffline(this);
+ TrekOfflineShell.activate();
+ } else {
+ TrekServerStore.recheckAfterUpdate(this);
+ }
String server = TrekServerStore.getUrl(this);
boolean onServer = server != null && !TrekServerStore.consumeShellOnce(this);
config = TrekServerStore.configFor(this, onServer ? server : null, restarting);
diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekOfflineShell.java b/client/android/app/src/main/java/com/liketrek/trek/TrekOfflineShell.java
new file mode 100644
index 000000000..722528b40
--- /dev/null
+++ b/client/android/app/src/main/java/com/liketrek/trek/TrekOfflineShell.java
@@ -0,0 +1,265 @@
+package com.liketrek.trek;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.Network;
+import android.net.NetworkCapabilities;
+import android.net.Uri;
+import android.util.Log;
+import android.webkit.WebResourceRequest;
+import android.webkit.WebResourceResponse;
+import com.getcapacitor.Bridge;
+import com.getcapacitor.JSInjector;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/**
+ * The server's UI kept on the device, so the app starts without its server: on
+ * a trip without reception, or away from home with a server on the home
+ * network. The web view runs no service worker on a plain-http server, the
+ * usual address of a server at home, so the app keeps the start page and every
+ * file of the build itself (refreshed by native/offlineShell.ts while the
+ * server is reachable) and serves them under the server's own origin while it
+ * is not. The data comes from the UI's own offline store; the API is tried as
+ * usual and answers again once the server is back.
+ */
+final class TrekOfflineShell {
+
+ private static final String DIR = "offline-shell";
+ private static final String PAGE = "index.html";
+ private static final String STAMP = "server.txt";
+ private static final String FILES = "files";
+ /** A path of the build: no "..", no query, nothing outside the copy's folder. */
+ private static final Pattern SAFE_PATH = Pattern.compile("^[A-Za-z0-9._@\\-]+(?:/[A-Za-z0-9._@\\-]+)*$");
+ private static final Map<String, String> TYPES = new HashMap<>();
+
+ static {
+ TYPES.put("js", "text/javascript");
+ TYPES.put("mjs", "text/javascript");
+ TYPES.put("css", "text/css");
+ TYPES.put("json", "application/json");
+ TYPES.put("webmanifest", "application/manifest+json");
+ TYPES.put("svg", "image/svg+xml");
+ TYPES.put("png", "image/png");
+ TYPES.put("jpg", "image/jpeg");
+ TYPES.put("jpeg", "image/jpeg");
+ TYPES.put("webp", "image/webp");
+ TYPES.put("ico", "image/x-icon");
+ TYPES.put("woff", "font/woff");
+ TYPES.put("woff2", "font/woff2");
+ TYPES.put("ttf", "font/ttf");
+ TYPES.put("wasm", "application/wasm");
+ TYPES.put("html", "text/html");
+ }
+
+ /** The UI comes from the copy in this run: the server did not answer when the app started. */
+ private static volatile boolean active;
+ private static volatile JSInjector injector;
+ private static volatile boolean injectorLooked;
+
+ private TrekOfflineShell() {}
+
+ static boolean isActive() {
+ return active;
+ }
+
+ static void activate() {
+ active = true;
+ }
+
+ private static File root(Context context) {
+ return new File(context.getFilesDir(), DIR);
+ }
+
+ /** Whether there is a copy of this server's UI to start from. */
+ static boolean hasCopy(Context context, String server) {
+ if (server == null) return false;
+ File page = new File(root(context), PAGE);
+ return page.isFile() && server.equals(readStamp(context));
+ }
+
+ /** Whether the device has a network at all; with none, the server cannot answer and the copy starts at once. */
+ static boolean hasNetwork(Context context) {
+ try {
+ ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+ if (cm == null) return true;
+ Network network = cm.getActiveNetwork();
+ if (network == null) return false;
+ NetworkCapabilities caps = cm.getNetworkCapabilities(network);
+ return caps != null && caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
+ } catch (RuntimeException e) {
+ return true;
+ }
+ }
+
+ /** Keeps the start page; a copy of another server is thrown away first. */
+ static boolean savePage(Context context, String server, byte[] html) {
+ if (!server.equals(readStamp(context))) clear(context);
+ File dir = root(context);
+ if (!dir.isDirectory() && !dir.mkdirs()) return false;
+ return write(new File(dir, STAMP), server.getBytes(StandardCharsets.UTF_8)) && write(new File(dir, PAGE), html);
+ }
+
+ static boolean hasFile(Context context, String path) {
+ File file = fileFor(context, path);
+ return file != null && file.isFile();
+ }
+
+ static boolean saveFile(Context context, String path, byte[] data) {
+ File file = fileFor(context, path);
+ if (file == null) return false;
+ File parent = file.getParentFile();
+ if (parent != null && !parent.isDirectory() && !parent.mkdirs()) return false;
+ return write(file, data);
+ }
+
+ /** Drops the files of older builds once the current one is complete. */
+ static void prune(Context context, Set<String> keep) {
+ File base = new File(root(context), FILES);
+ pruneDir(base, base, keep);
+ }
+
+ static void clear(Context context) {
+ active = false;
+ deleteTree(root(context));
+ }
+
+ /**
+ * The copy's answer for a request of the server's UI while it is active:
+ * the start page for any page of the app (it routes itself), with
+ * Capacitor's bridge injected as into the server's own page, and a file of
+ * the build by its path. Null for anything else, which goes on as usual.
+ */
+ static WebResourceResponse serve(Context context, Bridge bridge, String server, WebResourceRequest request) {
+ if (!active || server == null || !"GET".equalsIgnoreCase(request.getMethod())) return null;
+ Uri url = request.getUrl();
+ Uri origin = Uri.parse(server);
+ if (!sameOrigin(url, origin)) return null;
+ try {
+ if (request.isForMainFrame()) {
+ File page = new File(root(context), PAGE);
+ if (!page.isFile()) return null;
+ InputStream html = withBridge(bridge, new FileInputStream(page));
+ return response("text/html", html);
+ }
+ String path = url.getPath();
+ if (path == null) return null;
+ File file = fileFor(context, path);
+ if (file == null || !file.isFile()) return null;
+ return response(typeOf(path), new FileInputStream(file));
+ } catch (IOException e) {
+ Log.w("TrekShell", "Offline copy could not answer " + url, e);
+ return null;
+ }
+ }
+
+ private static WebResourceResponse response(String type, InputStream body) {
+ Map<String, String> headers = new HashMap<>();
+ headers.put("Cache-Control", "no-store");
+ String charset = type.startsWith("text/") || type.endsWith("json") ? "utf-8" : null;
+ return new WebResourceResponse(type, charset, 200, "OK", headers, body);
+ }
+
+ /**
+ * Capacitor injects its bridge into the server's page as it passes through;
+ * the copy gets the same script. Its builder is internal to Capacitor, hence
+ * the reflection (kept in proguard-rules.pro). Without it the UI still runs,
+ * as it would in a browser, just without the app's native parts.
+ */
+ private static InputStream withBridge(Bridge bridge, InputStream html) {
+ if (!injectorLooked) {
+ injectorLooked = true;
+ try {
+ Method method = Bridge.class.getDeclaredMethod("getJSInjector");
+ method.setAccessible(true);
+ Object built = method.invoke(bridge);
+ if (built instanceof JSInjector) injector = (JSInjector) built;
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ Log.w("TrekShell", "No bridge for the offline copy", e);
+ }
+ }
+ JSInjector current = injector;
+ return current == null ? html : current.getInjectedStream(html);
+ }
+
+ private static boolean sameOrigin(Uri a, Uri b) {
+ if (a.getScheme() == null || b.getScheme() == null || a.getHost() == null || b.getHost() == null) return false;
+ return a.getScheme().equalsIgnoreCase(b.getScheme())
+ && a.getHost().equalsIgnoreCase(b.getHost())
+ && port(a) == port(b);
+ }
+
+ private static int port(Uri uri) {
+ if (uri.getPort() != -1) return uri.getPort();
+ return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80;
+ }
+
+ private static File fileFor(Context context, String path) {
+ String clean = path.startsWith("/") ? path.substring(1) : path;
+ if (clean.isEmpty() || clean.contains("..") || !SAFE_PATH.matcher(clean).matches()) return null;
+ return new File(new File(root(context), FILES), clean);
+ }
+
+ private static String typeOf(String path) {
+ int dot = path.lastIndexOf('.');
+ String ext = dot < 0 ? "" : path.substring(dot + 1).toLowerCase(Locale.ROOT);
+ String type = TYPES.get(ext);
+ return type == null ? "application/octet-stream" : type;
+ }
+
+ private static String readStamp(Context context) {
+ File stamp = new File(root(context), STAMP);
+ if (!stamp.isFile()) return null;
+ try (FileInputStream in = new FileInputStream(stamp)) {
+ byte[] data = new byte[(int) Math.min(stamp.length(), 4096)];
+ int read = in.read(data);
+ return read <= 0 ? null : new String(data, 0, read, StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ /** Written beside the target and moved over it, so a cut-off write never leaves half a file. */
+ private static boolean write(File target, byte[] data) {
+ File temp = new File(target.getPath() + ".part");
+ try (FileOutputStream out = new FileOutputStream(temp)) {
+ out.write(data);
+ out.getFD().sync();
+ } catch (IOException e) {
+ temp.delete();
+ return false;
+ }
+ return temp.renameTo(target);
+ }
+
+ private static void pruneDir(File base, File dir, Set<String> keep) {
+ File[] children = dir.listFiles();
+ if (children == null) return;
+ for (File child : children) {
+ if (child.isDirectory()) {
+ pruneDir(base, child, keep);
+ String[] left = child.list();
+ if (left != null && left.length == 0) child.delete();
+ } else {
+ String relative = base.toURI().relativize(child.toURI()).getPath();
+ if (!keep.contains(relative)) child.delete();
+ }
+ }
+ }
+
+ private static void deleteTree(File file) {
+ File[] children = file.listFiles();
+ if (children != null) for (File child : children) deleteTree(child);
+ file.delete();
+ }
+}
diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java b/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java
index a61fcfaf0..84ce945c0 100644
--- a/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java
+++ b/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java
@@ -38,6 +38,7 @@ final class TrekServerStore {
private static final String KEY_SIGN_IN_HOSTS = "sign_in_hosts";
private static final String KEY_SHELL_ONCE = "shell_once";
private static final String KEY_RESTART = "restart";
+ private static final String KEY_OFFLINE_START = "offline_start";
private static final String KEY_WELCOME = "welcome";
private static final String CONFIG_DIR = "trek-server-config";
@@ -191,6 +192,37 @@ final class TrekServerStore {
return consume(context, KEY_RESTART);
}
+ /** The next onCreate starts on the stored copy of the server's UI (TrekOfflineShell). */
+ static void markOfflineStart(Context context) {
+ prefs(context).edit().putBoolean(KEY_OFFLINE_START, true).commit();
+ }
+
+ static boolean consumeOfflineStart(Context context) {
+ return consume(context, KEY_OFFLINE_START);
+ }
+
+ /**
+ * The remembered server, or the one an update asked to check again: the
+ * server the stored copy of the UI belongs to.
+ */
+ static String getUrlOrPrevious(Context context) {
+ String url = getUrl(context);
+ return url != null ? url : getPreviousUrl(context);
+ }
+
+ /**
+ * Starting on the stored copy while the check an update asked for could not
+ * run: the server goes back in place, unchecked for now, and the check runs
+ * again on the next launch, which reaches the server.
+ */
+ static void restoreForOffline(Context context) {
+ SharedPreferences prefs = prefs(context);
+ if (prefs.getString(KEY_URL, null) != null) return;
+ String previous = prefs.getString(KEY_PREVIOUS_URL, null);
+ if (previous == null) return;
+ prefs.edit().putString(KEY_URL, previous).remove(KEY_PREVIOUS_URL).putInt(KEY_SERVER_CHECK, 0).commit();
+ }
+
private static boolean consume(Context context, String key) {
boolean set = prefs(context).getBoolean(key, false);
if (set) prefs(context).edit().remove(key).commit();
diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java
index b4eac2759..da4df1069 100644
--- a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java
+++ b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java
@@ -526,19 +526,95 @@ public class TrekShellPlugin extends Plugin {
authBrowserOpen = false;
}
- /** iOS only: Android keeps the service worker, which already starts TREK offline. */
+ /**
+ * Keeps the server's UI on the device for a start without the server
+ * (TrekOfflineShell): the start page, and each file of the build that
+ * native/offlineShell.ts lists from the server's manifest and the copy does
+ * not hold yet. Once all of them are there, files of older builds go. A web
+ * view runs no service worker on a plain-http server, the usual address of a
+ * server at home, so without this the app could not start away from it.
+ */
@PluginMethod
public void refreshOfflineCopy(PluginCall call) {
- JSObject result = new JSObject();
- result.put("saved", false);
- call.resolve(result);
+ Context context = getContext();
+ String server = TrekServerStore.getUrl(context);
+ JSArray listed = call.getArray("files");
+ if (server == null || TrekOfflineShell.isActive()) {
+ JSObject result = new JSObject();
+ result.put("saved", false);
+ call.resolve(result);
+ return;
+ }
+ new Thread(() -> {
+ JSObject result = new JSObject();
+ byte[] page = download(server, "", "text/html");
+ boolean saved = page != null && TrekOfflineShell.savePage(context, server, page);
+ boolean complete = saved;
+ if (saved && listed != null) {
+ Set<String> keep = new HashSet<>();
+ for (int i = 0; i < listed.length(); i++) {
+ String path = listed.optString(i, null);
+ if (path == null || path.isEmpty()) continue;
+ String clean = path.startsWith("/") ? path.substring(1) : path;
+ keep.add(clean);
+ if (TrekOfflineShell.hasFile(context, clean)) continue;
+ byte[] data = download(server, clean, null);
+ if (data == null || !TrekOfflineShell.saveFile(context, clean, data)) complete = false;
+ }
+ if (complete) TrekOfflineShell.prune(context, keep);
+ }
+ result.put("saved", saved);
+ result.put("complete", complete);
+ call.resolve(result);
+ }).start();
+ }
+
+ /** A file of the server's UI, or null: only a 200 counts, and the page only as HTML. */
+ private static byte[] download(String server, String path, String wantType) {
+ java.net.HttpURLConnection connection = null;
+ try {
+ java.net.URL base = new java.net.URL(server.endsWith("/") ? server : server + "/");
+ java.net.URL url = new java.net.URL(base, path);
+ connection = (java.net.HttpURLConnection) url.openConnection();
+ connection.setConnectTimeout(15000);
+ connection.setReadTimeout(30000);
+ connection.setInstanceFollowRedirects(true);
+ if (wantType != null) connection.setRequestProperty("Accept", wantType);
+ if (connection.getResponseCode() != 200) return null;
+ String type = connection.getContentType();
+ if (wantType != null && (type == null || !type.startsWith(wantType))) return null;
+ try (java.io.InputStream in = connection.getInputStream()) {
+ java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
+ byte[] buffer = new byte[16384];
+ for (int n = in.read(buffer); n > 0; n = in.read(buffer)) out.write(buffer, 0, n);
+ return out.toByteArray();
+ }
+ } catch (java.io.IOException | RuntimeException e) {
+ return null;
+ } finally {
+ if (connection != null) connection.disconnect();
+ }
}
+ /**
+ * The address screen found the server out of reach: with a copy of its UI
+ * the app restarts on that instead (TrekOfflineShell), the same way it
+ * leaves the server for the address screen. Also for the server an update
+ * asked to check again, whose check then waits for the next launch.
+ */
@PluginMethod
public void openOfflineCopy(PluginCall call) {
+ Context context = getContext();
JSObject result = new JSObject();
- result.put("opened", false);
+ if (!TrekOfflineShell.hasCopy(context, TrekServerStore.getUrlOrPrevious(context)) || getActivity() == null) {
+ result.put("opened", false);
+ call.resolve(result);
+ return;
+ }
+ TrekServerStore.markOfflineStart(context);
+ result.put("opened", true);
call.resolve(result);
+ restart();
}
// ---- Widgets, shortcuts and the travel day ----
diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java b/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java
index a015ec889..472b0e6a2 100644
--- a/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java
+++ b/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java
@@ -40,6 +40,7 @@ class TrekWebViewClient extends BridgeWebViewClient {
private boolean retriedMainFrame;
/** The page loaded again after a network error, until that load starts: its error page counts for nothing. */
private String retryUrl;
+ private final Bridge bridge;
TrekWebViewClient(
Bridge bridge,
@@ -49,6 +50,7 @@ class TrekWebViewClient extends BridgeWebViewClient {
Set<String> signInHosts
) {
super(bridge);
+ this.bridge = bridge;
this.onUnreachable = onUnreachable;
this.onSignInPage = onSignInPage;
this.onErrorPage = onErrorPage;
@@ -115,9 +117,15 @@ class TrekWebViewClient extends BridgeWebViewClient {
return signInHosts.contains(key) || (url.getPort() != -1 && signInHosts.contains(key + ":" + url.getPort()));
}
- /** Mapbox's map resources go through the app's own store (tiles/TrekTileStore.kt). */
+ /**
+ * Mapbox's map resources go through the app's own store (tiles/TrekTileStore.kt),
+ * and while the server is out of reach the UI comes from its stored copy
+ * (TrekOfflineShell).
+ */
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
+ WebResourceResponse copy = TrekOfflineShell.serve(view.getContext(), bridge, TrekServerStore.getUrl(view.getContext()), request);
+ if (copy != null) return copy;
if (com.liketrek.trek.tiles.TrekTileStore.INSTANCE.handles(request)) {
WebResourceResponse stored = com.liketrek.trek.tiles.TrekTileStore.INSTANCE.serve(request);
if (stored != null) return stored;
@@ -171,6 +179,15 @@ class TrekWebViewClient extends BridgeWebViewClient {
}, 1500);
return;
}
+ // Out of reach for good (a trip without reception, a server at home):
+ // the stored copy of the UI takes over, with the app's own offline data.
+ String server = TrekServerStore.getUrl(view.getContext());
+ if (isNetworkError(error.getErrorCode()) && !TrekOfflineShell.isActive() && TrekOfflineShell.hasCopy(view.getContext(), server)) {
+ TrekOfflineShell.activate();
+ String url = request.getUrl().toString();
+ view.post(() -> view.loadUrl(url));
+ return;
+ }
TrekServerStore.setFailure(view.getContext(), error.getDescription() + " (" + error.getErrorCode() + ")");
onUnreachable.run();
return;
diff --git a/client/ios/App/App/TrekBridgeViewController.swift b/client/ios/App/App/TrekBridgeViewController.swift
index 6131b70d1..7d61fcd21 100644
--- a/client/ios/App/App/TrekBridgeViewController.swift
+++ b/client/ios/App/App/TrekBridgeViewController.swift
@@ -455,10 +455,26 @@ enum TrekServerStore {
guard defaults.integer(forKey: checkedKey) < serverCheck else { return }
defaults.set(serverCheck, forKey: checkedKey)
guard let server = url else { return }
- url = nil
+ // Not through `url`, which throws the offline copy away: it still belongs
+ // to this server, and is what the app starts on if the check cannot run.
+ defaults.removeObject(forKey: key)
+ defaults.removeObject(forKey: signInHostsKey)
defaults.set(server, forKey: previousKey)
}
+ /// The check an update asked for cannot run (the server is out of reach),
+ /// but there is a copy of its UI: the server goes back in place, unchecked
+ /// for now, and the check runs again on the next launch.
+ static func restoreForOffline() -> Bool {
+ let defaults = UserDefaults.standard
+ guard url == nil, let previous = previousURL,
+ FileManager.default.fileExists(atPath: offlineCopyURL.path) else { return false }
+ defaults.set(previous, forKey: key)
+ defaults.removeObject(forKey: previousKey)
+ defaults.set(0, forKey: checkedKey)
+ return true
+ }
+
/// The server an update asked to check again, until a server is set.
static var previousURL: String? {
UserDefaults.standard.string(forKey: previousKey)
diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift
index af823bd37..ee63e01ff 100644
--- a/client/ios/App/App/TrekShellPlugin.swift
+++ b/client/ios/App/App/TrekShellPlugin.swift
@@ -477,6 +477,18 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
}
@objc func openOfflineCopy(_ call: CAPPluginCall) {
+ // The server an update asked to check again, out of reach: back to it on
+ // its copy. The new bridge loads the server, fails, and this screen comes
+ // back with the server set, which then opens the copy below.
+ if TrekServerStore.url == nil {
+ if TrekServerStore.restoreForOffline() {
+ call.resolve(["opened": true])
+ restartBridge()
+ } else {
+ call.resolve(["opened": false])
+ }
+ return
+ }
// With the trailing slash, like the bridge's serverURL: Capacitor only
// keeps a navigation in the app when it starts with that exact string,
// and hands anything else to Safari.
diff --git a/client/native-shell/main.ts b/client/native-shell/main.ts
index cc8032388..4f1324d78 100644
--- a/client/native-shell/main.ts
+++ b/client/native-shell/main.ts
@@ -1805,6 +1805,18 @@ async function start(): Promise<void> {
return;
}
if (!url && previousUrl) {
+ // An update asks to check the server once more. Out of reach (a trip, a
+ // server at home), that check cannot run: with a stored copy of the UI the
+ // app starts on that and checks on a later launch. Only for a server that
+ // did not answer, never for one that answered with a reason to stop.
+ const probe = await probeServer(previousUrl, get).catch(() => null);
+ if (!probe || (!probe.ok && probe.reason === 'unreachable')) {
+ const opened = await TrekShell.openOfflineCopy().then(
+ (r) => r.opened,
+ () => false
+ );
+ if (opened) return;
+ }
showConnect(previousUrl, { recheck: true });
} else if (!url) {
showWelcome();
diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts
index 4541730b6..870c5fc0b 100644
--- a/client/src/native/nativeApp.test.ts
+++ b/client/src/native/nativeApp.test.ts
@@ -10,7 +10,7 @@ import { installNativeGeolocation } from './geolocation';
import { prepareKeyboardFields } from './keyboardFields';
import { scrollToTop, startNativeApp } from './nativeApp';
import { keepOfflineShellFresh } from './offlineShell';
-import { isNativeApp, isNativeIos } from './platform';
+import { isNativeAndroid, isNativeApp, isNativeIos } from './platform';
import { openPushTarget } from './push';
import { trackTouchInput } from './touchInput';
@@ -22,7 +22,7 @@ vi.mock('@capacitor/keyboard', () => ({
}));
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } }));
vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } }));
-vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() }));
+vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn(), isNativeAndroid: vi.fn() }));
vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }));
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() }));
vi.mock('./capabilities', () => ({
@@ -50,6 +50,7 @@ beforeEach(() => {
vi.clearAllMocks();
vi.mocked(isNativeApp).mockReturnValue(true);
vi.mocked(isNativeIos).mockReturnValue(false);
+ vi.mocked(isNativeAndroid).mockReturnValue(false);
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
vi.mocked(keepOfflineShellFresh).mockResolvedValue();
vi.mocked(hasNativeFeature).mockReturnValue(false);
@@ -153,18 +154,19 @@ describe('startNativeApp', () => {
startNativeApp();
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
vi.advanceTimersByTime(15_000);
- expect(keepOfflineShellFresh).toHaveBeenCalled();
+ expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(false);
});
- it('skips the refresh while offline, and never on Android', () => {
- vi.mocked(isNativeIos).mockReturnValue(true);
- vi.mocked(isEffectivelyOffline).mockReturnValue(true);
+ it('refreshes it on Android too, into the store of the app', () => {
+ vi.mocked(isNativeAndroid).mockReturnValue(true);
startNativeApp();
vi.advanceTimersByTime(15_000);
- expect(keepOfflineShellFresh).not.toHaveBeenCalled();
+ expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(true);
+ });
- vi.mocked(isNativeIos).mockReturnValue(false);
- vi.mocked(isEffectivelyOffline).mockReturnValue(false);
+ it('skips the refresh while offline', () => {
+ vi.mocked(isNativeIos).mockReturnValue(true);
+ vi.mocked(isEffectivelyOffline).mockReturnValue(true);
startNativeApp();
vi.advanceTimersByTime(15_000);
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts
index a1d96762a..27a831bb6 100644
--- a/client/src/native/nativeApp.ts
+++ b/client/src/native/nativeApp.ts
@@ -11,7 +11,7 @@ import { fadeInImages } from './imageFade';
import { keepFieldInView } from './keepFieldInView';
import { prepareKeyboardFields } from './keyboardFields';
import { keepOfflineShellFresh } from './offlineShell';
-import { isNativeApp, isNativeIos } from './platform';
+import { isNativeAndroid, isNativeApp, isNativeIos } from './platform';
import { openPushTarget, startNativePush } from './push';
import { startQuickActions } from './quickActions';
import { reportNativeFailure } from './reportFailure';
@@ -88,15 +88,20 @@ export function startNativeApp(): void {
// The "‹ › Done" strip above the keyboard is a web form's, not an app's.
void Keyboard.setAccessoryBarVisible({ isVisible: false });
keepFieldInView(Keyboard);
- window.setTimeout(() => {
- if (isEffectivelyOffline()) return;
- // Not refreshed this time is no harm: the next launch tries again. An app
- // older than the offline copy has no such method, which is no failure.
- keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language).catch((err: unknown) => {
- if (!isUnimplemented(err)) reportNativeFailure(err);
- });
- }, OFFLINE_SHELL_DELAY_MS);
}
+
+ // The copy of the UI the app starts from without its server (offlineShell.ts):
+ // iOS in WebKit's cache, Android in the app's own store.
+ window.setTimeout(() => {
+ if (isEffectivelyOffline()) return;
+ // Not refreshed this time is no harm: the next launch tries again. An app
+ // older than the offline copy has no such method, which is no failure.
+ keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language, isNativeAndroid()).catch(
+ (err: unknown) => {
+ if (!isUnimplemented(err)) reportNativeFailure(err);
+ }
+ );
+ }, OFFLINE_SHELL_DELAY_MS);
}
/**
diff --git a/client/src/native/offlineShell.test.ts b/client/src/native/offlineShell.test.ts
index 735c58183..8d6f85aa1 100644
--- a/client/src/native/offlineShell.test.ts
+++ b/client/src/native/offlineShell.test.ts
@@ -99,4 +99,30 @@ describe('keepOfflineShellFresh', () => {
await keepOfflineShellFresh(fetchImpl, 'fr');
expect(fetched).toContain('/assets/fr-bbbb2222.js');
});
+
+ it('on Android hands the list to the native store instead of fetching it here', async () => {
+ vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: true });
+ const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {
+ if (String(input) === '/asset-manifest.json') return new Response(JSON.stringify(manifest));
+ throw new Error('the native side fetches the files');
+ }) as unknown as typeof fetch;
+
+ await keepOfflineShellFresh(fetchImpl, 'en', true);
+
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(1);
+ const { files } = vi.mocked(TrekShell.refreshOfflineCopy).mock.calls[0][0] as { files: string[] };
+ expect(files).toContain('assets/index-a1b2c3d4.js');
+ expect(files).toContain('assets/AtlasPage-99887766.js');
+ });
+
+ it('on Android asks again on the next launch while the store is incomplete', async () => {
+ vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: false });
+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify(manifest))) as unknown as typeof fetch;
+
+ await keepOfflineShellFresh(fetchImpl, 'en', true);
+ await keepOfflineShellFresh(fetchImpl, 'en', true);
+
+ expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/client/src/native/offlineShell.ts b/client/src/native/offlineShell.ts
index 8bc1bf6bd..09a715a76 100644
--- a/client/src/native/offlineShell.ts
+++ b/client/src/native/offlineShell.ts
@@ -1,13 +1,16 @@
import { TrekShell } from './trekShell';
/**
- * iOS only. WKWebView runs no service worker for a domain the app does not
- * list at build time, so the app stands in for it: the native side keeps a
- * copy of the start page (TrekShellPlugin.refreshOfflineCopy), and this pulls
- * every chunk of the current build into WebKit's HTTP cache. The server marks
- * them immutable, so a cold start without network can load the stored start
- * page under the server's origin and find all its scripts, including the lazy
- * routes nobody has opened yet.
+ * The app's stand-in for a service worker, so it starts without its server (a
+ * trip without reception, a server at home out of reach). WKWebView runs none
+ * for a domain the app does not list at build time, and Android's web view
+ * none on a plain-http server, the usual address of a server at home. So the
+ * native side keeps a copy of the start page (TrekShellPlugin.refreshOfflineCopy)
+ * and every chunk of the current build: iOS in WebKit's HTTP cache, which this
+ * fills (the server marks the files immutable), Android in the app's own store,
+ * which the native side fills from the list this hands it. A cold start without
+ * the server then loads the stored start page under the server's origin and
+ * finds all its scripts, including the lazy routes nobody has opened yet.
*/
const MANIFEST_URL = '/asset-manifest.json';
@@ -82,13 +85,23 @@ function rememberWarmed(build: string): void {
}
}
-export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch, language?: string): Promise<void> {
- await TrekShell.refreshOfflineCopy();
+export async function keepOfflineShellFresh(
+ fetchImpl: typeof fetch = fetch,
+ language?: string,
+ nativeStore = false
+): Promise<void> {
+ if (!nativeStore) await TrekShell.refreshOfflineCopy();
const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' });
if (!response.ok) return;
const files = manifestFiles(await response.json(), language);
// The build and the language together: a new language needs its own chunk.
const build = `${[...files].sort((a, b) => a.localeCompare(b)).find((f) => /index-[^/]+\.js$/.test(f)) ?? files.length}:${language ?? 'en'}`;
+ if (nativeStore) {
+ // The native side fetches only what its store lacks, and keeps the start page fresh each time.
+ const { complete } = await TrekShell.refreshOfflineCopy({ files });
+ if (complete) rememberWarmed(build);
+ return;
+ }
if (warmedBuild() === build) return;
const complete = await warmCache(files, (path) =>
fetchImpl(path, { priority: 'low' } as RequestInit).then((r) => r.blob())
diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts
index b64177115..ea5670079 100644
--- a/client/src/native/trekShell.ts
+++ b/client/src/native/trekShell.ts
@@ -57,9 +57,14 @@ export interface TrekShellPlugin {
* only for two minutes, as long as the server keeps its code. Not in iOS builds, nor in Android builds before 5.1.4.
*/
takeAuthCallback(): Promise<{ url: string | null }>;
- /** iOS: stores the server's start page for a cold start without network. */
- refreshOfflineCopy(): Promise<{ saved: boolean }>;
- /** iOS: loads that copy under the server's origin. False when there is none. */
+ /**
+ * Stores the server's start page for a start without the server. Android
+ * also downloads the build's `files` the copy does not hold yet (an Android
+ * build before the offline copy resolves `saved: false`); iOS keeps those in
+ * WebKit's HTTP cache instead and ignores them.
+ */
+ refreshOfflineCopy(options?: { files?: string[] }): Promise<{ saved: boolean; complete?: boolean }>;
+ /** Starts on that copy under the server's origin. False when there is none. */
openOfflineCopy(): Promise<{ opened: boolean }>;
/** What this binary offers the UI (native/capabilities.ts). Missing before shell API 2. */
getCapabilities(): Promise<NativeCapabilities>;