mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 22:57:32 +00:00
fix(native): start without the server on Android and keep the offline start on iOS
A tester with a server on his home network could not open the Android app
away from it: after closing the app and turning Wi-Fi off it stayed on the
address screen ("No server answered at this address").
- Android keeps the server's UI itself (TrekOfflineShell): the start page
and every file of the build, listed by native/offlineShell.ts from the
server's manifest and downloaded natively. A web view runs no service
worker on a plain-http server, the usual address of a server at home, so
the old "Android has the service worker" assumption did not hold.
- Without a network, or once the server failed to load twice, the web view
serves the copy under the server's origin with Capacitor's bridge; the UI
runs on its own offline data and the API answers again once the server
is back. The address screen opens the copy too (openOfflineCopy).
- The check an update asks for no longer locks the app out offline: on both
platforms a server out of reach is put back on its copy and checked on
the next launch that reaches it. iOS no longer throws its copy away when
the update check runs.
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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 ----
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user