Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Gym reminder: a short live-location check after the approach zone so Android notices the walk in within seconds, the paired server asked about today before posting (3 s at most), privacy page line
Duarte Santos4459d19ac0b4
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xmlindex cf48356ca..fd3aa0375 100644--- a/frontend/android/app/src/main/AndroidManifest.xml+++ b/frontend/android/app/src/main/AndroidManifest.xml@@ -91,6 +91,13 @@<receiverandroid:name=".GymReminderReceiver"android:exported="false" />+ <!-- Gym reminder: the short check with live location after the phone entered a gym's wide+ approach zone (GymScanService). At most 15 minutes, at most 3 a day; its notification+ is a silent one. Started by the approach alert's broadcast, never exported. -->+ <service+ android:name=".GymScanService"+ android:exported="false"+ android:foregroundServiceType="location" /><!-- Proximity alerts are gone after a restart or an app update: registered again here.Only the system sends these two broadcasts. --><receiver@@ -149,6 +156,10 @@<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />+ <!-- The approach check above runs as a location foreground service (Android 14+ names the+ type), and asks the paired server about today only when there is a network. -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><!-- Location is optional: a phone without GPS still installs the app (the permissions abovewould otherwise make Google Play require the hardware). --><uses-feature android:name="android.hardware.location" android:required="false" />diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminder.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminder.javaindex 06e58406a..94309bf04 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminder.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminder.java@@ -10,8 +10,23 @@ import android.content.Intent;import android.content.SharedPreferences;import android.content.pm.PackageManager;import android.location.LocationManager;+import android.net.ConnectivityManager;+import android.net.Network;+import android.net.NetworkCapabilities;import android.os.Build;+import android.util.Log;+import java.io.ByteArrayOutputStream;+import java.io.InputStream;+import java.net.HttpURLConnection;+import java.net.URL;+import java.net.URLEncoder;+import java.nio.charset.StandardCharsets;import java.util.Calendar;+import java.util.Iterator;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;import org.json.JSONArray;import org.json.JSONObject;@@ -24,6 +39,17 @@ import org.json.JSONObject;* whether to post. Proximity alerts do not survive a restart or an app update:* GymReminderBootReceiver registers them again.*+ * Android only looks at proximity alerts for a background app every 30 minutes, unless another+ * app's location request feeds it a fix. So every gym gets a second, wide alert (the approach+ * zone, GymReminderRules.approachOf): entering it starts GymScanService, a short check with live+ * location that notices the walk into the gym within a fix or two and then stops (at most 15+ * minutes, at most 3 times a day, never once today is settled). The gym's own alert stays as the+ * fallback.+ *+ * Before posting, a paired phone asks its server whether today was trained somewhere else (a+ * workout logged on the web or another phone this one has not synced yet), bounded to 3 seconds;+ * no server, no network or no answer in time: the phone's own status decides, as before.+ ** What is kept, in the app's private preferences: the config the page saved (gyms with their* places, the time window), the status it last reported (last day trained, a running session, the* notification's words) and the day it last went off. That file is left out of Android's cloud@@ -43,6 +69,12 @@ final class GymReminder {*/static final long ARM_GRACE_MS = 90_000L;+ static final String TAG = "OpenGymGym";+ /** The approach alerts use the request codes after the gyms' own ones. */+ private static final int NEAR_SLOT = MAX_GYMS;+ /** How long the server may take to say how today stands before the phone decides alone. */+ static final long SERVER_CHECK_MS = 3_000L;+static String actionEnter(Context ctx) { return ctx.getPackageName() + ".GYM_ENTER"; }static String actionOpen(Context ctx) { return ctx.getPackageName() + ".GYM_REMINDER_OPEN"; }@@ -80,6 +112,35 @@ final class GymReminder {}}+ /**+ * The paired server and the headers a request to it carries (the pairing token), from the page+ * (GymReminderPlugin.server); null or an empty server forgets them. Encrypted with the app's+ * Keystore key (NudgeCheck.seal), in the same file as the gyms, so also out of backups.+ */+ static void saveServer(Context ctx, JSONObject auth) {+ SharedPreferences.Editor e = prefs(ctx).edit();+ String[] sealed = auth == null || auth.optString("server", "").isEmpty() ? null : NudgeCheck.seal(auth.toString());+ if (sealed == null) e.remove("authIv").remove("auth");+ else e.putString("authIv", sealed[0]).putString("auth", sealed[1]);+ e.apply();+ }++ static JSONObject server(Context ctx) {+ SharedPreferences p = prefs(ctx);+ String plain = NudgeCheck.open(p.getString("authIv", null), p.getString("auth", null));+ try {+ return plain == null ? null : new JSONObject(plain);+ } catch (Exception e) {+ return null;+ }+ }++ /** What happened at the last arrival or check, for the emulator proof and bug reports. */+ static void note(Context ctx, String what) {+ Log.i(TAG, what);+ prefs(ctx).edit().putString("lastNote", what).apply();+ }+// ---------------------------------------------------------------- permissionsstatic boolean hasFine(Context ctx) {@@ -97,6 +158,7 @@ final class GymReminder {private static PendingIntent alertIntent(Context ctx, int slot, String gymId, int flags) {Intent i = new Intent(ctx, GymReminderReceiver.class).setAction(actionEnter(ctx));if (gymId != null) i.putExtra("gym", gymId);+ if (slot >= NEAR_SLOT) i.putExtra("near", true);// Mutable: the system adds KEY_PROXIMITY_ENTERING to it. Explicit, so nothing else can fill it in.int mutable = Build.VERSION.SDK_INT >= 31 ? PendingIntent.FLAG_MUTABLE : 0;return PendingIntent.getBroadcast(ctx, REQUEST_BASE + slot, i, flags | mutable);@@ -105,7 +167,7 @@ final class GymReminder {/** Stops every alert this app may have registered. */static void unregister(Context ctx) {LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);- for (int slot = 0; slot < MAX_GYMS; slot++) {+ for (int slot = 0; slot < 2 * MAX_GYMS; slot++) {PendingIntent pi = alertIntent(ctx, slot, null, PendingIntent.FLAG_NO_CREATE);if (pi == null) continue;try {@@ -138,6 +200,8 @@ final class GymReminder {if (Double.isNaN(lat) || Double.isNaN(lng)) continue;try {lm.addProximityAlert(lat, lng, radius, -1, alertIntent(ctx, slot, g.optString("id", ""), PendingIntent.FLAG_UPDATE_CURRENT));+ lm.addProximityAlert(lat, lng, (float) GymReminderRules.approachOf(radius), -1,+ alertIntent(ctx, NEAR_SLOT + slot, g.optString("id", ""), PendingIntent.FLAG_UPDATE_CURRENT));n++;} catch (SecurityException e) {break;@@ -158,23 +222,77 @@ final class GymReminder {if (!intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false)) return;SharedPreferences p = prefs(ctx);if (System.currentTimeMillis() - p.getLong("armedAt", 0) < ARM_GRACE_MS) return;- arrive(ctx, intent.getStringExtra("gym"), Calendar.getInstance());+ if (intent.getBooleanExtra("near", false)) startCheck(ctx, intent.getStringExtra("gym"), Calendar.getInstance());+ else arrive(ctx, intent.getStringExtra("gym"), Calendar.getInstance());}- /** Applies the no-nag rule for arriving at `gymId` now, and posts if it says so. True if posted. */- static boolean arrive(Context ctx, String gymId, Calendar now) {+ /** The no-nag rule for now (GymReminderRules.skipReason), or "off" without a config. */+ static String skipNow(Context ctx, Calendar now) {JSONObject c = config(ctx);- if (c == null) return false;+ if (c == null) return "off";JSONObject st = status(ctx);JSONObject win = c.optJSONObject("window");JSONArray gyms = c.optJSONArray("gyms");- SharedPreferences p = prefs(ctx);- String why = GymReminderRules.skipReason(+ return GymReminderRules.skipReason(c.optBoolean("on", false), gyms == null ? 0 : gyms.length(),win == null ? null : win.optString("from", null), win == null ? null : win.optString("to", null),st.optString("trainedOn", ""), st.optString("quietOn", ""), st.optLong("activeSince", 0),- p.getString("lastFired", ""), now);- if (why != null) return false;+ prefs(ctx).getString("lastFired", ""), now);+ }++ /**+ * The phone entered a gym's approach zone: start the short check with live location, unless+ * today is settled already (no point looking), three checks ran today, or Android refuses.+ */+ static void startCheck(Context ctx, String gymId, Calendar now) {+ String why = skipNow(ctx, now);+ if (why != null) {+ note(ctx, "near " + gymId + ": no check (" + why + ")");+ return;+ }+ SharedPreferences p = prefs(ctx);+ String today = GymReminderRules.isoOf(now);+ String day = p.getString("scanDay", "");+ int count = today.equals(day) ? p.getInt("scans", 0) : 0;+ if (!GymReminderRules.mayScan(day, count, today)) {+ note(ctx, "near " + gymId + ": no check (3 today)");+ return;+ }+ try {+ Intent i = new Intent(ctx, GymScanService.class);+ if (Build.VERSION.SDK_INT >= 26) ctx.startForegroundService(i);+ else ctx.startService(i);+ p.edit().putString("scanDay", today).putInt("scans", count + 1).apply();+ note(ctx, "near " + gymId + ": check started");+ } catch (Exception e) {+ // Android may refuse a foreground service from the background: the gym's own alert+ // still fires, just on the system's slower schedule.+ note(ctx, "near " + gymId + ": check refused (" + e.getClass().getSimpleName() + ")");+ }+ }++ /** Applies the no-nag rule for arriving at `gymId` now, and posts if it says so. True if posted. */+ static boolean arrive(Context ctx, String gymId, Calendar now) {+ JSONObject c = config(ctx);+ if (c == null) return false;+ JSONObject st = status(ctx);+ JSONArray gyms = c.optJSONArray("gyms");+ SharedPreferences p = prefs(ctx);+ String why = skipNow(ctx, now);+ if (why != null) {+ note(ctx, "at " + gymId + ": quiet (" + why + ")");+ return false;+ }+ String today = GymReminderRules.isoOf(now);+ if (trainedElsewhere(ctx, today)) {+ // Remember it, so the next alert today needs no network.+ try {+ saveStatus(ctx, status(ctx).put("trainedOn", today));+ } catch (Exception ignored) {+ }+ note(ctx, "at " + gymId + ": quiet (trained on another device)");+ return false;+ }JSONObject gym = null;for (int i = 0; gyms != null && i < gyms.length(); i++) {JSONObject g = gyms.optJSONObject(i);@@ -186,9 +304,87 @@ final class GymReminder {if (body.isEmpty()) body = "Ready for your workout? 💪";if (!post(ctx, title, body, st.optString("channel", ""))) return false;p.edit().putString("lastFired", GymReminderRules.isoOf(now)).apply();+ note(ctx, "at " + gymId + ": posted");return true;}+ // ---------------------------------------------------------------- the server's word on today++ private static boolean online(Context ctx) {+ try {+ ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);+ if (cm == null) return false;+ if (Build.VERSION.SDK_INT < 23) {+ android.net.NetworkInfo ni = cm.getActiveNetworkInfo();+ return ni != null && ni.isConnected();+ }+ Network n = cm.getActiveNetwork();+ NetworkCapabilities caps = n == null ? null : cm.getNetworkCapabilities(n);+ return caps != null && caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);+ } catch (Exception e) {+ return false;+ }+ }++ /**+ * Whether the paired server says `today` was trained or excused (GET /api/nudge-check, the+ * same few bytes the missed-day check asks for). False without a server, offline, on any+ * error and after SERVER_CHECK_MS: the phone then goes by what it knows. Runs off the main+ * thread (the receiver's and the check's own threads).+ */+ static boolean trainedElsewhere(Context ctx, String today) {+ JSONObject auth = server(ctx);+ String base = auth == null ? "" : auth.optString("server", "").replaceAll("/+$", "");+ if (base.isEmpty()) return false;+ if (!online(ctx)) {+ note(ctx, "server check skipped (offline)");+ return false;+ }+ JSONObject headers = auth.optJSONObject("headers");+ ExecutorService ex = Executors.newSingleThreadExecutor(r -> {+ Thread t = new Thread(r, "opengym-gym-check");+ t.setDaemon(true);+ return t;+ });+ long t0 = System.currentTimeMillis();+ Future<Boolean> f = ex.submit(() -> {+ HttpURLConnection c = (HttpURLConnection) new URL(base + "/api/nudge-check?date=" + URLEncoder.encode(today, "UTF-8")).openConnection();+ try {+ c.setConnectTimeout((int) SERVER_CHECK_MS);+ c.setReadTimeout((int) SERVER_CHECK_MS);+ c.setInstanceFollowRedirects(false);+ c.setRequestProperty("Accept", "application/json");+ if (headers != null) {+ for (Iterator<String> it = headers.keys(); it.hasNext();) {+ String k = it.next();+ c.setRequestProperty(k, headers.optString(k));+ }+ }+ if (c.getResponseCode() != 200) return false;+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ try (InputStream in = c.getInputStream()) {+ byte[] buf = new byte[1024];+ for (int n; (n = in.read(buf)) > 0 && out.size() < 8192;) out.write(buf, 0, n);+ }+ JSONObject a = new JSONObject(new String(out.toByteArray(), StandardCharsets.UTF_8));+ return today.equals(a.optString("date", null)) && Boolean.TRUE.equals(a.opt("done"));+ } finally {+ c.disconnect();+ }+ });+ try {+ boolean done = f.get(SERVER_CHECK_MS, TimeUnit.MILLISECONDS);+ note(ctx, "server check: " + (done ? "done" : "not done") + " in " + (System.currentTimeMillis() - t0) + " ms");+ return done;+ } catch (Exception e) {+ f.cancel(true);+ note(ctx, "server check: no answer (" + e.getClass().getSimpleName() + ") after " + (System.currentTimeMillis() - t0) + " ms");+ return false;+ } finally {+ ex.shutdownNow();+ }+ }+static boolean post(Context ctx, String title, String body, String channelName) {NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);if (nm == null || !nm.areNotificationsEnabled()) return false;diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderPlugin.javaindex f95f92c85..84d58285f 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderPlugin.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderPlugin.java@@ -29,7 +29,8 @@ import org.json.JSONObject;* Usage from JS:* const GR = registerPlugin('GymReminder');* await GR.configure({ config }); // { watching, permission }- * await GR.status({ trainedOn, quietOn, activeSince, title, body });+ * await GR.status({ trainedOn, quietOn, activeSince, title, body, channel, scan });+ * await GR.server({ server, headers }); // the paired server, asked about today before posting ('' forgets it)* await GR.get(); // { config, permission, watching }* await GR.permission(); // { location, background, notifications }* await GR.requestForeground(); // while-in-use location@@ -104,10 +105,29 @@ public class GymReminderPlugin extends Plugin {s.put("title", call.getString("title", ""));s.put("body", call.getString("body", ""));s.put("channel", call.getString("channel", ""));+ s.put("scan", call.getString("scan", ""));GymReminder.saveStatus(getContext(), s);call.resolve();}+ @PluginMethod+ public void server(PluginCall call) {+ String server = call.getString("server", "");+ JSONObject auth = null;+ if (server != null && !server.isEmpty()) {+ auth = new JSONObject();+ try {+ auth.put("server", server);+ JSObject h = call.getObject("headers");+ auth.put("headers", h == null ? new JSONObject() : h);+ } catch (Exception e) {+ auth = null;+ }+ }+ GymReminder.saveServer(getContext(), auth);+ call.resolve();+ }+@PluginMethodpublic void get(PluginCall call) {Context ctx = getContext();diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderRules.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderRules.javaindex b10096b8a..7a5bdd916 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderRules.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderRules.java@@ -54,4 +54,50 @@ final class GymReminderRules {if (!inWindow(windowFrom, windowTo, minute)) return "window";return null;}++ // ---------------------------------------------------------------- the approach check (Android)+ //+ // Android looks at proximity alerts only every 30 minutes for an app in the background unless+ // some other app's location request feeds it a fix. So each gym also gets a wide "approach"+ // zone. Entering it starts a short, bounded check with live location (GymScanService) that+ // notices the walk through the door within about one fix interval, then stops.++ /** The approach zone around a gym: at least 800 m, wider for a gym with a wide radius. */+ static final double APPROACH_MIN_M = 800;+ /** How long one check may keep the location on, at most: a walk across the zone fits. */+ static final long SCAN_MAX_MS = 15 * 60_000L;+ /** How often it asks for a fix while it runs. */+ static final long SCAN_INTERVAL_MS = 15_000L;+ /** How many checks one day may start (a commute past the gym, a gym next to the office). */+ static final int SCANS_PER_DAY = 3;+ /** A check ends early once the phone is this much beyond every gym's approach zone. */+ static final double AWAY_MARGIN_M = 250;++ static double approachOf(double radius) {+ return Math.max(APPROACH_MIN_M, 5 * radius);+ }++ /**+ * The gym a fix is inside (its index), or -1. Inside means within the gym's radius, with a fix+ * good enough to say so: accuracy no worse than twice the radius (and at least 100 m allowed).+ */+ static int insideOf(double[] dist, double[] radius, double accuracy) {+ int best = -1;+ for (int i = 0; i < dist.length; i++) {+ if (dist[i] > radius[i] || accuracy > Math.max(100, 2 * radius[i])) continue;+ if (best < 0 || dist[i] < dist[best]) best = i;+ }+ return best;+ }++ /** True when the phone has left every gym's approach zone (with a margin): the check stops. */+ static boolean awayFromAll(double[] dist, double[] radius) {+ for (int i = 0; i < dist.length; i++) if (dist[i] <= approachOf(radius[i]) + AWAY_MARGIN_M) return false;+ return true;+ }++ /** Whether another check may start today, given the day the last ones ran and how many. */+ static boolean mayScan(String scanDay, int scansThatDay, String today) {+ return !today.equals(scanDay) || scansThatDay < SCANS_PER_DAY;+ }}diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymScanService.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymScanService.javanew file mode 100644index 000000000..259910431--- /dev/null+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymScanService.java@@ -0,0 +1,201 @@+package ch.duartesantos.opengym;++import android.app.Notification;+import android.app.NotificationChannel;+import android.app.NotificationManager;+import android.app.Service;+import android.content.Context;+import android.content.Intent;+import android.content.pm.ServiceInfo;+import android.location.Location;+import android.location.LocationListener;+import android.location.LocationManager;+import android.location.LocationRequest;+import android.os.Build;+import android.os.Bundle;+import android.os.Handler;+import android.os.HandlerThread;+import android.os.IBinder;+import java.util.Calendar;+import org.json.JSONArray;+import org.json.JSONObject;++/**+ * The gym reminder's approach check (GymReminder.startCheck): the phone entered the wide zone+ * around a gym, so for a few minutes it asks for live location (one fix every 15 s) to notice the+ * walk through the door, instead of waiting for Android's next proximity-alert look, which for an+ * app in the background can be half an hour away. Ends as soon as one of these is true: the phone+ * is inside a gym (the reminder posts, or the no-nag rule keeps it quiet), it left every approach+ * zone, today got settled meanwhile, or 15 minutes passed. A foreground service because Android+ * only gives background apps a few fixes an hour otherwise; its notification is a silent one on+ * its own channel and goes away with the check.+ *+ * Battery: at most 15 minutes of GPS per check and at most 3 checks a day, none once the reminder+ * went off, a workout is logged or the time window is closed. A typical day is one check of a+ * minute or two on the way in.+ */+public class GymScanService extends Service implements LocationListener {+ static final int NOTIFICATION_ID = 3001;+ static final String CHANNEL_ID = "gym-reminder-check";++ private HandlerThread thread;+ private Handler handler;+ private LocationManager lm;+ private boolean running;+ private long startedAt;+ private int fixes;++ @Override+ public IBinder onBind(Intent intent) {+ return null;+ }++ @Override+ public int onStartCommand(Intent intent, int flags, int startId) {+ Context ctx = getApplicationContext();+ try {+ if (Build.VERSION.SDK_INT >= 29) startForeground(NOTIFICATION_ID, notification(ctx), ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);+ else startForeground(NOTIFICATION_ID, notification(ctx));+ } catch (Exception e) {+ GymReminder.note(ctx, "check: could not start (" + e.getClass().getSimpleName() + ")");+ stopSelf();+ return START_NOT_STICKY;+ }+ if (running) return START_NOT_STICKY;+ running = true;+ startedAt = System.currentTimeMillis();+ thread = new HandlerThread("opengym-gym-scan");+ thread.start();+ handler = new Handler(thread.getLooper());+ lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);+ String provider = provider(lm);+ if (provider == null || !GymReminder.hasFine(ctx)) {+ finish("no location");+ return START_NOT_STICKY;+ }+ try {+ if (Build.VERSION.SDK_INT >= 31) {+ LocationRequest req = new LocationRequest.Builder(GymReminderRules.SCAN_INTERVAL_MS)+ .setQuality(LocationRequest.QUALITY_HIGH_ACCURACY)+ .setMinUpdateIntervalMillis(5_000L)+ .setDurationMillis(GymReminderRules.SCAN_MAX_MS)+ .build();+ lm.requestLocationUpdates(provider, req, command -> handler.post(command), this);+ } else {+ lm.requestLocationUpdates(provider, GymReminderRules.SCAN_INTERVAL_MS, 0f, this, thread.getLooper());+ }+ } catch (Exception e) {+ finish("no location (" + e.getClass().getSimpleName() + ")");+ return START_NOT_STICKY;+ }+ handler.postDelayed(() -> finish("time up"), GymReminderRules.SCAN_MAX_MS);+ GymReminder.note(ctx, "check: watching with " + provider);+ return START_NOT_STICKY;+ }++ /** Fused where there is one (Android 12+: GPS and network together), else GPS, else network. */+ private static String provider(LocationManager lm) {+ if (lm == null) return null;+ String[] order = { Build.VERSION.SDK_INT >= 31 ? LocationManager.FUSED_PROVIDER : null, LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER };+ for (String p : order) {+ try {+ if (p != null && lm.getAllProviders().contains(p) && lm.isProviderEnabled(p)) return p;+ } catch (Exception ignored) {+ }+ }+ return null;+ }++ @Override+ public void onLocationChanged(Location loc) {+ if (!running || loc == null) return;+ fixes++;+ Context ctx = getApplicationContext();+ Calendar now = Calendar.getInstance();+ String why = GymReminder.skipNow(ctx, now);+ if (why != null) {+ finish("settled (" + why + ")");+ return;+ }+ JSONObject c = GymReminder.config(ctx);+ JSONArray gyms = c == null ? null : c.optJSONArray("gyms");+ int n = gyms == null ? 0 : Math.min(gyms.length(), GymReminder.MAX_GYMS);+ double[] dist = new double[n], radius = new double[n];+ String[] ids = new String[n];+ float[] out = new float[1];+ for (int i = 0; i < n; i++) {+ JSONObject g = gyms.optJSONObject(i);+ if (g == null) {+ dist[i] = Double.MAX_VALUE;+ continue;+ }+ Location.distanceBetween(loc.getLatitude(), loc.getLongitude(), g.optDouble("lat"), g.optDouble("lng"), out);+ dist[i] = out[0];+ radius[i] = Math.max(50, Math.min(500, g.optDouble("radius", 100)));+ ids[i] = g.optString("id", "");+ }+ int in = GymReminderRules.insideOf(dist, radius, loc.hasAccuracy() ? loc.getAccuracy() : 1000);+ if (in >= 0) {+ GymReminder.arrive(ctx, ids[in], now);+ finish("inside after " + (System.currentTimeMillis() - startedAt) / 1000 + " s");+ } else if (n == 0 || GymReminderRules.awayFromAll(dist, radius)) {+ finish("left the area");+ }+ }++ // Older Android calls these; nothing to do.+ @Override+ public void onStatusChanged(String provider, int status, Bundle extras) {}++ @Override+ public void onProviderEnabled(String provider) {}++ @Override+ public void onProviderDisabled(String provider) {}++ private synchronized void finish(String why) {+ if (!running) return;+ running = false;+ try {+ if (lm != null) lm.removeUpdates(this);+ } catch (Exception ignored) {+ }+ GymReminder.note(getApplicationContext(), "check: ended, " + why + ", " + fixes + " fixes in " + (System.currentTimeMillis() - startedAt) / 1000 + " s");+ if (handler != null) handler.removeCallbacksAndMessages(null);+ if (thread != null) thread.quitSafely();+ if (Build.VERSION.SDK_INT >= 24) stopForeground(STOP_FOREGROUND_REMOVE);+ else stopForeground(true);+ stopSelf();+ }++ @Override+ public void onDestroy() {+ finish("stopped");+ super.onDestroy();+ }++ private static Notification notification(Context ctx) {+ JSONObject st = GymReminder.status(ctx);+ String text = st.optString("scan", "");+ if (text.isEmpty()) text = "Checking if you made it to the gym";+ NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);+ if (Build.VERSION.SDK_INT >= 26 && nm != null) {+ NotificationChannel ch = nm.getNotificationChannel(CHANNEL_ID);+ if (ch == null || !text.contentEquals(ch.getName())) {+ // Silent and out of the way: no sound, no badge, folded away in the shade.+ ch = new NotificationChannel(CHANNEL_ID, text, NotificationManager.IMPORTANCE_MIN);+ ch.setShowBadge(false);+ nm.createNotificationChannel(ch);+ }+ }+ Notification.Builder b = Build.VERSION.SDK_INT >= 26 ? new Notification.Builder(ctx, CHANNEL_ID) : new Notification.Builder(ctx);+ b.setSmallIcon(R.drawable.ic_stat_dumbbell)+ .setContentTitle(text)+ .setOngoing(true)+ .setOnlyAlertOnce(true)+ .setShowWhen(false)+ .setCategory(Notification.CATEGORY_SERVICE);+ if (Build.VERSION.SDK_INT < 26) b.setPriority(Notification.PRIORITY_MIN);+ return b.build();+ }+}diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheck.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheck.javaindex e2f16b271..8d50691ed 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheck.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheck.java@@ -45,28 +45,44 @@ final class NudgeCheck {// ---------------------------------------------------------------- what is keptstatic boolean save(Context ctx, JSONObject config) {+ String[] sealed = seal(config.toString());+ if (sealed == null) return false;+ prefs(ctx).edit().putString("iv", sealed[0]).putString("config", sealed[1]).apply();+ return true;+ }++ static JSONObject load(Context ctx) {+ SharedPreferences p = prefs(ctx);+ String plain = open(p.getString("iv", null), p.getString("config", null));+ try {+ return plain == null ? null : new JSONObject(plain);+ } catch (Exception e) {+ return null;+ }+ }++ /**+ * `plain` encrypted with this app's Keystore key, as { iv, sealed } in Base64, or null. Also+ * keeps the gym reminder's copy of the server and its headers (GymReminder.saveServer).+ */+ static String[] seal(String plain) {try {Cipher c = Cipher.getInstance("AES/GCM/NoPadding");c.init(Cipher.ENCRYPT_MODE, key());- byte[] sealed = c.doFinal(config.toString().getBytes(StandardCharsets.UTF_8));- prefs(ctx).edit()- .putString("iv", Base64.encodeToString(c.getIV(), Base64.NO_WRAP))- .putString("config", Base64.encodeToString(sealed, Base64.NO_WRAP))- .apply();- return true;+ byte[] sealed = c.doFinal(plain.getBytes(StandardCharsets.UTF_8));+ return new String[] { Base64.encodeToString(c.getIV(), Base64.NO_WRAP), Base64.encodeToString(sealed, Base64.NO_WRAP) };} catch (Exception e) {- return false;+ return null;}}- static JSONObject load(Context ctx) {+ /** The other way round; null when either part is missing or does not open. */+ static String open(String iv, String sealed) {+ if (iv == null || sealed == null) return null;try {- SharedPreferences p = prefs(ctx);- String iv = p.getString("iv", null), sealed = p.getString("config", null);- if (iv == null || sealed == null) return null;Cipher c = Cipher.getInstance("AES/GCM/NoPadding");c.init(Cipher.DECRYPT_MODE, key(), new GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)));- return new JSONObject(new String(c.doFinal(Base64.decode(sealed, Base64.NO_WRAP)), StandardCharsets.UTF_8));+ return new String(c.doFinal(Base64.decode(sealed, Base64.NO_WRAP)), StandardCharsets.UTF_8);} catch (Exception e) {return null;}diff --git a/frontend/android/app/src/test/java/ch/duartesantos/opengym/GymReminderRulesTest.java b/frontend/android/app/src/test/java/ch/duartesantos/opengym/GymReminderRulesTest.javaindex f26182b72..7780f4218 100644--- a/frontend/android/app/src/test/java/ch/duartesantos/opengym/GymReminderRulesTest.java+++ b/frontend/android/app/src/test/java/ch/duartesantos/opengym/GymReminderRulesTest.java@@ -69,4 +69,34 @@ public class GymReminderRulesTest {assertEquals(-1, GymReminderRules.minuteOf("24:00"));assertEquals(6 * 60 + 5, GymReminderRules.minuteOf("06:05"));}++ @Test+ public void approachZoneIsAtLeast800Metres() {+ assertEquals(800, GymReminderRules.approachOf(100), 0.01);+ assertEquals(2500, GymReminderRules.approachOf(500), 0.01);+ }++ @Test+ public void insideNeedsTheRadiusAndAGoodEnoughFix() {+ double[] r = { 100, 100 };+ assertEquals(-1, GymReminderRules.insideOf(new double[] { 400, 900 }, r, 10));+ assertEquals(0, GymReminderRules.insideOf(new double[] { 80, 900 }, r, 10));+ assertEquals(1, GymReminderRules.insideOf(new double[] { 90, 30 }, r, 10)); // the nearer one+ assertEquals(-1, GymReminderRules.insideOf(new double[] { 80, 900 }, r, 350)); // a vague network fix+ }++ @Test+ public void theCheckStopsOnceEveryGymIsBehind() {+ double[] r = { 100, 100 };+ assertFalse(GymReminderRules.awayFromAll(new double[] { 1000, 5000 }, r));+ assertTrue(GymReminderRules.awayFromAll(new double[] { 1100, 5000 }, r));+ }++ @Test+ public void atMostThreeChecksADay() {+ assertTrue(GymReminderRules.mayScan("", 0, "2026-10-15"));+ assertTrue(GymReminderRules.mayScan("2026-10-15", 2, "2026-10-15"));+ assertFalse(GymReminderRules.mayScan("2026-10-15", 3, "2026-10-15"));+ assertTrue(GymReminderRules.mayScan("2026-10-14", 3, "2026-10-15"));+ }}diff --git a/frontend/ios/App/App/GymReminderPlugin.swift b/frontend/ios/App/App/GymReminderPlugin.swiftindex 48f51c49a..3f450b410 100644--- a/frontend/ios/App/App/GymReminderPlugin.swift+++ b/frontend/ios/App/App/GymReminderPlugin.swift@@ -23,12 +23,17 @@ import UserNotifications* const GR = registerPlugin('GymReminder');* await GR.configure({ config }); // { watching, permission }* await GR.status({ trainedOn, quietOn, activeSince, title, body });+ * await GR.server({ server, headers }); // the paired server, asked about today before posting ('' forgets it)* await GR.get(); // { config, permission, watching }* await GR.permission(); // { location, background, precise, notifications }* await GR.requestForeground(); // While Using the App* await GR.requestBackground(); // Always, after the in-app explainer* await GR.currentPosition(); // { lat, lng, accuracy }* await GR.openSettings();+ * Before posting, a paired phone asks its server whether today was trained on another device that+ * has not synced here yet (GET /api/nudge-check, at most 3 seconds). The server and its headers+ * (the pairing token) are kept in the Keychain, this device only. No server, offline, or no+ * answer in time: the phone's own status decides.* A tap on the notification goes through Capacitor's local-notifications handler (the page* listens there for id 3000).*/@@ -39,6 +44,7 @@ public class GymReminderPlugin: CAPPlugin, CAPBridgedPlugin {public let pluginMethods: [CAPPluginMethod] = [CAPPluginMethod(name: "configure", returnType: CAPPluginReturnPromise),CAPPluginMethod(name: "status", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "server", returnType: CAPPluginReturnPromise),CAPPluginMethod(name: "get", returnType: CAPPluginReturnPromise),CAPPluginMethod(name: "permission", returnType: CAPPluginReturnPromise),CAPPluginMethod(name: "requestForeground", returnType: CAPPluginReturnPromise),@@ -72,6 +78,16 @@ public class GymReminderPlugin: CAPPlugin, CAPBridgedPlugin {}}+ @objc func server(_ call: CAPPluginCall) {+ let server = call.getString("server") ?? ""+ if server.isEmpty {+ GymReminderCenter.clearServer()+ } else {+ _ = GymReminderCenter.saveServer(["server": server, "headers": call.getObject("headers") ?? [:]])+ }+ call.resolve()+ }+@objc func get(_ call: CAPPluginCall) {DispatchQueue.main.async {// Regions lost while the app could not watch (Always taken back and given again):@@ -182,6 +198,71 @@ final class GymReminderCenter: NSObject, CLLocationManagerDelegate {func saveConfig(_ c: [String: Any]) { store["config"] = c; writeStore() }func saveStatus(_ s: [String: Any]) { store["status"] = s; writeStore() }+ // MARK: the paired server (Keychain: it carries the pairing token)++ private static func serverQuery() -> [String: Any] {+ return [kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: Bundle.main.bundleIdentifier ?? "ch.opengym.app",+ kSecAttrAccount as String: "gym-reminder-server"]+ }++ static func saveServer(_ auth: [String: Any]) -> Bool {+ guard let data = try? JSONSerialization.data(withJSONObject: auth) else { return false }+ SecItemDelete(serverQuery() as CFDictionary)+ var add = serverQuery()+ add[kSecValueData as String] = data+ // Readable after the first unlock: a region event can wake the app while the phone is locked.+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly+ return SecItemAdd(add as CFDictionary, nil) == errSecSuccess+ }++ static func loadServer() -> [String: Any]? {+ var q = serverQuery()+ q[kSecReturnData as String] = true+ q[kSecMatchLimit as String] = kSecMatchLimitOne+ var out: AnyObject?+ guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil }+ return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]+ }++ static func clearServer() {+ SecItemDelete(serverQuery() as CFDictionary)+ }++ /// Whether the paired server says `today` was trained or excused. Calls back false without a+ /// server, offline, on any error and after 3 seconds, always on the main queue.+ func trainedElsewhere(today: String, _ done: @escaping (Bool) -> Void) {+ guard let auth = GymReminderCenter.loadServer(), var base = auth["server"] as? String, !base.isEmpty else { done(false); return }+ while base.hasSuffix("/") { base.removeLast() }+ guard var parts = URLComponents(string: base + "/api/nudge-check") else { done(false); return }+ parts.queryItems = [URLQueryItem(name: "date", value: today)]+ guard let url = parts.url else { done(false); return }+ var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 3)+ request.setValue("application/json", forHTTPHeaderField: "Accept")+ for (k, v) in auth["headers"] as? [String: String] ?? [:] { request.setValue(v, forHTTPHeaderField: k) }+ let cfg = URLSessionConfiguration.ephemeral+ cfg.timeoutIntervalForRequest = 3+ cfg.timeoutIntervalForResource = 3+ cfg.waitsForConnectivity = false+ let session = URLSession(configuration: cfg)+ var finished = false+ let finish: (Bool) -> Void = { v in+ DispatchQueue.main.async {+ if finished { return }+ finished = true+ session.invalidateAndCancel()+ done(v)+ }+ }+ session.dataTask(with: request) { data, response, _ in+ guard (response as? HTTPURLResponse)?.statusCode == 200, let data = data,+ let a = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { finish(false); return }+ finish((a["date"] as? String) == today && (a["done"] as? Bool) == true)+ }.resume()+ // The hard stop, whatever URLSession does with DNS or a half-open socket.+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) { finish(false) }+ }+// MARK: permissionsprivate var authorization: CLAuthorizationStatus { manager.authorizationStatus }@@ -351,6 +432,23 @@ final class GymReminderCenter: NSObject, CLLocationManagerDelegate {activeSince: (st["activeSince"] as? NSNumber)?.doubleValue ?? 0,lastFired: store["lastFired"] as? String ?? "", now: now)guard why == nil else { done(); return }+ let today = GymReminderRules.isoOf(now)+ trainedElsewhere(today: today) { [weak self] elsewhere in+ guard let self = self else { done(); return }+ if elsewhere {+ // Remember it, so the next region event today needs no network.+ var s = self.status+ s["trainedOn"] = today+ self.saveStatus(s)+ done()+ return+ }+ self.post(gymId: gymId, gyms: gyms, now: now, done: done)+ }+ }++ private func post(gymId: String, gyms: [[String: Any]], now: Date, done: @escaping () -> Void) {+ let st = statuslet gym = gyms.first { ($0["id"] as? String) == gymId }let own = ((gym?["text"] as? String) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)let content = UNMutableNotificationContent()diff --git a/frontend/src/lib/gym-reminder.js b/frontend/src/lib/gym-reminder.jsindex f62d4aa24..2144735f0 100644--- a/frontend/src/lib/gym-reminder.js+++ b/frontend/src/lib/gym-reminder.js@@ -15,6 +15,7 @@ import { MOBILE } from './mobile.js'import { t } from './i18n-core.js'import { isoOf } from './format.js'import { excusedOn } from './day-notes.js'+import { remoteAuth } from './api.js'export const GYM_KEY = 'gym_reminder_v1'export const RADIUS = Object.freeze({ min: 50, max: 500, def: 100, step: 10 })@@ -98,6 +99,8 @@ export function statusOf(S, now = new Date()) {body: t('Ready for your workout? 💪'),// Android's name for the notification channel, in the app's language.channel: t('Gym reminder'),+ // Android: the quiet notification while it checks with live location near a gym.+ scan: t('Checking if you made it to the gym'),}}@@ -204,6 +207,22 @@ export async function saveGymConfig(next, S = null) {}let lastStatus = ''+let lastServer = null+/**+ * Tells the native side which server this phone is paired with (and the headers a request to it+ * carries), so that on arrival it can ask whether today was trained on another device that has+ * not synced here yet (GET /api/nudge-check, bounded to 3 s, see GymReminder.java and+ * GymReminderPlugin.swift). A phone without a server sends '' and the phone decides alone. The+ * native side keeps it encrypted (Android Keystore, iOS Keychain), never in the page's storage.+ */+async function pushGymServer(p) {+ const auth = remoteAuth()+ const arg = auth ? { server: auth.base, headers: auth.headers } : { server: '' }+ const key = JSON.stringify(arg)+ if (key === lastServer) return+ try { await p.GymReminder.server(arg); lastServer = key } catch { /* an older native shell: no server check */ }+}+/*** Tells the native side how today stands (statusOf). Cheap and deduplicated: run after every* save of the profile; does nothing with the reminder off on this device.@@ -211,11 +230,12 @@ let lastStatus = ''export async function pushGymStatus(S, force = false) {if (!MOBILE) return falseif (!force && !readGymConfig().on) return false+ const p = await gymPlugin()+ if (!p) return false+ await pushGymServer(p)const status = statusOf(S)const key = JSON.stringify(status)if (!force && key === lastStatus) return false- const p = await gymPlugin()- if (!p) return falsetry { await p.GymReminder.status(status); lastStatus = key; return true } catch { return false }}@@ -278,4 +298,4 @@ export function onGymReminderOpen(cb) {return () => { gone = true; handles.splice(0).forEach(h => { try { h?.remove?.() } catch { /* gone already */ } }) }}-export function _resetGymReminder() { pluginP = null; lastStatus = ''; memory = null }+export function _resetGymReminder() { pluginP = null; lastStatus = ''; lastServer = null; memory = null }diff --git a/frontend/src/lib/gym-reminder.test.js b/frontend/src/lib/gym-reminder.test.jsindex 91754605f..37891fb6c 100644--- a/frontend/src/lib/gym-reminder.test.js+++ b/frontend/src/lib/gym-reminder.test.js@@ -5,9 +5,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'applies when a gym is entered, and the plugin wrapper (never resolving with the bare proxy). */const mocks = vi.hoisted(() => ({MOBILE: true, platform: 'android', registered: 0, calls: [], listeners: {},- get: null, configure: null, status: null,+ get: null, configure: null, status: null, auth: null,}))vi.mock('./mobile.js', () => ({ get MOBILE() { return mocks.MOBILE } }))+vi.mock('./api.js', () => ({ remoteAuth: () => mocks.auth }))vi.mock('@capacitor/core', () => ({Capacitor: { getPlatform: () => mocks.platform },registerPlugin: name => {@@ -20,6 +21,7 @@ vi.mock('@capacitor/core', () => ({if (k === 'get') return async () => mocks.getif (k === 'configure') return async a => { mocks.calls.push(['configure', a]); return mocks.configure }if (k === 'status') return async a => { mocks.calls.push(['status', a]); return mocks.status }+ if (k === 'server') return async a => { mocks.calls.push(['server', a]) }if (k === 'addListener') return async (ev, fn) => { mocks.listeners[ev] = fn; return { remove: () => { delete mocks.listeners[ev] } } }return () => new Promise(() => {})},@@ -43,7 +45,7 @@ const on = (over = {}) => ({ on: true, gyms: [gym()], window: null, ...over })const flush = () => new Promise(r => setTimeout(r, 0))beforeEach(() => {- mocks.MOBILE = true; mocks.platform = 'android'; mocks.registered = 0; mocks.calls = []; mocks.listeners = {}+ mocks.MOBILE = true; mocks.platform = 'android'; mocks.registered = 0; mocks.calls = []; mocks.listeners = {}; mocks.auth = nullmocks.get = null; mocks.configure = { watching: 1, permission: { location: 'granted', background: 'granted' } }; mocks.status = undefinedln.listeners = {}localStorage.clear()@@ -168,7 +170,21 @@ describe('kept on the device, never in the synced state', () => {})it('with the profile: today is sent first, so the native side never acts on stale news', async () => {await saveGymConfig(on(), { workouts: [{ d: '2026-10-01' }] })- expect(mocks.calls.map(c => c[0])).toEqual(['status', 'configure'])+ expect(mocks.calls.map(c => c[0])).toEqual(['server', 'status', 'configure'])+ })+ it('server: a paired phone hands over its server for the arrival check, once per change; no server, an empty one', async () => {+ localStorage.setItem(GYM_KEY, JSON.stringify(on()))+ await pushGymStatus({ workouts: [] })+ expect(mocks.calls.filter(c => c[0] === 'server')).toEqual([['server', { server: '' }]])+ mocks.auth = { base: 'https://gym.example', headers: { Authorization: 'Bearer t' } }+ await pushGymStatus({ workouts: [] })+ await pushGymStatus({ workouts: [] })+ expect(mocks.calls.filter(c => c[0] === 'server')).toEqual([+ ['server', { server: '' }],+ ['server', { server: 'https://gym.example', headers: { Authorization: 'Bearer t' } }],+ ])+ // never in the page's own storage+ expect(JSON.stringify({ ...localStorage })).not.toContain('Bearer')})it('loading prefers the native copy (WebView storage can be evicted)', async () => {localStorage.setItem(GYM_KEY, JSON.stringify(on({ on: false })))diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex f7db38982..ccb8a7a7f 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -2481,6 +2481,7 @@ export default {'Finding you…': 'نبحث عنك…','From': 'من','Gym reminder': 'تذكير الصالة',+ 'Checking if you made it to the gym': 'نتحقق إن كنت وصلت إلى النادي','Gym spotted': 'تم رصد الصالة','I’m at the gym right now': 'أنا في الصالة الآن','Leave it empty for the default.': 'اتركه فارغًا للنص الافتراضي.',diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.jsindex 9f0868d1c..f6a24f488 100644--- a/frontend/src/locales/bn.js+++ b/frontend/src/locales/bn.js@@ -2505,6 +2505,7 @@ export default {'Finding you…': 'আপনাকে খুঁজছি…','From': 'থেকে','Gym reminder': 'জিম রিমাইন্ডার',+ 'Checking if you made it to the gym': 'দেখছি তুমি জিমে পৌঁছেছ কি না','Gym spotted': 'জিম দেখা গেছে','I’m at the gym right now': 'আমি এখন জিমে আছি','Leave it empty for the default.': 'ডিফল্ট লেখার জন্য ফাঁকা রাখুন।',diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex a599b3585..62569cb20 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -2446,6 +2446,7 @@ export default {'Finding you…': 'Suche dich…','From': 'Von','Gym reminder': 'Gym-Erinnerung',+ 'Checking if you made it to the gym': 'Schaue, ob du es ins Gym geschafft hast','Gym spotted': 'Gym gesichtet','I’m at the gym right now': 'Ich bin gerade im Gym','Leave it empty for the default.': 'Leer lassen für den Standardtext.',diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 2d1725864..627f50cf0 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': 'Buscándote…','From': 'Desde','Gym reminder': 'Recordatorio del gimnasio',+ 'Checking if you made it to the gym': 'Comprobando si llegaste al gimnasio','Gym spotted': 'Gimnasio a la vista','I’m at the gym right now': 'Estoy en el gimnasio ahora mismo','Leave it empty for the default.': 'Déjalo vacío para el texto por defecto.',diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 91d608303..81f53d18c 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': 'On te cherche…','From': 'De','Gym reminder': 'Rappel à la salle',+ 'Checking if you made it to the gym': 'On vérifie si tu es arrivé à la salle','Gym spotted': 'Salle repérée','I’m at the gym right now': 'Je suis à la salle en ce moment','Leave it empty for the default.': 'Laisse vide pour le texte par défaut.',diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex a43ad8b94..9f9208bce 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': 'आपको ढूँढ रहे हैं…','From': 'से','Gym reminder': 'जिम रिमाइंडर',+ 'Checking if you made it to the gym': 'देख रहे हैं कि आप जिम पहुँचे या नहीं','Gym spotted': 'जिम दिख गया','I’m at the gym right now': 'मैं अभी जिम में हूँ','Leave it empty for the default.': 'डिफ़ॉल्ट टेक्स्ट के लिए खाली छोड़ें।',diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 06c811914..14eaf881e 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -2429,6 +2429,7 @@ export default {'Finding you…': 'Keresünk…','From': 'Ettől','Gym reminder': 'Edzőterem-emlékeztető',+ 'Checking if you made it to the gym': 'Nézzük, beértél-e az edzőterembe','Gym spotted': 'Edzőterem a láthatáron','I’m at the gym right now': 'Most épp a teremben vagyok','Leave it empty for the default.': 'Hagyd üresen az alapszöveghez.',diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex c32dbe3b7..3a2f8c114 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': 'Ti cerchiamo…','From': 'Dalle','Gym reminder': 'Promemoria palestra',+ 'Checking if you made it to the gym': 'Controllo se sei arrivato in palestra','Gym spotted': 'Palestra avvistata','I’m at the gym right now': 'Sono in palestra adesso','Leave it empty for the default.': 'Lascia vuoto per il testo predefinito.',diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 8befb3cc2..702caeb63 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': '위치 찾는 중…','From': '시작','Gym reminder': '헬스장 알림',+ 'Checking if you made it to the gym': '헬스장에 도착했는지 확인하는 중','Gym spotted': '헬스장 발견','I’m at the gym right now': '지금 헬스장에 있어요','Leave it empty for the default.': '비워 두면 기본 문구를 써요.',diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 99a8d5e00..b305e051a 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': 'Szukamy cię…','From': 'Od','Gym reminder': 'Przypomnienie na siłowni',+ 'Checking if you made it to the gym': 'Sprawdzam, czy dotarłeś na siłownię','Gym spotted': 'Siłownia namierzona','I’m at the gym right now': 'Jestem teraz na siłowni','Leave it empty for the default.': 'Zostaw puste dla domyślnego tekstu.',diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 13455ebef..c3f347954 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1547,6 +1547,7 @@ export const PT_BR_OVERRIDES = {'Finding you…': 'Procurando você…','From': 'Das','Gym reminder': 'Lembrete da academia',+ 'Checking if you made it to the gym': 'Vendo se você chegou na academia','Gym spotted': 'Academia à vista','I’m at the gym right now': 'Estou na academia agora','Leave it empty for the default.': 'Deixe vazio para o texto padrão.',diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 95ff3b0d6..6232bb0fd 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': 'À tua procura…','From': 'Das','Gym reminder': 'Lembrete do ginásio',+ 'Checking if you made it to the gym': 'A ver se chegaste ao ginásio','Gym spotted': 'Ginásio à vista','I’m at the gym right now': 'Estou no ginásio agora','Leave it empty for the default.': 'Deixa vazio para o texto predefinido.',diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex b5b2dd979..8b8bf6264 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -2430,6 +2430,7 @@ export default {'Finding you…': 'Ищем тебя…','From': 'С','Gym reminder': 'Напоминание в зале',+ 'Checking if you made it to the gym': 'Проверяем, добрался ли ты до зала','Gym spotted': 'Зал замечен','I’m at the gym right now': 'Я сейчас в зале','Leave it empty for the default.': 'Оставь пустым для текста по умолчанию.',diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 7ac57b291..da43d404f 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -2437,6 +2437,7 @@ export default {'Finding you…': 'กำลังหาคุณ…','From': 'ตั้งแต่','Gym reminder': 'เตือนเมื่อถึงยิม',+ 'Checking if you made it to the gym': 'กำลังดูว่าคุณถึงยิมแล้วหรือยัง','Gym spotted': 'เจอยิมแล้ว','I’m at the gym right now': 'ตอนนี้ฉันอยู่ที่ยิม','Leave it empty for the default.': 'เว้นว่างไว้เพื่อใช้ข้อความเริ่มต้น',diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 73c1446d9..c38d8bbb6 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': 'Seni arıyoruz…','From': 'Başlangıç','Gym reminder': 'Salon hatırlatıcısı',+ 'Checking if you made it to the gym': 'Spor salonuna varıp varmadığına bakılıyor','Gym spotted': 'Salon göründü','I’m at the gym right now': 'Şu an salondayım','Leave it empty for the default.': 'Varsayılan metin için boş bırak.',diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 4f20def3d..c019c7aeb 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -2423,6 +2423,7 @@ export default {'Finding you…': 'Шукаємо тебе…','From': 'З','Gym reminder': 'Нагадування в залі',+ 'Checking if you made it to the gym': 'Перевіряємо, чи ти дістався до залу','Gym spotted': 'Зал помічено','I’m at the gym right now': 'Я зараз у залі','Leave it empty for the default.': 'Залиш порожнім для тексту за замовчуванням.',diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex c7e8bdfd1..5e44dd221 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -2419,6 +2419,7 @@ export default {'Finding you…': '正在定位…','From': '從','Gym reminder': '健身房提醒',+ 'Checking if you made it to the gym': '正在看看你到健身房了沒','Gym spotted': '發現健身房','I’m at the gym right now': '我現在就在健身房','Leave it empty for the default.': '留空則使用預設文字。',diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 5cbe2e163..d30dbeb02 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -2426,6 +2426,7 @@ export default {'Finding you…': '正在定位…','From': '从','Gym reminder': '健身房提醒',+ 'Checking if you made it to the gym': '正在看看你到健身房了没','Gym spotted': '发现健身房','I’m at the gym right now': '我现在就在健身房','Leave it empty for the default.': '留空则使用默认文字。',diff --git a/scripts/android/gym-reminder-approach-emulator.sh b/scripts/android/gym-reminder-approach-emulator.shnew file mode 100755index 000000000..6e9eb1ba4--- /dev/null+++ b/scripts/android/gym-reminder-approach-emulator.sh@@ -0,0 +1,152 @@+#!/usr/bin/env bash+# Proves the gym reminder's approach check and server check (#614) on the Android emulator.+#+# ANDROID_SERIAL=emulator-5590 scripts/android/gym-reminder-approach-emulator.sh <debug apk>+#+# 1. Latency with Android's REAL schedule: the proximity-alert throttle is left at its default+# (a look every 30 minutes for a background app). The phone waits in a gym's approach zone+# (650 m out) until Android notices it, which starts the short check with live location; then+# it walks in at 1.4 m/s. Measured: how long after crossing the gym's radius the notification+# shows up, and that the check (and its silent notification) ends right after.+# 2.-4. The server check before posting, with the throttle lowered to 15 s only to save the wait+# (the latency is not what these measure): a fake paired server on the host says "trained+# today" -> quiet; a server that never answers -> posts after the 3 s bound; no server -> posts.+#+# Needs a running emulator (one, -cores 2 is plenty), Node 22 and the CDP driver+# (CDP=/root/homelab/scripts/android-repro/cdp.mjs). Exits 0 when every step behaved.+set -uo pipefail+APK=${1:?debug apk}+ADB=${ADB:-/opt/android-sdk/platform-tools/adb}+CDP=${CDP:-/root/homelab/scripts/android-repro/cdp.mjs}+PKG=${PKG:-ch.duartesantos.opengym.test}+PREFS=shared_prefs/opengym_gym_reminder.xml+PORT=${PORT:-47731}+LAT=47.3769; LNG=8.5417 # the gym (Zurich), radius 100 m, approach zone 800 m+RING_LAT=47.382739 # 650 m north: inside the approach zone, outside the gym+FAR_LAT=47.4200; FAR_LNG=8.5900 # 5 km away+TODAY=$(date +%F)+TMP=$(mktemp -d)+FAIL=0++cdp() { PKG=$PKG timeout 90 node --experimental-websocket "$CDP" eval "$1" 2>&1 | grep '^=>'; }+at() { $ADB shell cmd location providers set-test-provider-location fused --location "$1,$2" --accuracy 8; }+count() { $ADB shell dumpsys notification --noredact | grep -c "Gym spotted"; }+checking() { $ADB shell dumpsys notification --noredact | grep -c "Checking if you made it"; }+note() { $ADB exec-out run-as "$PKG" cat "$PREFS" 2>/dev/null | grep -o '<string name="lastNote">[^<]*' | sed 's/.*>//'; }+foreground() {+ $ADB shell am start -n "$PKG/ch.duartesantos.opengym.MainActivity" >/dev/null 2>&1+ for i in $(seq 1 60); do+ $ADB shell cat /proc/net/unix | grep -q "webview_devtools_remote_$($ADB shell pidof $PKG | tr -d '\r')" && break+ sleep 3+ done+ sleep 8+}+background() { $ADB shell input keyevent KEYCODE_HOME; sleep 2; $ADB shell am kill "$PKG"; sleep 2; }+server() { # server <url or ''>: what the page hands over on a paired phone+ if [ -z "$1" ]; then cdp "window.Capacitor.Plugins.GymReminder.server({ server: '' }).then(() => 'server cleared')"+ else cdp "window.Capacitor.Plugins.GymReminder.server({ server: '$1', headers: { Authorization: 'Bearer emu' } }).then(() => 'server set')"; fi+}+configure() {+ cdp "window.Capacitor.Plugins.GymReminder.configure({ config: { on: true, window: null, gyms: [{ id: 'emu', name: 'Emulator gym', lat: $LAT, lng: $LNG, radius: 100, text: '' }] } }).then(r => JSON.stringify(r))"+}+new_day() { # new_day <server or ''>: as if it were tomorrow (force-stop also clears the shade)+ $ADB shell am force-stop "$PKG"; sleep 2+ $ADB exec-out run-as "$PKG" cat "$PREFS" \+ | sed -e "s#<string name=\"lastFired\">[^<]*</string>#<string name=\"lastFired\">2000-01-01</string>#" \+ -e "s#<string name=\"scanDay\">[^<]*</string>#<string name=\"scanDay\">2000-01-01</string>#" > "$TMP/prefs.xml"+ $ADB exec-in run-as "$PKG" sh -c "cat > $PREFS" < "$TMP/prefs.xml"+ foreground; status; server "$1"; configure; background+}+status() { # nothing logged today, as the page would report it+ cdp "window.Capacitor.Plugins.GymReminder.status({ trainedOn: '2000-01-01', quietOn: '', activeSince: 0, title: 'Gym spotted', body: 'Ready for your workout? 💪', channel: 'Gym reminder', scan: 'Checking if you made it to the gym' }).then(() => 'status ok')"+}+walk_in_fast() { # far, out the 90 s arming grace, then in; up to 90 s inside+ at $FAR_LAT $FAR_LNG; sleep 95+ for i in $(seq 1 18); do at $LAT $LNG; sleep 5; done+}++# The fake paired server: /api/nudge-check answers with "done" from a file.+echo false > "$TMP/done"+node -e "+ const fs = require('fs'), http = require('http')+ http.createServer((q, r) => {+ const u = new URL(q.url, 'http://x')+ console.log(new Date().toISOString(), q.method, q.url, q.headers.authorization || '')+ if (u.pathname !== '/api/nudge-check') { r.writeHead(404); return r.end() }+ const done = fs.readFileSync('$TMP/done', 'utf8').trim() === 'true'+ r.writeHead(200, { 'Content-Type': 'application/json' })+ r.end(JSON.stringify({ date: u.searchParams.get('date'), done, nudge: !done, rev: 1 }))+ }).listen($PORT, '0.0.0.0')+" > "$TMP/server.log" 2>&1 &+SRV=$!+trap 'kill $SRV 2>/dev/null; rm -rf "$TMP"' EXIT++$ADB install -r -g "$APK" >/dev/null+$ADB shell pm clear "$PKG" >/dev/null+for p in ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION ACCESS_BACKGROUND_LOCATION POST_NOTIFICATIONS; do+ $ADB shell pm grant "$PKG" "android.permission.$p" 2>/dev/null || true+done+$ADB shell cmd location set-location-enabled true+# Android's own schedule for phase 1: whatever an earlier run lowered goes back to the default.+$ADB shell settings delete global location_background_throttle_proximity_alert_interval_ms >/dev/null+echo " proximity-alert throttle: '$($ADB shell settings get global location_background_throttle_proximity_alert_interval_ms | tr -d '\r')' (null = default, 30 min)"+$ADB shell appops set com.android.shell android:mock_location allow+$ADB shell cmd location providers add-test-provider fused --supportsAltitude --supportsSpeed --supportsBearing 2>/dev/null+$ADB shell cmd location providers set-test-provider-enabled fused true+at $FAR_LAT $FAR_LNG++echo "== 1. Android's real schedule: wait in the approach zone, then walk in"+foreground+status+server "http://10.0.2.2:$PORT"+configure+background+sleep 95 # the arming grace, far away+t0=$(date +%s)+started=0+while [ $(( $(date +%s) - t0 )) -lt 2100 ]; do # up to 35 min: one full Android look and a bit+ at $RING_LAT $LNG # a phone in the zone: fixes keep coming (5 s)+ sleep 5+ case "$(note)" in *"check started"*|*"check: watching"*) started=1; break ;; esac+done+waited=$(( $(date +%s) - t0 ))+[ $started -eq 1 ] && echo " Android noticed the approach zone after ${waited} s in it: $(note)" || { echo " approach zone never noticed in ${waited} s"; FAIL=1; }+echo " silent check notification showing: $(checking)"+if [ $started -eq 1 ]; then+ lat=$RING_LAT; tin=0; t1=$(date +%s); posted=0+ for i in $(seq 1 200); do # 7 m every 5 s = 1.4 m/s, 650 m in ~7.7 min+ lat=$(awk "BEGIN{v = $lat - 0.0000629; if (v < $LAT) v = $LAT; printf \"%.7f\", v}")+ at "$lat" $LNG+ d=$(awk "BEGIN{printf \"%d\", ($lat - $LAT) * 111320}")+ [ $tin -eq 0 ] && [ "$d" -le 100 ] && tin=$(date +%s) && echo " crossed the gym's 100 m after $(( tin - t1 )) s of walking"+ sleep 5+ [ "$(count)" -gt 0 ] && { posted=1; break; }+ done+ if [ $posted -eq 1 ]; then echo " NOTIFIED $(( $(date +%s) - tin )) s after crossing into the gym"; else echo " no notification"; FAIL=1; fi+ sleep 3+ echo " last note: $(note)"+ echo " silent check notification still showing: $(checking)"; [ "$(checking)" -eq 0 ] || FAIL=1+fi+$ADB logcat -d -s OpenGymGym | tail -8 | sed 's/^/ log: /'++echo "== 2.-4. server check (throttle lowered to 15 s for these only)"+$ADB shell settings put global location_background_throttle_proximity_alert_interval_ms 15000++echo "-- 2. the server says today was trained on another device: quiet"+echo true > "$TMP/done"; new_day "http://10.0.2.2:$PORT"; walk_in_fast+n=$(count); echo " notifications: $n, note: $(note)"; [ "$n" -eq 0 ] || FAIL=1+grep -q "Bearer emu" "$TMP/server.log" && echo " server saw the pairing header" || FAIL=1++echo "-- 3. the server never answers (black-holed address): posts after the 3 s bound"+echo false > "$TMP/done"; new_day "http://10.255.255.1:9"; walk_in_fast+n=$(count); echo " notifications: $n"; [ "$n" -ge 1 ] || FAIL=1+$ADB logcat -d -s OpenGymGym | grep "server check" | tail -1 | sed 's/^/ log: /'++echo "-- 4. no server (local only): posts"+new_day ''; walk_in_fast+n=$(count); echo " notifications: $n, note: $(note)"; [ "$n" -ge 1 ] || FAIL=1++$ADB shell settings delete global location_background_throttle_proximity_alert_interval_ms >/dev/null+echo " server requests: $(grep -c nudge-check "$TMP/server.log")"+[ $FAIL -eq 0 ] && echo "== ALL GOOD" || echo "== SOMETHING DID NOT BEHAVE"+exit $FAILdiff --git a/website/privacy.html b/website/privacy.htmlindex bc8b85826..58b229885 100644--- a/website/privacy.html+++ b/website/privacy.html@@ -103,7 +103,7 @@<h1>Privacy</h1><p class="lead">This page covers the openGym apps for Android and iPhone (the APK from thissite and GitHub, the Google Play and App Store versions) and this website.- Last changed: 11 October 2026.</p>+ Last changed: 15 October 2026.</p><h2 id="short">The short version</h2><ul>@@ -113,7 +113,8 @@<li><b>Your training log stays on your phone.</b> Workouts, plans, body weight, photos andsettings are stored in the app's own storage on your device. We never receive them.</li><li><b>You decide what leaves the phone</b>, and only these things can: a backup you export,- a server you connect, the AI coach if you set it up, and Health Connect if you switch it on.</li>+ a server you connect, the AI coach if you set it up, Health Connect if you switch it on,+ and the address search of the gym reminder.</li></ul><h2 id="online">When the app goes online</h2>@@ -144,6 +145,14 @@The camera is used only when you scan your gym membership code or take a photo or video ofan exercise you add yourself; scanned images are read on the phone and never stored orsent. Notifications (workout reminder, end of a rest) are scheduled on the phone itself.</p>+ <p><b>Gym reminder</b> (phone app, off until you switch it on). Where your gyms are stays on your+ phone: not synced, not in backups, not sent to us or to your server. The phone itself notices+ when you walk in (Android's location service or iOS region monitoring), so nobody, us+ included, learns where you go. We don't want to know, honestly. Two things do go out: an+ address you search for on the map goes to OpenStreetMap's Nominatim (just the text you+ typed), and the map tiles come from OpenStreetMap. And if the phone is connected to your own+ server, it asks that server "trained today already?" when you arrive, so a workout logged on+ your laptop doesn't get you nagged. That question carries the date, not your location.</p><p><b>Deleting your data:</b> it's on your phone, so Settings → Reset or uninstalling the appremoves it. A backup file you exported is yours to keep or delete. On a server youconnected, delete your profile there.</p>