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: the approach check starts with unrestricted battery or exact alarms (Android refuses it from a proximity alert otherwise), shown as Quick arrival check; one arrival posts once; docs, changelog, emulator proof
Duarte Santos857ec77025a4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a1825f7da..986a413d5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,11 @@ your gyms in Settings → Reminders → Gym reminder: "I'm at the gym right now"OpenStreetMap map, each with its own radius and text. Once a day at most, never after you trained,never mid-workout, optionally only between certain hours. Off by default, and your gyms stay onthe phone (not on your server, not in backups). Android uses the system's own proximity alerts,-so no Google services are needed.+so no Google services are needed. Android can be slow to notice you arrived (up to half an hour),+so near a gym the phone can take a short GPS look and nudge you at the door; that needs openGym's+battery use on Unrestricted (Settings shows it as "Quick arrival check"). And if you logged a+workout on your laptop that your phone hasn't synced yet, the phone asks your server first (3+seconds at most) instead of nagging you anyway.**Security.** Five private reports, all fixed, plus our own audit. Thanks to Boris Kurktchievfor the reports, each with a patch and a test. Self-hosters: please update.diff --git a/docs/MOBILE.md b/docs/MOBILE.mdindex f8ea73941..d37c61619 100644--- a/docs/MOBILE.md+++ b/docs/MOBILE.md@@ -287,8 +287,16 @@ opens the Start screen (or the running workout).logged today, not on a day note that excuses today, not while a session started in the last12 hours runs, and only inside the optional time window (an overnight one wraps). The phonedecides when the gym is entered, from what the page last told it (`GymReminder.status`, sent- after every save of the profile and on every return to the app). A workout logged on another- device and not yet synced to this phone is not known there.+ after every save of the profile and on every return to the app).+- **Trained on another device?** A workout logged on the web or another phone that this phone has+ not synced yet: before posting, a paired phone asks its server (`GET /api/nudge-check`, the same+ few bytes the missed-day check uses) whether today is done, bounded to **3 seconds** (Android:+ a future with a timeout around `HttpURLConnection`, so a hanging DNS lookup cannot stretch it;+ iOS: an ephemeral `URLSession` with 3 s timeouts plus a hard stop). "Done" keeps it quiet and is+ remembered for the rest of the day. No server (local only), offline, an error or no answer in+ time: the phone's own status decides, as before. The page hands over the server and its headers+ with `GymReminder.server` (`lib/gym-reminder.js` `pushGymServer`); Android keeps them encrypted+ with the app's Keystore key (`NudgeCheck.seal`), iOS in the Keychain (this device only).- **Locations stay on the phone.** The gyms live only in the native side's own storage: Android`shared_prefs/opengym_gym_reminder.xml`, left out of cloud backup and device transfer(`res/xml/*_rules.xml`); iOS `Application Support/gym-reminder.json`, excluded from backups. The@@ -301,7 +309,31 @@ opens the Start screen (or the running workout).`GymReminderReceiver` gets the alert, `GymReminderBootReceiver` registers the alerts again aftera restart or an app update. An alert added while you are already inside reports an entry at once;entries in the first 90 s after arming are ignored. How soon an entry is noticed is the system's- call (a few minutes with the screen off is normal).+ call: Android's geofencing service asks for a fix only every 30 min for a background app+ (`location_background_throttle_proximity_alert_interval_ms`) and otherwise piggybacks on fixes+ other apps cause. On a phone with Google Play Services those come often; on a phone without+ (and indoors, where GPS may not get a fix at all) the nudge could come half an hour late.+- **Approach check (Android):** every gym also gets a wide proximity alert, the approach zone+ (800 m, or 5× the radius for big ones; `GymReminderRules.approachOf`). Entering it starts+ `GymScanService`, a location foreground service that asks for a fix every 15 s (fused, high+ accuracy) and stops at the first of: inside a gym (then the usual no-nag rule and the server+ check decide), beyond every approach zone + 250 m, today settled meanwhile, or **15 minutes**.+ At most **3 checks a day**, none once today is settled (fired, trained, excused, outside the+ window), so a normal day costs one check of a few minutes and the worst case is 45 min of GPS.+ Its notification is a silent one on its own channel (`gym-reminder-check`, IMPORTANCE_MIN) and+ goes away with the check (Android holds a new foreground-service notification back for up to+ 10 s, so a check that ends quickly may never show one). Catch: Android 12+ lets a background app start a foreground service+ only with an exemption, and a proximity alert is not one (checked on the emulator:+ `ForegroundServiceStartNotAllowedException`). It works with openGym's battery use on+ **Unrestricted** (started directly) or with "Alarms & reminders" allowed (an exact alarm half a+ second later starts it); the gym page shows this as "Quick arrival check" and leads to the app's+ settings. Without either, the gym's own alert still fires on the system's schedule. Trade-offs+ considered: the Play Services Geofencing API would give ~2 min latency on the `play` flavour+ without any of this (and its transitions do exempt a service start), but adds a Google+ dependency and a second code path; a periodic location poll would cost battery all day for one+ arrival. Google Play: the `play` flavour now also declares a `location` foreground service type,+ which needs the foreground-service declaration in the Play Console next to the background+ location one (same feature, same video).- **iOS:** region monitoring (`CLLocationManager`, `GymReminderPlugin.swift`). Needs **Always**location and Precise Location; no background location mode is declared (region monitoring doesnot need one). iOS relaunches the app in the background on arrival; `AppDelegate` makes@@ -317,6 +349,13 @@ every 30 min on its own (`location_background_throttle_proximity_alert_interval_whenever other apps get fixes; the script lowers it to 15 s. On a real phone that means the nudgeusually comes within minutes, at worst about half an hour after you walk in.+`scripts/android/gym-reminder-approach-emulator.sh <debug apk>` (EXEMPT=battery|alarm|none) proves+the approach check with the throttle left at Android's default: the app is closed, the phone+waits in the approach zone, the check starts (its location request shows in `dumpsys location`),+then the phone walks in at 1.4 m/s and the time from crossing the radius to the notification is+measured; then the server check against a fake paired server on the host (trained elsewhere:+quiet; a black-holed server: posts after the 3 s bound; no server: posts).+## Prerequisites- Node 20+diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xmlindex fd3aa0375..87600223f 100644--- a/frontend/android/app/src/main/AndroidManifest.xml+++ b/frontend/android/app/src/main/AndroidManifest.xml@@ -93,7 +93,8 @@android:exported="false" /><!-- Gym reminder: the short check with live location after the phone entered a gym's wideapproach 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. -->+ is a silent one. Started by the approach alert's broadcast (Android 12+: only with+ unrestricted battery or exact alarms allowed, see GymReminder.launchCheck), never exported. --><serviceandroid:name=".GymScanService"android:exported="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 94309bf04..8bd75a59c 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@@ -76,6 +76,7 @@ final class GymReminder {static final long SERVER_CHECK_MS = 3_000L;static String actionEnter(Context ctx) { return ctx.getPackageName() + ".GYM_ENTER"; }+ static String actionCheck(Context ctx) { return ctx.getPackageName() + ".GYM_CHECK"; }static String actionOpen(Context ctx) { return ctx.getPackageName() + ".GYM_REMINDER_OPEN"; }private GymReminder() {}@@ -258,21 +259,69 @@ final class GymReminder {note(ctx, "near " + gymId + ": no check (3 today)");return;}+ String how = launchCheck(ctx);+ if (how == null) {+ // Android 12+ refuses a foreground service from the background unless the app may+ // set exact alarms or runs with unrestricted battery: the gym's own alert still+ // fires, just on the system's slower schedule.+ note(ctx, "near " + gymId + ": check refused (background start not allowed)");+ return;+ }+ p.edit().putString("scanDay", today).putInt("scans", count + 1).apply();+ note(ctx, "near " + gymId + ": check started (" + how + ")");+ }++ /**+ * Starts GymScanService. Android 12+ lets a background app start a foreground service only+ * with an exemption: unrestricted battery (works directly), or the right to set exact alarms+ * (an exact alarm a moment later may start it: GymReminderReceiver, actionCheck). Returns how+ * it went ("direct", "alarm"), or null when neither is possible.+ */+ static String launchCheck(Context ctx) {+ if (startScan(ctx)) return "direct";+ if (Build.VERSION.SDK_INT < 31) return null;+ android.app.AlarmManager am = (android.app.AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);+ if (am == null || !am.canScheduleExactAlarms()) return null;+ Intent i = new Intent(ctx, GymReminderReceiver.class).setAction(actionCheck(ctx));+ PendingIntent pi = PendingIntent.getBroadcast(ctx, REQUEST_BASE + 2 * MAX_GYMS, i, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);+ try {+ am.setExactAndAllowWhileIdle(android.app.AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 500, pi);+ return "alarm";+ } catch (SecurityException e) {+ return null;+ }+ }++ /**+ * Whether the approach check can start with the app in the background: always before+ * Android 12; from 12 on with unrestricted battery or with the right to set exact alarms.+ */+ static boolean quickCheckAllowed(Context ctx) {+ if (Build.VERSION.SDK_INT < 31) return true;+ android.os.PowerManager pm = (android.os.PowerManager) ctx.getSystemService(Context.POWER_SERVICE);+ if (pm != null && pm.isIgnoringBatteryOptimizations(ctx.getPackageName())) return true;+ android.app.AlarmManager am = (android.app.AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);+ return am != null && am.canScheduleExactAlarms();+ }++ /** True when the check's foreground service could be started from here. */+ static boolean startScan(Context ctx) {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");+ return true;} 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() + ")");+ Log.i(TAG, "check: start refused (" + e.getClass().getSimpleName() + ")");+ return false;}}- /** 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) {+ /**+ * Applies the no-nag rule for arriving at `gymId` now, and posts if it says so. True if posted.+ * One at a time: the gym's own alert and the approach check can both see the same arrival.+ */+ static synchronized boolean arrive(Context ctx, String gymId, Calendar now) {JSONObject c = config(ctx);if (c == null) return false;JSONObject st = status(ctx);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 84d58285f..04a009759 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@@ -77,6 +77,8 @@ public class GymReminderPlugin extends Plugin {else r.put("background", "prompt");android.app.NotificationManager nm = (android.app.NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);r.put("notifications", nm != null && nm.areNotificationsEnabled() ? "granted" : "denied");+ // Whether the approach check may start from the background (GymReminder.launchCheck).+ r.put("quick", GymReminder.quickCheckAllowed(ctx) ? "granted" : "off");return r;}diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderReceiver.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderReceiver.javaindex 40d4a3b1d..ea8fbbe2e 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderReceiver.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderReceiver.java@@ -4,11 +4,18 @@ import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;-/** A gym's proximity alert fired (GymReminder). Explicit and not exported: only the system's alert reaches it. */+/** A gym's proximity alert fired, or the alarm that starts the approach check (GymReminder). Explicit and not exported: only the system's alert and alarm reach it. */public class GymReminderReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {- if (intent == null || !GymReminder.actionEnter(context).equals(intent.getAction())) return;+ if (intent == null) return;+ if (GymReminder.actionCheck(context).equals(intent.getAction())) {+ // The exact alarm GymReminder.launchCheck set: its delivery may start the check.+ boolean ok = GymReminder.startScan(context.getApplicationContext());+ if (!ok) GymReminder.note(context.getApplicationContext(), "check: refused at the alarm too");+ return;+ }+ if (!GymReminder.actionEnter(context).equals(intent.getAction())) return;final PendingResult pending = goAsync();final Context app = context.getApplicationContext();new Thread(() -> {diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex ccb8a7a7f..dc13203b9 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -2482,6 +2482,9 @@ export default {'From': 'من','Gym reminder': 'تذكير الصالة','Checking if you made it to the gym': 'نتحقق إن كنت وصلت إلى النادي',+ 'Quick arrival check': 'فحص سريع عند الوصول',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'قرب النادي يلقي الهاتف نظرة قصيرة عبر GPS (بضع دقائق على الأكثر) ليصلك التذكير عند الباب.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'قد يحتاج أندرويد حتى نصف ساعة ليلاحظ أنك وصلت. اضبط استخدام البطارية لـ openGym على «غير مقيّد» وسيلقي الهاتف نظرة قصيرة عبر GPS قرب النادي، فيصلك التذكير عند الباب.','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 f6a24f488..cff733c5c 100644--- a/frontend/src/locales/bn.js+++ b/frontend/src/locales/bn.js@@ -2506,6 +2506,9 @@ export default {'From': 'থেকে','Gym reminder': 'জিম রিমাইন্ডার','Checking if you made it to the gym': 'দেখছি তুমি জিমে পৌঁছেছ কি না',+ 'Quick arrival check': 'দ্রুত পৌঁছানোর চেক',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'জিমের কাছে ফোন অল্প সময় GPS দিয়ে দেখে নেয় (বড়জোর কয়েক মিনিট), যাতে দরজাতেই মনে করিয়ে দেয়।',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'তুমি পৌঁছেছ সেটা বুঝতে Android-এর আধা ঘণ্টা পর্যন্ত লাগতে পারে। openGym-এর ব্যাটারি ব্যবহার Unrestricted করে দাও, তাহলে জিমের কাছে ফোন অল্প সময় GPS দিয়ে দেখে নেবে আর দরজাতেই মনে করিয়ে দেবে।','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 62569cb20..b98b21f84 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -2447,6 +2447,9 @@ export default {'From': 'Von','Gym reminder': 'Gym-Erinnerung','Checking if you made it to the gym': 'Schaue, ob du es ins Gym geschafft hast',+ 'Quick arrival check': 'Schneller Ankunfts-Check',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'In der Nähe eines Gyms schaut das Handy kurz per GPS nach (höchstens ein paar Minuten), damit der Stupser schon an der Tür kommt.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android merkt manchmal erst nach einer halben Stunde, dass du angekommen bist. Stell den Akkuverbrauch von openGym auf „Uneingeschränkt“, dann schaut das Handy in der Nähe eines Gyms kurz per GPS nach und der Stupser kommt an der Tür.','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 627f50cf0..7af08d227 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -2427,6 +2427,9 @@ export default {'From': 'Desde','Gym reminder': 'Recordatorio del gimnasio','Checking if you made it to the gym': 'Comprobando si llegaste al gimnasio',+ 'Quick arrival check': 'Aviso rápido de llegada',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Cerca de un gimnasio, el móvil echa un vistazo corto con GPS (unos minutos como mucho) para que el aviso llegue en la puerta.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android puede tardar hasta media hora en notar que llegaste. Pon el uso de batería de openGym en Sin restricciones y el móvil echará un vistazo corto con GPS cerca de un gimnasio, así el aviso llega en la puerta.','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 81f53d18c..e47ae3ee7 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -2427,6 +2427,9 @@ export default {'From': 'De','Gym reminder': 'Rappel à la salle','Checking if you made it to the gym': 'On vérifie si tu es arrivé à la salle',+ 'Quick arrival check': 'Détection rapide à l’arrivée',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Près d’une salle, le téléphone jette un coup d’œil GPS rapide (quelques minutes au plus) pour que le rappel arrive à la porte.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android peut mettre jusqu’à une demi-heure à remarquer que tu es arrivé. Règle l’utilisation de la batterie d’openGym sur Non restreinte et le téléphone jette un coup d’œil GPS près d’une salle, pour que le rappel arrive à la porte.','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 9f9208bce..d4a23e862 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -2427,6 +2427,9 @@ export default {'From': 'से','Gym reminder': 'जिम रिमाइंडर','Checking if you made it to the gym': 'देख रहे हैं कि आप जिम पहुँचे या नहीं',+ 'Quick arrival check': 'जल्दी पहुँचने की जाँच',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'जिम के पास फ़ोन थोड़ी देर GPS से देख लेता है (ज़्यादा से ज़्यादा कुछ मिनट), ताकि याद दिलाना दरवाज़े पर ही आ जाए।',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android को यह पता चलने में आधा घंटा तक लग सकता है कि आप पहुँच गए। openGym का बैटरी इस्तेमाल Unrestricted कर दें, तो जिम के पास फ़ोन थोड़ी देर GPS से देख लेगा और याद दिलाना दरवाज़े पर आएगा।','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 14eaf881e..92bbde15c 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -2430,6 +2430,9 @@ export default {'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',+ 'Quick arrival check': 'Gyors érkezésfigyelés',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Edzőterem közelében a telefon rövid ideig GPS-szel néz körül (legfeljebb pár percig), hogy az emlékeztető már az ajtóban jöjjön.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Az Android akár fél óra múlva veszi csak észre, hogy megérkeztél. Állítsd az openGym akkuhasználatát Korlátlanra, és edzőterem közelében a telefon rövid ideig GPS-szel néz körül, így az emlékeztető az ajtóban jön.','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 3a2f8c114..2e018cceb 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -2427,6 +2427,9 @@ export default {'From': 'Dalle','Gym reminder': 'Promemoria palestra','Checking if you made it to the gym': 'Controllo se sei arrivato in palestra',+ 'Quick arrival check': 'Controllo rapido all’arrivo',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Vicino a una palestra il telefono dà una breve occhiata col GPS (qualche minuto al massimo) così il promemoria arriva alla porta.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android può metterci fino a mezz’ora ad accorgersi che sei arrivato. Imposta l’uso della batteria di openGym su Senza restrizioni e vicino a una palestra il telefono dà una breve occhiata col GPS, così il promemoria arriva alla porta.','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 702caeb63..76b8c8324 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -2427,6 +2427,9 @@ export default {'From': '시작','Gym reminder': '헬스장 알림','Checking if you made it to the gym': '헬스장에 도착했는지 확인하는 중',+ 'Quick arrival check': '빠른 도착 확인',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': '헬스장 근처에서 휴대폰이 잠깐 GPS로 확인해요(길어야 몇 분). 그래서 알림이 문 앞에서 와요.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android는 도착을 알아차리는 데 30분까지 걸릴 수 있어요. openGym의 배터리 사용을 제한 없음으로 바꾸면 헬스장 근처에서 잠깐 GPS로 확인해서 알림이 문 앞에서 와요.','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 b305e051a..cf3725ac0 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -2427,6 +2427,9 @@ export default {'From': 'Od','Gym reminder': 'Przypomnienie na siłowni','Checking if you made it to the gym': 'Sprawdzam, czy dotarłeś na siłownię',+ 'Quick arrival check': 'Szybkie wykrycie przyjścia',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'W pobliżu siłowni telefon na chwilę zerka na GPS (najwyżej kilka minut), żeby przypomnienie przyszło już przy drzwiach.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android potrafi zauważyć twoje przyjście nawet po pół godzinie. Ustaw zużycie baterii openGym na Bez ograniczeń, a telefon w pobliżu siłowni na chwilę zerknie na GPS i przypomnienie przyjdzie przy drzwiach.','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 c3f347954..dfb997107 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1548,6 +1548,9 @@ export const PT_BR_OVERRIDES = {'From': 'Das','Gym reminder': 'Lembrete da academia','Checking if you made it to the gym': 'Vendo se você chegou na academia',+ 'Quick arrival check': 'Detecção rápida na chegada',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Perto de uma academia, o celular dá uma olhada rápida no GPS (alguns minutos no máximo) para o lembrete chegar na porta.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'O Android pode levar até meia hora para perceber que você chegou. Coloque o uso de bateria do openGym em Sem restrições e o celular dá uma olhada rápida no GPS perto de uma academia, para o lembrete chegar na porta.','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 6232bb0fd..c865dfd28 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -2427,6 +2427,9 @@ export default {'From': 'Das','Gym reminder': 'Lembrete do ginásio','Checking if you made it to the gym': 'A ver se chegaste ao ginásio',+ 'Quick arrival check': 'Deteção rápida à chegada',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Perto de um ginásio, o telemóvel dá uma espreitadela curta com GPS (uns minutos no máximo) para o lembrete chegar à porta.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'O Android pode demorar até meia hora a perceber que chegaste. Põe a utilização da bateria do openGym em Sem restrições e o telemóvel dá uma espreitadela curta com GPS perto de um ginásio, para o lembrete chegar à porta.','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 8b8bf6264..318f97832 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -2431,6 +2431,9 @@ export default {'From': 'С','Gym reminder': 'Напоминание в зале','Checking if you made it to the gym': 'Проверяем, добрался ли ты до зала',+ 'Quick arrival check': 'Быстрая проверка прихода',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Рядом с залом телефон ненадолго включает GPS (максимум на несколько минут), чтобы напоминание пришло уже у двери.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android может заметить, что ты пришёл, только через полчаса. Поставь для openGym расход батареи «Без ограничений», и рядом с залом телефон ненадолго глянет по GPS, так что напоминание придёт у двери.','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 da43d404f..518e2a067 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -2438,6 +2438,9 @@ export default {'From': 'ตั้งแต่','Gym reminder': 'เตือนเมื่อถึงยิม','Checking if you made it to the gym': 'กำลังดูว่าคุณถึงยิมแล้วหรือยัง',+ 'Quick arrival check': 'ตรวจการมาถึงแบบเร็ว',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'เมื่อใกล้ยิม โทรศัพท์จะเปิด GPS ดูแป๊บหนึ่ง (อย่างมากไม่กี่นาที) การแจ้งเตือนจะมาถึงตอนอยู่หน้าประตู',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android อาจใช้เวลาถึงครึ่งชั่วโมงกว่าจะรู้ว่าคุณมาถึงแล้ว ตั้งการใช้แบตเตอรี่ของ openGym เป็น "ไม่จำกัด" แล้วโทรศัพท์จะเปิด GPS ดูแป๊บหนึ่งเมื่อใกล้ยิม การแจ้งเตือนจะมาถึงตอนอยู่หน้าประตู','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 c38d8bbb6..e71e0557f 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -2427,6 +2427,9 @@ export default {'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',+ 'Quick arrival check': 'Hızlı varış kontrolü',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Spor salonuna yakınken telefon kısa bir GPS bakışı atar (en fazla birkaç dakika), hatırlatma kapıda gelir.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android geldiğini fark etmek için yarım saate kadar sürebilir. openGym’in pil kullanımını Kısıtlanmamış yap, telefon spor salonuna yakınken kısa bir GPS bakışı atsın, hatırlatma kapıda gelsin.','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 c019c7aeb..ee15f4bf7 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -2424,6 +2424,9 @@ export default {'From': 'З','Gym reminder': 'Нагадування в залі','Checking if you made it to the gym': 'Перевіряємо, чи ти дістався до залу',+ 'Quick arrival check': 'Швидка перевірка приходу',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': 'Біля залу телефон ненадовго вмикає GPS (щонайбільше кілька хвилин), щоб нагадування прийшло вже біля дверей.',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android може помітити, що ти прийшов, лише за пів години. Постав для openGym використання батареї «Без обмежень», і біля залу телефон ненадовго гляне через GPS, тож нагадування прийде біля дверей.','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 5e44dd221..c4ce92626 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -2420,6 +2420,9 @@ export default {'From': '從','Gym reminder': '健身房提醒','Checking if you made it to the gym': '正在看看你到健身房了沒',+ 'Quick arrival check': '到達快速偵測',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': '靠近健身房時,手機會用 GPS 短暫看一下(最多幾分鐘),提醒在門口就到。',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android 可能要半小時才發現你到了。把 openGym 的電池使用設為「無限制」,手機在健身房附近會用 GPS 短暫看一下,提醒在門口就到。','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 d30dbeb02..47f412c3e 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -2427,6 +2427,9 @@ export default {'From': '从','Gym reminder': '健身房提醒','Checking if you made it to the gym': '正在看看你到健身房了没',+ 'Quick arrival check': '到达快速检测',+ 'Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.': '靠近健身房时,手机会用 GPS 短暂看一下(最多几分钟),提醒在门口就到。',+ 'Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.': 'Android 可能要半小时才发现你到了。把 openGym 的电池使用设为“无限制”,手机在健身房附近会用 GPS 短暂看一下,提醒在门口就到。','Gym spotted': '发现健身房','I’m at the gym right now': '我现在就在健身房','Leave it empty for the default.': '留空则使用默认文字。',diff --git a/frontend/src/views/GymReminder.jsx b/frontend/src/views/GymReminder.jsxindex 0e7c0e67a..9dc51bf92 100644--- a/frontend/src/views/GymReminder.jsx+++ b/frontend/src/views/GymReminder.jsx@@ -155,6 +155,13 @@ export default function GymReminderPage() {accessory={perm.background === 'granted' ? 'none' : 'chevron'}onClick={perm.background === 'granted' ? undefined : () => openAppSettings()} /></Section>}+ {perm?.quick && perm.background === 'granted' && <Section footer={perm.quick === 'granted'+ ? t('Near a gym, the phone takes a short GPS look (a few minutes at most) so the nudge comes at the door.')+ : t('Android can take up to half an hour to notice you walked in. Set openGym’s battery use to Unrestricted and the phone takes a short GPS look when you get near a gym, so the nudge comes at the door.')}>+ <Row icon="bolt" iconTint="var(--orange)" title={t('Quick arrival check')} value={perm.quick === 'granted' ? t('On') : t('Off')}+ accessory={perm.quick === 'granted' ? 'none' : 'chevron'}+ onClick={perm.quick === 'granted' ? undefined : () => openAppSettings()} />+ </Section>}</>}diff --git a/frontend/src/views/GymReminder.test.jsx b/frontend/src/views/GymReminder.test.jsxindex 44ec82618..6d2afdd57 100644--- a/frontend/src/views/GymReminder.test.jsx+++ b/frontend/src/views/GymReminder.test.jsx@@ -142,6 +142,26 @@ describe('Gym reminder page', () => {expect(host.textContent).toContain('Only while using the app')expect(host.textContent).toContain('needs location access in the background')})+ it('Android, quick arrival check not allowed: says why and leads to the settings; allowed: just On', async () => {+ const { openAppSettings } = await import('../lib/gym-reminder.js')+ mocks.perm = { location: 'granted', background: 'granted', notifications: 'granted', quick: 'off' }+ await render(<GymReminderPage />)+ expect(rowByText('Quick arrival check').textContent).toContain('Off')+ expect(host.textContent).toContain('up to half an hour')+ await click(rowByText('Quick arrival check'))+ expect(openAppSettings).toHaveBeenCalled()+ act(() => root.unmount()); host.remove()+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+ mocks.perm = { ...mocks.perm, quick: 'granted' }+ await render(<GymReminderPage />)+ expect(rowByText('Quick arrival check').textContent).toContain('On')+ expect(host.textContent).toContain('a few minutes at most')+ })+ it('iOS (no quick flag): no such row', async () => {+ mocks.perm = { location: 'granted', background: 'granted', notifications: 'granted' }+ await render(<GymReminderPage />)+ expect(host.textContent).not.toContain('Quick arrival check')+ })})describe('one gym', () => {diff --git a/scripts/android/gym-reminder-approach-emulator.sh b/scripts/android/gym-reminder-approach-emulator.shindex 6e9eb1ba4..4e02cfe7a 100755--- a/scripts/android/gym-reminder-approach-emulator.sh+++ b/scripts/android/gym-reminder-approach-emulator.sh@@ -1,7 +1,11 @@#!/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>+# ANDROID_SERIAL=emulator-5590 [EXEMPT=battery|alarm|none] scripts/android/gym-reminder-approach-emulator.sh <debug apk>+#+# EXEMPT: how the app may start the check from the background on Android 12+ (battery =+# "Unrestricted" battery, the default here; alarm = "Alarms & reminders" allowed; none = neither,+# then the check is refused and only the gym's own alert is left).## 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@@ -21,6 +25,7 @@ CDP=${CDP:-/root/homelab/scripts/android-repro/cdp.mjs}PKG=${PKG:-ch.duartesantos.opengym.test}PREFS=shared_prefs/opengym_gym_reminder.xmlPORT=${PORT:-47731}+EXEMPT=${EXEMPT:-battery}LAT=47.3769; LNG=8.5417 # the gym (Zurich), radius 100 m, approach zone 800 mRING_LAT=47.382739 # 650 m north: inside the approach zone, outside the gymFAR_LAT=47.4200; FAR_LNG=8.5900 # 5 km away@@ -30,8 +35,8 @@ FAIL=0cdp() { 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"; }+count() { $ADB shell dumpsys notification --noredact | grep -c "android.title=String (Gym spotted"; }+checking() { $ADB shell dumpsys notification --noredact | grep -c "android.title=String (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@@ -83,10 +88,17 @@ trap 'kill $SRV 2>/dev/null; rm -rf "$TMP"' EXIT$ADB install -r -g "$APK" >/dev/null$ADB shell pm clear "$PKG" >/dev/null+$ADB logcat -cfor 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 || truedone$ADB shell cmd location set-location-enabled true+$ADB shell dumpsys deviceidle whitelist -"$PKG" >/dev/null 2>&1; $ADB shell appops set "$PKG" SCHEDULE_EXACT_ALARM default+case "$EXEMPT" in+ battery) $ADB shell dumpsys deviceidle whitelist +"$PKG" >/dev/null ;;+ alarm) $ADB shell appops set "$PKG" SCHEDULE_EXACT_ALARM allow ;;+esac+echo " exemption: $EXEMPT"# 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/nullecho " proximity-alert throttle: '$($ADB shell settings get global location_background_throttle_proximity_alert_interval_ms | tr -d '\r')' (null = default, 30 min)"@@ -107,11 +119,13 @@ started=0while [ $(( $(date +%s) - t0 )) -lt 2100 ]; do # up to 35 min: one full Android look and a bitat $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+ case "$(note)" in *"check started"*|*"check: watching"*) started=1; break ;; *refused*) break ;; esacdonewaited=$(( $(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)"+$ADB shell dumpsys location | grep -A1 -i "$PKG" | grep -i "interval\|Request\|@" | head -3 | sed 's/^ */ location request: /'+[ "$EXEMPT" = none ] && { echo " (no exemption: refused as expected)"; [ $started -eq 0 ] && FAIL=0; $ADB logcat -d -s OpenGymGym | tail -3 | sed 's/^/ log: /'; exit $FAIL; }if [ $started -eq 1 ]; thenlat=$RING_LAT; tin=0; t1=$(date +%s); posted=0for i in $(seq 1 200); do # 7 m every 5 s = 1.4 m/s, 650 m in ~7.7 min@@ -125,6 +139,7 @@ if [ $started -eq 1 ]; thenif [ $posted -eq 1 ]; then echo " NOTIFIED $(( $(date +%s) - tin )) s after crossing into the gym"; else echo " no notification"; FAIL=1; fisleep 3echo " last note: $(note)"+ np=$($ADB logcat -d -s OpenGymGym | grep -c ': posted'); echo " posted: $np time(s) (the gym's own alert and the check can both see the arrival)"; [ "$np" -eq 1 ] || FAIL=1echo " silent check notification still showing: $(checking)"; [ "$(checking)" -eq 0 ] || FAIL=1fi$ADB logcat -d -s OpenGymGym | tail -8 | sed 's/^/ log: /'