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 (#614): a nudge when you walk into your gym
Duarte Santos95266a02f910
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.ymlindex 0c803dd02..751583d4b 100644--- a/.github/workflows/ios.yml+++ b/.github/workflows/ios.yml@@ -54,6 +54,12 @@ jobs:run: |set -o pipefailswift test 2>&1 | tail -60+ # The gym reminder's no-nag rule (#614), compiled into the iPhone app, tested on the Mac.+ - name: GymReminderCore tests+ working-directory: frontend/ios/App/GymReminderCore+ run: |+ set -o pipefail+ swift test 2>&1 | tail -60# The widgets and the Live Activity's extension, likewise until it is committed.- run: ruby ios/ci/add-widgets.rbworking-directory: frontenddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 35407fe8b..a1825f7da 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,13 @@## Unreleased+**Gym reminder** (#614, phone app). Walk into your gym and openGym nudges you to hit Start. Add+your gyms in Settings → Reminders → Gym reminder: "I'm at the gym right now" or a pin on an+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 on+the phone (not on your server, not in backups). Android uses the system's own proximity alerts,+so no Google services are needed.+**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 c283d4b0c..94fed1145 100644--- a/docs/MOBILE.md+++ b/docs/MOBILE.md@@ -272,6 +272,46 @@ Worth checking on a device: picking 720 px starts a download that shows its proganimation sharpens once it is done; Delete frees the space and the animation falls back; oncellular with Wi-Fi only on, it waits; Still only shows stills everywhere a workout shows media.+### Gym reminder (#614)++Settings → Reminders → **Gym reminder**, in the phone app only (the web build has no such page:+a browser cannot watch where you are with the page closed). Off by default. Add gyms with "I'm at+the gym right now" (the phone's position) or a pin on an OpenStreetMap map (Leaflet; the address+search asks Nominatim, only on an explicit tap of Search, with a User-Agent naming the app). Each+gym has a radius (100 m by default, 50 to 500) and an optional text. Up to 20 gyms (iOS watches at+most 20 regions per app). Walking into one posts "Gym spotted. Ready for your workout? 💪"; a tap+opens the Start screen (or the running workout).++- **No nagging** (`src/lib/gym-reminder.js` `skipReason`, the same rule in+ `GymReminderRules.java` and `ios/App/GymReminderCore`): at most once a day, not after a workout+ logged today, not on a day note that excuses today, not while a session started in the last+ 12 hours runs, and only inside the optional time window (an overnight one wraps). The phone+ decides 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.+- **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+ WebView's storage keeps only an on/off flag (it is part of phone backups), the synced profile+ and backup files never see any of it.+- **Android:** the platform's proximity alerts (`LocationManager.addProximityAlert`), no Google+ Play Services, so the APK and F-Droid builds have it too. Location while in use is asked when+ you add a gym from where you stand; "Allow all the time" (`ACCESS_BACKGROUND_LOCATION`) only+ after the in-app explainer, and from Android 11 on that is the system's settings page.+ `GymReminderReceiver` gets the alert, `GymReminderBootReceiver` registers the alerts again after+ a 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).+- **iOS:** region monitoring (`CLLocationManager`, `GymReminderPlugin.swift`). Needs **Always**+ location and Precise Location; no background location mode is declared (region monitoring does+ not need one). iOS relaunches the app in the background on arrival; `AppDelegate` makes+ `GymReminderCenter` the location delegate at launch so the event lands. On an iPhone with an+ Apple Watch the notification shows on the watch as usual.++Testing on the Android emulator: add a gym, wait 90 s, `adb emu geo fix <lng> <lat>` somewhere+far away, then inside the radius; the notification arrives within a minute or two+(`scripts/android/gym-reminder-emulator.sh` does exactly that).+## Prerequisites- Node 20+diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xmlindex a63377cb0..cf48356ca 100644--- a/frontend/android/app/src/main/AndroidManifest.xml+++ b/frontend/android/app/src/main/AndroidManifest.xml@@ -86,6 +86,22 @@android:permission="android.permission.BIND_JOB_SERVICE"android:exported="false" />+ <!-- Gym reminder (#614): the platform's proximity alert for a gym fires this (GymReminder).+ Explicit, not exported: nothing but that alert's own PendingIntent reaches it. -->+ <receiver+ android:name=".GymReminderReceiver"+ android:exported="false" />+ <!-- Proximity alerts are gone after a restart or an app update: registered again here.+ Only the system sends these two broadcasts. -->+ <receiver+ android:name=".GymReminderBootReceiver"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.BOOT_COMPLETED" />+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+ </intent-filter>+ </receiver>+<!-- Gym check-in scanner (@capacitor-mlkit/barcode-scanning): pre-fetch the ML Kitbarcode model at install time so the first scan doesn't wait on a download. --><meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="barcode_ui" />@@ -125,6 +141,20 @@<uses-permission android:name="android.permission.health.WRITE_EXERCISE" /><uses-permission android:name="android.permission.health.WRITE_WEIGHT" />+ <!-- Gym reminder (#614), off until switched on in Settings: where the phone is, for "I'm at+ the gym right now" and to watch the gyms the user added with the platform's proximity+ alerts (no Google Play Services). Background location ("Allow all the time") is asked for+ separately, after an explanation in the app, because the alert has to fire with openGym+ closed. The places never leave the phone. -->+ <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" />+ <!-- Location is optional: a phone without GPS still installs the app (the permissions above+ would otherwise make Google Play require the hardware). -->+ <uses-feature android:name="android.hardware.location" android:required="false" />+ <uses-feature android:name="android.hardware.location.gps" android:required="false" />+ <uses-feature android:name="android.hardware.location.network" android:required="false" />+<!-- Whether the Health Connect app is there, on Android 13 and lower. --><queries><package android:name="com.google.android.apps.healthdata" />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.javanew file mode 100644index 000000000..06e58406a--- /dev/null+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminder.java@@ -0,0 +1,219 @@+package ch.duartesantos.opengym;++import android.Manifest;+import android.app.Notification;+import android.app.NotificationChannel;+import android.app.NotificationManager;+import android.app.PendingIntent;+import android.content.Context;+import android.content.Intent;+import android.content.SharedPreferences;+import android.content.pm.PackageManager;+import android.location.LocationManager;+import android.os.Build;+import java.util.Calendar;+import org.json.JSONArray;+import org.json.JSONObject;++/**+ * The gym reminder (#614): a notification when the phone walks into one of the user's gyms.+ *+ * The platform's own proximity alerts (LocationManager.addProximityAlert) watch the gyms, so it+ * works without Google Play Services (the APK and F-Droid builds too) and with the app closed; the+ * system hands GymReminderReceiver a broadcast on entering, which decides with GymReminderRules+ * whether to post. Proximity alerts do not survive a restart or an app update:+ * GymReminderBootReceiver registers them again.+ *+ * 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+ * backup and device transfer (res/xml/backup_rules.xml, data_extraction_rules.xml): the places+ * stay on this phone, and never go to the user's server either.+ */+final class GymReminder {+ static final String PREFS = "opengym_gym_reminder";+ static final String CHANNEL_ID = "gym-reminder";+ static final int NOTIFICATION_ID = 3000;+ static final int MAX_GYMS = 20;+ /** The request codes of the proximity alerts' PendingIntents: one per gym slot. */+ private static final int REQUEST_BASE = 46_300;+ /**+ * An alert reports "entering" as soon as it is added while the phone is already inside, which+ * would ping right after "I'm at the gym right now". Entries this soon after arming are ignored.+ */+ static final long ARM_GRACE_MS = 90_000L;++ static String actionEnter(Context ctx) { return ctx.getPackageName() + ".GYM_ENTER"; }+ static String actionOpen(Context ctx) { return ctx.getPackageName() + ".GYM_REMINDER_OPEN"; }++ private GymReminder() {}++ private static SharedPreferences prefs(Context ctx) {+ return ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE);+ }++ // ---------------------------------------------------------------- what is kept++ static void saveConfig(Context ctx, JSONObject config) {+ prefs(ctx).edit().putString("config", config.toString()).apply();+ }++ static JSONObject config(Context ctx) {+ try {+ String s = prefs(ctx).getString("config", null);+ return s == null ? null : new JSONObject(s);+ } catch (Exception e) {+ return null;+ }+ }++ static void saveStatus(Context ctx, JSONObject status) {+ prefs(ctx).edit().putString("status", status.toString()).apply();+ }++ static JSONObject status(Context ctx) {+ try {+ String s = prefs(ctx).getString("status", null);+ return s == null ? new JSONObject() : new JSONObject(s);+ } catch (Exception e) {+ return new JSONObject();+ }+ }++ // ---------------------------------------------------------------- permissions++ static boolean hasFine(Context ctx) {+ return ctx.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;+ }++ /** Before Android 10 there is no separate background permission: the location one covers it. */+ static boolean hasBackground(Context ctx) {+ if (Build.VERSION.SDK_INT < 29) return hasFine(ctx);+ return ctx.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;+ }++ // ---------------------------------------------------------------- watching++ 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);+ // 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);+ }++ /** 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++) {+ PendingIntent pi = alertIntent(ctx, slot, null, PendingIntent.FLAG_NO_CREATE);+ if (pi == null) continue;+ try {+ if (lm != null) lm.removeProximityAlert(pi);+ } catch (Exception ignored) {+ // no permission any more: the system dropped it already+ }+ pi.cancel();+ }+ prefs(ctx).edit().putInt("watching", 0).apply();+ }++ /**+ * Watches the saved gyms, or nothing when the reminder is off or location may not be used.+ * Returns how many gyms are watched.+ */+ static int register(Context ctx) {+ unregister(ctx);+ JSONObject c = config(ctx);+ if (c == null || !c.optBoolean("on", false) || !hasFine(ctx)) return 0;+ LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);+ if (lm == null) return 0;+ JSONArray gyms = c.optJSONArray("gyms");+ int n = 0;+ for (int slot = 0; gyms != null && slot < gyms.length() && slot < MAX_GYMS; slot++) {+ JSONObject g = gyms.optJSONObject(slot);+ if (g == null) continue;+ double lat = g.optDouble("lat", Double.NaN), lng = g.optDouble("lng", Double.NaN);+ float radius = (float) Math.max(50, Math.min(500, g.optDouble("radius", 100)));+ 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));+ n++;+ } catch (SecurityException e) {+ break;+ }+ }+ prefs(ctx).edit().putInt("watching", n).putLong("armedAt", System.currentTimeMillis()).apply();+ return n;+ }++ static int watching(Context ctx) {+ return prefs(ctx).getInt("watching", 0);+ }++ // ---------------------------------------------------------------- arriving++ /** From GymReminderReceiver: a proximity alert fired. */+ static void onAlert(Context ctx, Intent intent) {+ 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());+ }++ /** 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);+ JSONObject win = c.optJSONObject("window");+ JSONArray gyms = c.optJSONArray("gyms");+ SharedPreferences p = prefs(ctx);+ String why = 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;+ JSONObject gym = null;+ for (int i = 0; gyms != null && i < gyms.length(); i++) {+ JSONObject g = gyms.optJSONObject(i);+ if (g != null && g.optString("id", "").equals(gymId)) gym = g;+ }+ String title = st.optString("title", "");+ String body = gym != null && !gym.optString("text", "").trim().isEmpty() ? gym.optString("text") : st.optString("body", "");+ if (title.isEmpty()) title = "Gym spotted";+ 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();+ return true;+ }++ 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;+ if (Build.VERSION.SDK_INT >= 26 && nm.getNotificationChannel(CHANNEL_ID) == null) {+ NotificationChannel ch = new NotificationChannel(CHANNEL_ID, channelName.isEmpty() ? "Gym reminder" : channelName, NotificationManager.IMPORTANCE_DEFAULT);+ nm.createNotificationChannel(ch);+ }+ Intent open = new Intent(ctx, MainActivity.class).setAction(actionOpen(ctx));+ open.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);+ PendingIntent tap = PendingIntent.getActivity(ctx, NOTIFICATION_ID, open, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);+ 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(title)+ .setContentText(body)+ .setStyle(new Notification.BigTextStyle().bigText(body))+ .setAutoCancel(true)+ .setShowWhen(true)+ .setWhen(System.currentTimeMillis())+ .setCategory(Notification.CATEGORY_REMINDER)+ .setContentIntent(tap);+ try {+ nm.notify(NOTIFICATION_ID, b.build());+ return true;+ } catch (Exception e) {+ return false;+ }+ }+}diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderBootReceiver.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderBootReceiver.javanew file mode 100644index 000000000..57d19b973--- /dev/null+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderBootReceiver.java@@ -0,0 +1,19 @@+package ch.duartesantos.opengym;++import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;++/**+ * Proximity alerts are gone after a restart or an app update; this registers the saved gyms again+ * (GymReminder.register does nothing with the reminder off). Listens for system broadcasts only.+ */+public class GymReminderBootReceiver extends BroadcastReceiver {+ @Override+ public void onReceive(Context context, Intent intent) {+ if (intent == null) return;+ String a = intent.getAction();+ if (!Intent.ACTION_BOOT_COMPLETED.equals(a) && !Intent.ACTION_MY_PACKAGE_REPLACED.equals(a)) return;+ GymReminder.register(context.getApplicationContext());+ }+}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.javanew file mode 100644index 000000000..f95f92c85--- /dev/null+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderPlugin.java@@ -0,0 +1,274 @@+package ch.duartesantos.opengym;++import android.Manifest;+import android.content.Context;+import android.content.Intent;+import android.location.Location;+import android.location.LocationManager;+import android.net.Uri;+import android.os.Build;+import android.os.CancellationSignal;+import android.os.Handler;+import android.os.Looper;+import android.provider.Settings;+import com.getcapacitor.JSObject;+import com.getcapacitor.PermissionState;+import com.getcapacitor.Plugin;+import com.getcapacitor.PluginCall;+import com.getcapacitor.PluginMethod;+import com.getcapacitor.annotation.CapacitorPlugin;+import com.getcapacitor.annotation.Permission;+import com.getcapacitor.annotation.PermissionCallback;+import java.util.concurrent.atomic.AtomicBoolean;+import org.json.JSONObject;++/**+ * The page's side of the gym reminder (#614, frontend lib/gym-reminder.js); GymReminder does the+ * watching and the posting.+ *+ * Usage from JS:+ * const GR = registerPlugin('GymReminder');+ * await GR.configure({ config }); // { watching, permission }+ * await GR.status({ trainedOn, quietOn, activeSince, title, body });+ * await GR.get(); // { config, permission, watching }+ * await GR.permission(); // { location, background, notifications }+ * await GR.requestForeground(); // while-in-use location+ * await GR.requestBackground(); // "Allow all the time" (Android 10+), after the in-app explainer+ * await GR.currentPosition(); // { lat, lng, accuracy }+ * await GR.openSettings();+ * GR.addListener('open', fn); // the notification was tapped+ */+@CapacitorPlugin(+ name = "GymReminder",+ permissions = {+ @Permission(alias = "location", strings = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }),+ @Permission(alias = "background", strings = { Manifest.permission.ACCESS_BACKGROUND_LOCATION }),+ }+)+public class GymReminderPlugin extends Plugin {++ @Override+ public void load() {+ // Launched by a tap on the notification: told to the page once it listens.+ Intent i = getActivity() == null ? null : getActivity().getIntent();+ if (i != null && GymReminder.actionOpen(getContext()).equals(i.getAction())) {+ i.setAction(Intent.ACTION_MAIN);+ notifyListeners("open", new JSObject(), true);+ }+ }++ @Override+ protected void handleOnNewIntent(Intent intent) {+ super.handleOnNewIntent(intent);+ if (intent != null && GymReminder.actionOpen(getContext()).equals(intent.getAction())) {+ notifyListeners("open", new JSObject(), true);+ }+ }++ private JSObject permissions() {+ Context ctx = getContext();+ JSObject r = new JSObject();+ boolean fine = GymReminder.hasFine(ctx);+ PermissionState loc = getPermissionState("location");+ r.put("location", fine ? "granted" : loc == PermissionState.DENIED ? "denied" : "prompt");+ if (GymReminder.hasBackground(ctx)) r.put("background", "granted");+ else if (Build.VERSION.SDK_INT >= 29 && getPermissionState("background") == PermissionState.DENIED && fine) r.put("background", "denied");+ 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");+ return r;+ }++ @PluginMethod+ public void configure(PluginCall call) {+ JSObject config = call.getObject("config");+ if (config == null) {+ call.reject("config is required");+ return;+ }+ GymReminder.saveConfig(getContext(), config);+ int n = GymReminder.register(getContext());+ JSObject r = new JSObject();+ r.put("watching", n);+ r.put("permission", permissions());+ call.resolve(r);+ }++ @PluginMethod+ public void status(PluginCall call) {+ JSObject s = new JSObject();+ s.put("trainedOn", call.getString("trainedOn", ""));+ s.put("quietOn", call.getString("quietOn", ""));+ Double since = call.getDouble("activeSince");+ s.put("activeSince", since == null ? 0L : since.longValue());+ s.put("title", call.getString("title", ""));+ s.put("body", call.getString("body", ""));+ s.put("channel", call.getString("channel", ""));+ GymReminder.saveStatus(getContext(), s);+ call.resolve();+ }++ @PluginMethod+ public void get(PluginCall call) {+ Context ctx = getContext();+ JSONObject c = GymReminder.config(ctx);+ // Alerts lost while the app could not watch (permission taken back and given again):+ // the page opening the settings is a good moment to arm them again.+ if (c != null && c.optBoolean("on", false) && GymReminder.watching(ctx) == 0 && GymReminder.hasFine(ctx)) GymReminder.register(ctx);+ JSObject r = new JSObject();+ try {+ if (c != null) r.put("config", JSObject.fromJSONObject(c));+ } catch (Exception ignored) {+ // an unreadable copy: the page falls back to its own+ }+ r.put("permission", permissions());+ r.put("watching", GymReminder.watching(ctx));+ call.resolve(r);+ }++ @PluginMethod+ public void permission(PluginCall call) {+ call.resolve(permissions());+ }++ @PluginMethod+ public void requestForeground(PluginCall call) {+ if (GymReminder.hasFine(getContext())) {+ call.resolve(permissions());+ return;+ }+ requestPermissionForAlias("location", call, "afterPermission");+ }++ @PluginMethod+ public void requestBackground(PluginCall call) {+ Context ctx = getContext();+ if (GymReminder.hasBackground(ctx) || Build.VERSION.SDK_INT < 29) {+ call.resolve(permissions());+ return;+ }+ if (!GymReminder.hasFine(ctx)) {+ // Android grants "all the time" only on top of while-in-use location.+ requestPermissionForAlias("location", call, "afterForegroundForBackground");+ return;+ }+ requestPermissionForAlias("background", call, "afterPermission");+ }++ @PermissionCallback+ private void afterForegroundForBackground(PluginCall call) {+ if (!GymReminder.hasFine(getContext())) {+ call.resolve(permissions());+ return;+ }+ requestPermissionForAlias("background", call, "afterPermission");+ }++ @PermissionCallback+ private void afterPermission(PluginCall call) {+ // Allowed now: whatever the page saved earlier is watched from here on.+ GymReminder.register(getContext());+ call.resolve(permissions());+ }++ @PluginMethod+ public void openSettings(PluginCall call) {+ Intent i = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", getContext().getPackageName(), null));+ i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);+ getContext().startActivity(i);+ call.resolve();+ }++ /** One fix, from whichever provider is on; a recent last known one if none answers in time. */+ @PluginMethod+ public void currentPosition(PluginCall call) {+ Context ctx = getContext();+ if (!GymReminder.hasFine(ctx)) {+ call.reject("location not allowed");+ return;+ }+ LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);+ if (lm == null) {+ call.reject("no location service");+ return;+ }+ String provider = null;+ for (String p : new String[] { Build.VERSION.SDK_INT >= 31 ? LocationManager.FUSED_PROVIDER : null, LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER }) {+ if (p != null && lm.getAllProviders().contains(p) && lm.isProviderEnabled(p)) {+ provider = p;+ break;+ }+ }+ if (provider == null) {+ call.reject("location is switched off");+ return;+ }+ AtomicBoolean done = new AtomicBoolean(false);+ Handler main = new Handler(Looper.getMainLooper());+ final String used = provider;+ Runnable fallback = () -> {+ if (done.getAndSet(true)) return;+ Location last = lastKnown(lm);+ if (last != null && System.currentTimeMillis() - last.getTime() < 10 * 60_000L) answer(call, last);+ else call.reject("no fix");+ };+ try {+ if (Build.VERSION.SDK_INT >= 30) {+ CancellationSignal cancel = new CancellationSignal();+ lm.getCurrentLocation(used, cancel, ctx.getMainExecutor(), loc -> {+ if (loc == null) {+ fallback.run();+ return;+ }+ if (done.getAndSet(true)) return;+ answer(call, loc);+ });+ main.postDelayed(() -> {+ cancel.cancel();+ fallback.run();+ }, 25_000);+ } else {+ lm.requestSingleUpdate(used, new android.location.LocationListener() {+ @Override+ public void onLocationChanged(Location loc) {+ if (done.getAndSet(true)) return;+ answer(call, loc);+ }++ @Override+ public void onStatusChanged(String p, int s, android.os.Bundle b) {}++ @Override+ public void onProviderEnabled(String p) {}++ @Override+ public void onProviderDisabled(String p) {}+ }, Looper.getMainLooper());+ main.postDelayed(fallback, 25_000);+ }+ } catch (SecurityException e) {+ call.reject("location not allowed");+ }+ }++ private static Location lastKnown(LocationManager lm) {+ Location best = null;+ try {+ for (String p : lm.getProviders(true)) {+ Location l = lm.getLastKnownLocation(p);+ if (l != null && (best == null || l.getTime() > best.getTime())) best = l;+ }+ } catch (SecurityException ignored) {+ // asked without permission: nothing known+ }+ return best;+ }++ private static void answer(PluginCall call, Location loc) {+ JSObject r = new JSObject();+ r.put("lat", loc.getLatitude());+ r.put("lng", loc.getLongitude());+ r.put("accuracy", loc.hasAccuracy() ? loc.getAccuracy() : null);+ call.resolve(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.javanew file mode 100644index 000000000..40d4a3b1d--- /dev/null+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderReceiver.java@@ -0,0 +1,22 @@+package ch.duartesantos.opengym;++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. */+public class GymReminderReceiver extends BroadcastReceiver {+ @Override+ public void onReceive(Context context, Intent intent) {+ if (intent == null || !GymReminder.actionEnter(context).equals(intent.getAction())) return;+ final PendingResult pending = goAsync();+ final Context app = context.getApplicationContext();+ new Thread(() -> {+ try {+ GymReminder.onAlert(app, intent);+ } finally {+ pending.finish();+ }+ }, "opengym-gym").start();+ }+}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.javanew file mode 100644index 000000000..b10096b8a--- /dev/null+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/GymReminderRules.java@@ -0,0 +1,57 @@+package ch.duartesantos.opengym;++import java.util.Calendar;+import java.util.Locale;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++/**+ * The gym reminder's no-nag rule (#614), decided on the phone when a gym is entered, since the+ * page is not running then. The same rule as frontend lib/gym-reminder.js skipReason and+ * ios/App/GymReminderCore GymReminderRules.swift, in the same order; plain Java so the JVM unit+ * test can run it without Android.+ */+final class GymReminderRules {+ /** A running session older than this was never finished; it does not keep the reminder quiet. */+ static final long ACTIVE_FRESH_MS = 12L * 3600 * 1000;+ private static final Pattern TIME = Pattern.compile("^([01]\\d|2[0-3]):([0-5]\\d)$");++ private GymReminderRules() {}++ /** "HH:MM" as minutes after midnight, or -1. */+ static int minuteOf(String hhmm) {+ if (hhmm == null) return -1;+ Matcher m = TIME.matcher(hhmm);+ if (!m.matches()) return -1;+ return Integer.parseInt(m.group(1)) * 60 + Integer.parseInt(m.group(2));+ }++ /** No window (either end missing or invalid, or both the same) means any time; overnight wraps. */+ static boolean inWindow(String from, String to, int minuteOfDay) {+ int f = minuteOf(from), t = minuteOf(to);+ if (f < 0 || t < 0 || f == t) return true;+ return f < t ? minuteOfDay >= f && minuteOfDay < t : minuteOfDay >= f || minuteOfDay < t;+ }++ static String isoOf(Calendar c) {+ return String.format(Locale.ROOT, "%04d-%02d-%02d", c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));+ }++ /**+ * Why entering a gym now would not notify, or null when it should: off, fired (already today),+ * trained (a workout logged today), quiet (a day note excuses today), active (a session started+ * less than 12 hours ago), window (outside the time window).+ */+ static String skipReason(boolean on, int gyms, String windowFrom, String windowTo,+ String trainedOn, String quietOn, long activeSince, String lastFired, Calendar now) {+ if (!on || gyms <= 0) return "off";+ String today = isoOf(now);+ if (today.equals(lastFired)) return "fired";+ if (today.equals(trainedOn)) return "trained";+ if (today.equals(quietOn)) return "quiet";+ if (activeSince > 0 && now.getTimeInMillis() - activeSince < ACTIVE_FRESH_MS) return "active";+ int minute = now.get(Calendar.HOUR_OF_DAY) * 60 + now.get(Calendar.MINUTE);+ if (!inWindow(windowFrom, windowTo, minute)) return "window";+ return null;+ }+}diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.javaindex c15a57d9c..311286481 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java@@ -33,6 +33,7 @@ public class MainActivity extends BridgeActivity {registerPlugin(DeviceAuthPlugin.class);registerPlugin(AnimationPacksPlugin.class);registerPlugin(NudgeCheckPlugin.class);+ registerPlugin(GymReminderPlugin.class);super.onCreate(savedInstanceState);passSystemBarsToPage();}diff --git a/frontend/android/app/src/main/res/xml/backup_rules.xml b/frontend/android/app/src/main/res/xml/backup_rules.xmlindex 14ae9c098..83162ac2d 100644--- a/frontend/android/app/src/main/res/xml/backup_rules.xml+++ b/frontend/android/app/src/main/res/xml/backup_rules.xml@@ -6,8 +6,10 @@mirror (opengym-state.json) down with them. A paired phone gets the files back from itsserver; a phone in local mode keeps them in the zip export.The pairing (opengym-remote.json) stays out as well: it holds the session token for the- server, and a backup is no place for a credential. A restored phone pairs again. -->+ server, and a backup is no place for a credential. A restored phone pairs again.+ The gym reminder's places (opengym_gym_reminder.xml, #614) never leave the phone. --><full-backup-content><exclude domain="file" path="opengym-media/" /><exclude domain="file" path="opengym-remote.json" />+ <exclude domain="sharedpref" path="opengym_gym_reminder.xml" /></full-backup-content>diff --git a/frontend/android/app/src/main/res/xml/data_extraction_rules.xml b/frontend/android/app/src/main/res/xml/data_extraction_rules.xmlindex a6cd542c2..f7f21363c 100644--- a/frontend/android/app/src/main/res/xml/data_extraction_rules.xml+++ b/frontend/android/app/src/main/res/xml/data_extraction_rules.xml@@ -3,13 +3,16 @@the 25 MB cap applies. A device-to-device transfer has no such cap, and a phone moved to anew one should arrive with its photos and videos, so that section is left out: without one,a transfer takes everything, as before, except the pairing (opengym-remote.json), which holds- the session token for the server and stays out of both. A new phone pairs again. -->+ the session token for the server and stays out of both. A new phone pairs again. The gym+ reminder's places (opengym_gym_reminder.xml, #614) stay out of both too: they never leave the phone. --><data-extraction-rules><cloud-backup><exclude domain="file" path="opengym-media/" /><exclude domain="file" path="opengym-remote.json" />+ <exclude domain="sharedpref" path="opengym_gym_reminder.xml" /></cloud-backup><device-transfer><exclude domain="file" path="opengym-remote.json" />+ <exclude domain="sharedpref" path="opengym_gym_reminder.xml" /></device-transfer></data-extraction-rules>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.javanew file mode 100644index 000000000..f26182b72--- /dev/null+++ b/frontend/android/app/src/test/java/ch/duartesantos/opengym/GymReminderRulesTest.java@@ -0,0 +1,72 @@+package ch.duartesantos.opengym;++import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertFalse;+import static org.junit.Assert.assertNull;+import static org.junit.Assert.assertTrue;++import java.util.Calendar;+import org.junit.Test;++/** The no-nag rule, case for case the same as frontend src/lib/gym-reminder.test.js. */+public class GymReminderRulesTest {+ private static Calendar at(int h, int m) {+ Calendar c = Calendar.getInstance();+ c.clear();+ c.set(2026, Calendar.OCTOBER, 15, h, m, 0);+ return c;+ }++ private static String reason(boolean on, int gyms, String from, String to, String trained, String quiet, long active, String fired, Calendar now) {+ return GymReminderRules.skipReason(on, gyms, from, to, trained, quiet, active, fired, now);+ }++ @Test+ public void goesOffOnANormalDay() {+ assertNull(reason(true, 1, null, null, "2026-10-14", "", 0, "", at(18, 0)));+ }++ @Test+ public void offOrNoGym() {+ assertEquals("off", reason(false, 1, null, null, "", "", 0, "", at(18, 0)));+ assertEquals("off", reason(true, 0, null, null, "", "", 0, "", at(18, 0)));+ }++ @Test+ public void onceADay() {+ assertEquals("fired", reason(true, 1, null, null, "", "", 0, "2026-10-15", at(18, 0)));+ assertNull(reason(true, 1, null, null, "", "", 0, "2026-10-14", at(18, 0)));+ }++ @Test+ public void notAfterTrainingNorOnAnExcusedDay() {+ assertEquals("trained", reason(true, 1, null, null, "2026-10-15", "", 0, "", at(18, 0)));+ assertEquals("quiet", reason(true, 1, null, null, "", "2026-10-15", 0, "", at(18, 0)));+ }++ @Test+ public void notWhileAWorkoutRuns() {+ Calendar now = at(18, 0);+ assertEquals("active", reason(true, 1, null, null, "", "", now.getTimeInMillis() - 3_600_000L, "", now));+ assertNull(reason(true, 1, null, null, "", "", now.getTimeInMillis() - 13 * 3_600_000L, "", now));+ }++ @Test+ public void timeWindowAlsoOvernight() {+ assertEquals("window", reason(true, 1, "06:00", "12:00", "", "", 0, "", at(18, 0)));+ assertNull(reason(true, 1, "06:00", "12:00", "", "", 0, "", at(7, 0)));+ assertTrue(GymReminderRules.inWindow("22:00", "02:00", 23 * 60 + 30));+ assertTrue(GymReminderRules.inWindow("22:00", "02:00", 90));+ assertFalse(GymReminderRules.inWindow("22:00", "02:00", 12 * 60));+ assertTrue(GymReminderRules.inWindow("06:00", "06:00", 3 * 60));+ assertTrue(GymReminderRules.inWindow("6:00", "22:00", 3 * 60));+ assertFalse(GymReminderRules.inWindow("06:00", "22:00", 22 * 60));+ }++ @Test+ public void isoDate() {+ assertEquals("2026-10-15", GymReminderRules.isoOf(at(0, 0)));+ assertEquals(-1, GymReminderRules.minuteOf("24:00"));+ assertEquals(6 * 60 + 5, GymReminderRules.minuteOf("06:05"));+ }+}diff --git a/frontend/ios/App/App.xcodeproj/project.pbxproj b/frontend/ios/App/App.xcodeproj/project.pbxprojindex d8a0e1469..0abe52598 100644--- a/frontend/ios/App/App.xcodeproj/project.pbxproj+++ b/frontend/ios/App/App.xcodeproj/project.pbxproj@@ -32,6 +32,8 @@AA0500000000000000000012 /* WidgetPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000011 /* WidgetPreview.swift */; };AA0700000000000000000002 /* WatchBridgePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0700000000000000000001 /* WatchBridgePlugin.swift */; };AA0600000000000000000002 /* ClipCodec.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0600000000000000000001 /* ClipCodec.swift */; };+ AA0800000000000000000002 /* GymReminderPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0800000000000000000001 /* GymReminderPlugin.swift */; };+ AA0800000000000000000004 /* GymReminderRules.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0800000000000000000003 /* GymReminderRules.swift */; };/* End PBXBuildFile section *//* Begin PBXFileReference section */@@ -65,6 +67,8 @@AA0500000000000000000011 /* WidgetPreview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetPreview.swift; sourceTree = "<group>"; };AA0700000000000000000001 /* WatchBridgePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchBridgePlugin.swift; sourceTree = "<group>"; };AA0600000000000000000001 /* ClipCodec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ClipCodec.swift; path = ../WatchCore/Sources/WatchCore/ClipCodec.swift; sourceTree = "<group>"; };+ AA0800000000000000000001 /* GymReminderPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GymReminderPlugin.swift; sourceTree = "<group>"; };+ AA0800000000000000000003 /* GymReminderRules.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = GymReminderRules.swift; path = ../GymReminderCore/Sources/GymReminderCore/GymReminderRules.swift; sourceTree = "<group>"; };/* End PBXFileReference section *//* Begin PBXFrameworksBuildPhase section */@@ -127,6 +131,8 @@AA0500000000000000000011 /* WidgetPreview.swift */,AA0700000000000000000001 /* WatchBridgePlugin.swift */,AA0600000000000000000001 /* ClipCodec.swift */,+ AA0800000000000000000001 /* GymReminderPlugin.swift */,+ AA0800000000000000000003 /* GymReminderRules.swift */,AA0200000000000000000007 /* PrivacyInfo.xcprivacy */,504EC30B1FED79650016851F /* Main.storyboard */,504EC30E1FED79650016851F /* Assets.xcassets */,@@ -280,6 +286,8 @@AA0500000000000000000012 /* WidgetPreview.swift in Sources */,AA0700000000000000000002 /* WatchBridgePlugin.swift in Sources */,AA0600000000000000000002 /* ClipCodec.swift in Sources */,+ AA0800000000000000000002 /* GymReminderPlugin.swift in Sources */,+ AA0800000000000000000004 /* GymReminderRules.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;};diff --git a/frontend/ios/App/App/AppDelegate.swift b/frontend/ios/App/App/AppDelegate.swiftindex 316032174..069d9ae85 100644--- a/frontend/ios/App/App/AppDelegate.swift+++ b/frontend/ios/App/App/AppDelegate.swift@@ -8,6 +8,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate {// The background check before a nudge (NudgeCheckPlugin): iOS hands the task only to a// handler registered before launching ends.NudgeCheckPlugin.registerTask()+ // The gym reminder (GymReminderPlugin): iOS relaunches the app in the background for a+ // region it watches and delivers the event to the location delegate that exists then.+ GymReminderCenter.shared.start()return true}diff --git a/frontend/ios/App/App/GymReminderPlugin.swift b/frontend/ios/App/App/GymReminderPlugin.swiftnew file mode 100644index 000000000..48f51c49a--- /dev/null+++ b/frontend/ios/App/App/GymReminderPlugin.swift@@ -0,0 +1,375 @@+import Foundation+import Capacitor+import CoreLocation+import UIKit+import UserNotifications++/**+ * The gym reminder (#614): a notification when the iPhone arrives at one of the user's gyms+ * (frontend lib/gym-reminder.js has the page's side and the rules in words).+ *+ * iOS watches the gyms itself with region monitoring (at most 20 regions per app), with openGym+ * closed and at hardly any battery cost: on arriving it launches the app in the background and+ * hands GymReminderCenter the region, which decides with GymReminderRules whether to post and+ * posts a local notification. That needs "Always" location; no background location mode+ * (UIBackgroundModes location) is needed or declared, region monitoring works without it.+ *+ * The page's status (last day trained, a running session, the words in the app's language) is+ * kept beside the gyms, so the decision needs no JavaScript. All of it lives in one file in+ * Application Support that is excluded from iCloud/iTunes backups: the places never leave the+ * phone, and never go to the user's server either.+ *+ * Usage from JS:+ * const GR = registerPlugin('GymReminder');+ * await GR.configure({ config }); // { watching, permission }+ * await GR.status({ trainedOn, quietOn, activeSince, title, body });+ * 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();+ * A tap on the notification goes through Capacitor's local-notifications handler (the page+ * listens there for id 3000).+ */+@objc(GymReminderPlugin)+public class GymReminderPlugin: CAPPlugin, CAPBridgedPlugin {+ public let identifier = "GymReminderPlugin"+ public let jsName = "GymReminder"+ public let pluginMethods: [CAPPluginMethod] = [+ CAPPluginMethod(name: "configure", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "status", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "get", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "permission", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "requestForeground", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "requestBackground", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "currentPosition", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "openSettings", returnType: CAPPluginReturnPromise),+ ]++ private var center: GymReminderCenter { GymReminderCenter.shared }++ @objc func configure(_ call: CAPPluginCall) {+ guard let config = call.getObject("config") else { call.reject("config is required"); return }+ DispatchQueue.main.async {+ self.center.saveConfig(config as [String: Any])+ let n = self.center.register(force: true)+ self.center.permissions { p in call.resolve(["watching": n, "permission": p]) }+ }+ }++ @objc func status(_ call: CAPPluginCall) {+ let status: [String: Any] = [+ "trainedOn": call.getString("trainedOn") ?? "",+ "quietOn": call.getString("quietOn") ?? "",+ "activeSince": call.getDouble("activeSince") ?? 0,+ "title": call.getString("title") ?? "",+ "body": call.getString("body") ?? "",+ ]+ DispatchQueue.main.async {+ self.center.saveStatus(status)+ call.resolve()+ }+ }++ @objc func get(_ call: CAPPluginCall) {+ DispatchQueue.main.async {+ // Regions lost while the app could not watch (Always taken back and given again):+ // the page opening the settings is a good moment to arm them again.+ self.center.register(force: false)+ let config = self.center.config+ let n = self.center.watching()+ self.center.permissions { p in+ var r: [String: Any] = ["permission": p, "watching": n]+ if let c = config { r["config"] = c }+ call.resolve(r)+ }+ }+ }++ @objc func permission(_ call: CAPPluginCall) {+ DispatchQueue.main.async { self.center.permissions { call.resolve($0) } }+ }++ @objc func requestForeground(_ call: CAPPluginCall) {+ DispatchQueue.main.async {+ self.center.askWhenInUse {+ self.center.permissions { call.resolve($0) }+ }+ }+ }++ @objc func requestBackground(_ call: CAPPluginCall) {+ DispatchQueue.main.async {+ self.center.askAlways {+ self.center.register(force: false)+ self.center.permissions { call.resolve($0) }+ }+ }+ }++ @objc func currentPosition(_ call: CAPPluginCall) {+ DispatchQueue.main.async {+ self.center.locate { loc in+ guard let loc = loc else { call.reject("no fix"); return }+ call.resolve(["lat": loc.coordinate.latitude, "lng": loc.coordinate.longitude, "accuracy": loc.horizontalAccuracy])+ }+ }+ }++ @objc func openSettings(_ call: CAPPluginCall) {+ DispatchQueue.main.async {+ if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }+ call.resolve()+ }+ }+}++/// The location side, alive from launch on (AppDelegate): iOS relaunches the app in the+/// background for a region event and hands it to whichever CLLocationManager delegate exists then.+final class GymReminderCenter: NSObject, CLLocationManagerDelegate {+ static let shared = GymReminderCenter()+ static let notificationId = "3000"+ static let regionPrefix = "gym:"+ static let maxGyms = 20++ private let manager = CLLocationManager()+ private var authWaiters: [() -> Void] = []+ private var fixWaiters: [(CLLocation?) -> Void] = []+ private var promptShown = false+ private var store: [String: Any] = [:]++ private override init() {+ super.init()+ store = GymReminderCenter.readStore()+ }++ /// From AppDelegate, before launching ends: becomes the delegate, so a region event that+ /// relaunched the app is delivered here.+ func start() {+ manager.delegate = self+ NotificationCenter.default.addObserver(self, selector: #selector(resignedActive), name: UIApplication.willResignActiveNotification, object: nil)+ NotificationCenter.default.addObserver(self, selector: #selector(becameActive), name: UIApplication.didBecomeActiveNotification, object: nil)+ }++ // MARK: what is kept++ private static var fileURL: URL? {+ guard let dir = try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else { return nil }+ return dir.appendingPathComponent("gym-reminder.json")+ }++ private static func readStore() -> [String: Any] {+ guard let url = fileURL, let data = try? Data(contentsOf: url),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [:] }+ return obj+ }++ private func writeStore() {+ guard var url = GymReminderCenter.fileURL,+ let data = try? JSONSerialization.data(withJSONObject: store) else { return }+ // Readable after the first unlock: a region event can wake the app while the phone is locked.+ try? data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])+ var values = URLResourceValues()+ values.isExcludedFromBackup = true+ try? url.setResourceValues(values)+ }++ var config: [String: Any]? { store["config"] as? [String: Any] }+ var isOn: Bool { (config?["on"] as? Bool) == true }+ private var status: [String: Any] { store["status"] as? [String: Any] ?? [:] }++ func saveConfig(_ c: [String: Any]) { store["config"] = c; writeStore() }+ func saveStatus(_ s: [String: Any]) { store["status"] = s; writeStore() }++ // MARK: permissions++ private var authorization: CLAuthorizationStatus { manager.authorizationStatus }++ func permissions(_ done: @escaping ([String: Any]) -> Void) {+ let a = authorization+ let precise = manager.accuracyAuthorization == .fullAccuracy+ let location: String = (a == .authorizedAlways || a == .authorizedWhenInUse) ? "granted" : (a == .denied || a == .restricted) ? "denied" : "prompt"+ let background: String = a == .authorizedAlways ? (precise ? "granted" : "denied")+ : (a == .denied || a == .restricted || (a == .authorizedWhenInUse && (store["askedAlways"] as? Bool) == true)) ? "denied" : "prompt"+ UNUserNotificationCenter.current().getNotificationSettings { s in+ let n: String = s.authorizationStatus == .authorized || s.authorizationStatus == .provisional ? "granted" : s.authorizationStatus == .denied ? "denied" : "prompt"+ DispatchQueue.main.async {+ done(["location": location, "background": background, "precise": precise, "notifications": n])+ }+ }+ }++ func askWhenInUse(_ done: @escaping () -> Void) {+ guard authorization == .notDetermined else { done(); return }+ waitForAnswer(done)+ manager.requestWhenInUseAuthorization()+ }++ func askAlways(_ done: @escaping () -> Void) {+ let a = authorization+ guard a == .notDetermined || a == .authorizedWhenInUse else { done(); return }+ store["askedAlways"] = true+ writeStore()+ waitForAnswer(done)+ manager.requestAlwaysAuthorization()+ }++ /// iOS answers a request it shows by changing the authorization; one it does not show (asked+ /// before, or "Allow Once") changes nothing and calls back never. So: done on a change, when+ /// the app comes back after a prompt, or shortly after asking when no prompt took the screen.+ private func waitForAnswer(_ done: @escaping () -> Void) {+ authWaiters.append(done)+ promptShown = false+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in+ guard let self = self, !self.promptShown else { return }+ self.flushAuth()+ }+ }++ private func flushAuth() {+ let w = authWaiters+ authWaiters.removeAll()+ w.forEach { $0() }+ }++ @objc private func resignedActive() { if !authWaiters.isEmpty { promptShown = true } }+ @objc private func becameActive() {+ if promptShown { promptShown = false; DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in self?.flushAuth() } }+ }++ func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {+ if authorization != .notDetermined { flushAuth() }+ // Always given (or taken back) in Settings: watch, or stop. Also runs once at launch,+ // where nothing changes when the right gyms are already watched.+ register(force: false)+ }++ // MARK: one fix++ func locate(_ done: @escaping (CLLocation?) -> Void) {+ let a = authorization+ guard a == .authorizedAlways || a == .authorizedWhenInUse else { done(nil); return }+ fixWaiters.append(done)+ manager.desiredAccuracy = kCLLocationAccuracyBest+ manager.requestLocation()+ DispatchQueue.main.asyncAfter(deadline: .now() + 25) { [weak self] in+ guard let self = self, !self.fixWaiters.isEmpty else { return }+ self.flushFix(self.manager.location)+ }+ }++ private func flushFix(_ loc: CLLocation?) {+ let w = fixWaiters+ fixWaiters.removeAll()+ w.forEach { $0(loc) }+ }++ func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {+ if let last = locations.last { flushFix(last) }+ }++ func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {+ if !fixWaiters.isEmpty { flushFix(manager.location) }+ }++ // MARK: watching++ func watching() -> Int {+ manager.monitoredRegions.filter { $0.identifier.hasPrefix(GymReminderCenter.regionPrefix) }.count+ }++ /// The regions the saved gyms ask for: none when off, without Always, or with approximate+ /// location (region monitoring needs precise location).+ private func wanted() -> [CLCircularRegion] {+ guard isOn, authorization == .authorizedAlways, manager.accuracyAuthorization == .fullAccuracy,+ CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) else { return [] }+ let gyms = (config?["gyms"] as? [[String: Any]]) ?? []+ var out: [CLCircularRegion] = []+ for g in gyms.prefix(GymReminderCenter.maxGyms) {+ guard let id = g["id"] as? String,+ let lat = (g["lat"] as? NSNumber)?.doubleValue, let lng = (g["lng"] as? NSNumber)?.doubleValue else { continue }+ let radius = min(max((g["radius"] as? NSNumber)?.doubleValue ?? 100, 50), min(500, manager.maximumRegionMonitoringDistance))+ let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: lat, longitude: lng), radius: radius, identifier: GymReminderCenter.regionPrefix + id)+ region.notifyOnEntry = true+ region.notifyOnExit = false+ out.append(region)+ }+ return out+ }++ /// Watches the saved gyms (or stops). `force` restarts every region (the page saved new gyms);+ /// otherwise nothing is touched when the right ones are already watched, so a launch or a+ /// permission check never re-arms a region the phone is standing in. Returns how many are watched.+ @discardableResult+ func register(force: Bool) -> Int {+ let want = wanted()+ let have = manager.monitoredRegions.filter { $0.identifier.hasPrefix(GymReminderCenter.regionPrefix) }+ let same = Set(have.compactMap { r -> String? in+ guard let c = r as? CLCircularRegion else { return nil }+ return "\(c.identifier)|\(c.center.latitude)|\(c.center.longitude)|\(c.radius)"+ }) == Set(want.map { "\($0.identifier)|\($0.center.latitude)|\($0.center.longitude)|\($0.radius)" })+ if same && !force { return have.count }+ for r in have { manager.stopMonitoring(for: r) }+ for r in want { manager.startMonitoring(for: r) }+ if !want.isEmpty { store["armedAt"] = Date().timeIntervalSince1970; writeStore() }+ return want.count+ }++ func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {+ guard region.identifier.hasPrefix(GymReminderCenter.regionPrefix) else { return }+ // A region added while the phone is already inside it may report an entry right away,+ // which would ping right after "I'm at the gym right now".+ let armedAt = (store["armedAt"] as? NSNumber)?.doubleValue ?? 0+ if Date().timeIntervalSince1970 - armedAt < 90 { return }+ let gymId = String(region.identifier.dropFirst(GymReminderCenter.regionPrefix.count))+ // A few seconds to write the notification, even when iOS woke the app just for this.+ var task: UIBackgroundTaskIdentifier = .invalid+ task = UIApplication.shared.beginBackgroundTask(withName: "gym-reminder") {+ UIApplication.shared.endBackgroundTask(task)+ task = .invalid+ }+ arrive(gymId: gymId, now: Date()) {+ if task != .invalid { UIApplication.shared.endBackgroundTask(task); task = .invalid }+ }+ }++ func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {+ // Nothing to do here but not crash: the settings page shows how many gyms are watched.+ }++ /// Applies the no-nag rule for arriving at `gymId` now, and posts if it says so.+ func arrive(gymId: String, now: Date, done: @escaping () -> Void) {+ let c = config ?? [:]+ let st = status+ let gyms = (c["gyms"] as? [[String: Any]]) ?? []+ let win = c["window"] as? [String: Any]+ let why = GymReminderRules.skipReason(+ on: (c["on"] as? Bool) == true, gyms: gyms.count,+ windowFrom: win?["from"] as? String, windowTo: win?["to"] as? String,+ trainedOn: st["trainedOn"] as? String ?? "", quietOn: st["quietOn"] as? String ?? "",+ activeSince: (st["activeSince"] as? NSNumber)?.doubleValue ?? 0,+ lastFired: store["lastFired"] as? String ?? "", now: now)+ guard why == nil else { done(); return }+ let gym = gyms.first { ($0["id"] as? String) == gymId }+ let own = ((gym?["text"] as? String) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)+ let content = UNMutableNotificationContent()+ let title = st["title"] as? String ?? ""+ let body = st["body"] as? String ?? ""+ content.title = title.isEmpty ? "Gym spotted" : title+ content.body = !own.isEmpty ? own : (body.isEmpty ? "Ready for your workout? 💪" : body)+ content.sound = .default+ // How Capacitor's local-notifications handler hands `extra` to the page on a tap.+ content.userInfo = ["cap_extra": ["gymReminder": true]]+ let request = UNNotificationRequest(identifier: GymReminderCenter.notificationId, content: content, trigger: nil)+ UNUserNotificationCenter.current().add(request) { [weak self] error in+ DispatchQueue.main.async {+ if error == nil, let self = self {+ self.store["lastFired"] = GymReminderRules.isoOf(now)+ self.writeStore()+ }+ done()+ }+ }+ }+}diff --git a/frontend/ios/App/App/Info.plist b/frontend/ios/App/App/Info.plistindex 31b868638..d6fa3d0b4 100644--- a/frontend/ios/App/App/Info.plist+++ b/frontend/ios/App/App/Info.plist@@ -98,6 +98,12 @@<string>Used to show your heart rate on your Apple Watch while you train, next to each set.</string><key>NSHealthUpdateUsageDescription</key><string>Used to save your finished workouts and weigh-ins to Apple Health, when you switch it on.</string>+ <!-- Gym reminder (#614): off until switched on in Settings. Region monitoring needs Always,+ but no background location mode (UIBackgroundModes stays without "location"). -->+ <key>NSLocationWhenInUseUsageDescription</key>+ <string>Used to put a gym on the map where you are standing, for the gym reminder. Your location stays on this iPhone.</string>+ <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>+ <string>Lets the gym reminder notice when you arrive at a gym you added, even with openGym closed. iOS only watches those places, and your location never leaves this iPhone.</string><key>NSFaceIDUsageDescription</key><string>Used to make sure it’s really you before your account is deleted.</string></dict>diff --git a/frontend/ios/App/App/MainViewController.swift b/frontend/ios/App/App/MainViewController.swiftindex e07403103..c37a3b27b 100644--- a/frontend/ios/App/App/MainViewController.swift+++ b/frontend/ios/App/App/MainViewController.swift@@ -24,6 +24,7 @@ class MainViewController: CAPBridgeViewController {bridge?.registerPluginInstance(DeviceAuthPlugin())bridge?.registerPluginInstance(AnimationPacksPlugin())bridge?.registerPluginInstance(NudgeCheckPlugin())+ bridge?.registerPluginInstance(GymReminderPlugin())bridge?.registerPluginInstance(WatchBridgePlugin())bridge?.registerPluginInstance(AppleHealthPlugin())bridge?.registerPluginInstance(WidgetBridgePlugin())diff --git a/frontend/ios/App/GymReminderCore/Package.swift b/frontend/ios/App/GymReminderCore/Package.swiftnew file mode 100644index 000000000..7e9978175--- /dev/null+++ b/frontend/ios/App/GymReminderCore/Package.swift@@ -0,0 +1,15 @@+// swift-tools-version:5.9+// The gym reminder's no-nag rule (#614): plain Foundation, compiled straight into the iPhone app+// (App.xcodeproj references Sources/GymReminderCore/GymReminderRules.swift); this package exists+// so CI can test it with `swift test` on the Mac, no simulator needed.+import PackageDescription++let package = Package(+ name: "GymReminderCore",+ platforms: [.macOS(.v13), .iOS(.v15)],+ products: [.library(name: "GymReminderCore", targets: ["GymReminderCore"])],+ targets: [+ .target(name: "GymReminderCore"),+ .testTarget(name: "GymReminderCoreTests", dependencies: ["GymReminderCore"]),+ ]+)diff --git a/frontend/ios/App/GymReminderCore/Sources/GymReminderCore/GymReminderRules.swift b/frontend/ios/App/GymReminderCore/Sources/GymReminderCore/GymReminderRules.swiftnew file mode 100644index 000000000..201f407f6--- /dev/null+++ b/frontend/ios/App/GymReminderCore/Sources/GymReminderCore/GymReminderRules.swift@@ -0,0 +1,51 @@+import Foundation++/**+ * The gym reminder's no-nag rule (#614), decided on the phone when a gym is entered, since the+ * page is not running then. The same rule as frontend lib/gym-reminder.js skipReason and+ * android/.../GymReminderRules.java, in the same order.+ */+public enum GymReminderRules {+ /// A running session older than this was never finished; it does not keep the reminder quiet.+ public static let activeFreshMs: Double = 12 * 3600 * 1000++ /// "HH:MM" as minutes after midnight, or nil.+ public static func minuteOf(_ hhmm: String?) -> Int? {+ guard let s = hhmm, s.count == 5, s[s.index(s.startIndex, offsetBy: 2)] == ":" else { return nil }+ let parts = s.split(separator: ":")+ guard parts.count == 2, parts[0].count == 2, parts[1].count == 2,+ parts[0].allSatisfy({ $0.isASCII && $0.isNumber }), parts[1].allSatisfy({ $0.isASCII && $0.isNumber }),+ let h = Int(parts[0]), let m = Int(parts[1]), h < 24, m < 60 else { return nil }+ return h * 60 + m+ }++ /// No window (either end missing or invalid, or both the same) means any time; overnight wraps.+ public static func inWindow(from: String?, to: String?, minute: Int) -> Bool {+ guard let f = minuteOf(from), let t = minuteOf(to), f != t else { return true }+ return f < t ? (minute >= f && minute < t) : (minute >= f || minute < t)+ }++ public static func isoOf(_ date: Date, calendar: Calendar = .current) -> String {+ let c = calendar.dateComponents([.year, .month, .day], from: date)+ return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)+ }++ /**+ * Why entering a gym now would not notify, or nil when it should: off, fired (already today),+ * trained (a workout logged today), quiet (a day note excuses today), active (a session+ * started less than 12 hours ago), window (outside the time window).+ */+ public static func skipReason(on: Bool, gyms: Int, windowFrom: String?, windowTo: String?,+ trainedOn: String, quietOn: String, activeSince: Double, lastFired: String,+ now: Date, calendar: Calendar = .current) -> String? {+ if !on || gyms <= 0 { return "off" }+ let today = isoOf(now, calendar: calendar)+ if lastFired == today { return "fired" }+ if trainedOn == today { return "trained" }+ if quietOn == today { return "quiet" }+ if activeSince > 0 && now.timeIntervalSince1970 * 1000 - activeSince < activeFreshMs { return "active" }+ let c = calendar.dateComponents([.hour, .minute], from: now)+ if !inWindow(from: windowFrom, to: windowTo, minute: (c.hour ?? 0) * 60 + (c.minute ?? 0)) { return "window" }+ return nil+ }+}diff --git a/frontend/ios/App/GymReminderCore/Tests/GymReminderCoreTests/GymReminderRulesTests.swift b/frontend/ios/App/GymReminderCore/Tests/GymReminderCoreTests/GymReminderRulesTests.swiftnew file mode 100644index 000000000..5c2b36fc7--- /dev/null+++ b/frontend/ios/App/GymReminderCore/Tests/GymReminderCoreTests/GymReminderRulesTests.swift@@ -0,0 +1,65 @@+import XCTest+@testable import GymReminderCore++/// The no-nag rule, case for case the same as frontend src/lib/gym-reminder.test.js.+final class GymReminderRulesTests: XCTestCase {+ private var cal: Calendar = {+ var c = Calendar(identifier: .gregorian)+ c.timeZone = TimeZone(identifier: "Europe/Zurich")!+ return c+ }()++ private func at(_ h: Int, _ m: Int) -> Date {+ cal.date(from: DateComponents(year: 2026, month: 10, day: 15, hour: h, minute: m))!+ }++ private func reason(on: Bool = true, gyms: Int = 1, from: String? = nil, to: String? = nil, trained: String = "2026-10-14",+ quiet: String = "", active: Double = 0, fired: String = "", now: Date) -> String? {+ GymReminderRules.skipReason(on: on, gyms: gyms, windowFrom: from, windowTo: to, trainedOn: trained, quietOn: quiet,+ activeSince: active, lastFired: fired, now: now, calendar: cal)+ }++ func testGoesOffOnANormalDay() {+ XCTAssertNil(reason(now: at(18, 0)))+ }++ func testOffOrNoGym() {+ XCTAssertEqual(reason(on: false, now: at(18, 0)), "off")+ XCTAssertEqual(reason(gyms: 0, now: at(18, 0)), "off")+ }++ func testOnceADay() {+ XCTAssertEqual(reason(fired: "2026-10-15", now: at(18, 0)), "fired")+ XCTAssertNil(reason(fired: "2026-10-14", now: at(18, 0)))+ }++ func testNotAfterTrainingNorOnAnExcusedDay() {+ XCTAssertEqual(reason(trained: "2026-10-15", now: at(18, 0)), "trained")+ XCTAssertEqual(reason(quiet: "2026-10-15", now: at(18, 0)), "quiet")+ }++ func testNotWhileAWorkoutRuns() {+ let now = at(18, 0)+ let ms = now.timeIntervalSince1970 * 1000+ XCTAssertEqual(reason(active: ms - 3_600_000, now: now), "active")+ XCTAssertNil(reason(active: ms - 13 * 3_600_000, now: now))+ }++ func testTimeWindowAlsoOvernight() {+ XCTAssertEqual(reason(from: "06:00", to: "12:00", now: at(18, 0)), "window")+ XCTAssertNil(reason(from: "06:00", to: "12:00", now: at(7, 0)))+ XCTAssertTrue(GymReminderRules.inWindow(from: "22:00", to: "02:00", minute: 23 * 60 + 30))+ XCTAssertTrue(GymReminderRules.inWindow(from: "22:00", to: "02:00", minute: 90))+ XCTAssertFalse(GymReminderRules.inWindow(from: "22:00", to: "02:00", minute: 12 * 60))+ XCTAssertTrue(GymReminderRules.inWindow(from: "06:00", to: "06:00", minute: 180))+ XCTAssertTrue(GymReminderRules.inWindow(from: "6:00", to: "22:00", minute: 180))+ XCTAssertFalse(GymReminderRules.inWindow(from: "06:00", to: "22:00", minute: 22 * 60))+ }++ func testIsoAndMinutes() {+ XCTAssertEqual(GymReminderRules.isoOf(at(0, 0), calendar: cal), "2026-10-15")+ XCTAssertNil(GymReminderRules.minuteOf("24:00"))+ XCTAssertNil(GymReminderRules.minuteOf("6:00"))+ XCTAssertEqual(GymReminderRules.minuteOf("06:05"), 365)+ }+}diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 6d803ec53..d5b7fd1af 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -17,6 +17,7 @@"@capacitor/local-notifications": "^8.0.0","@capacitor/share": "^8.0.0","jsqr": "^1.4.0",+ "leaflet": "^1.9.4","lean-qr": "^2.7.3","react": "^19.2.7","react-dom": "^19.2.7",@@ -2638,6 +2639,12 @@"node": ">=6"}},+ "node_modules/leaflet": {+ "version": "1.9.4",+ "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",+ "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",+ "license": "BSD-2-Clause"+ },"node_modules/lean-qr": {"version": "2.7.3","resolved": "https://registry.npmjs.org/lean-qr/-/lean-qr-2.7.3.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex b9f80662f..0aa35b4bb 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -22,6 +22,7 @@"@capacitor/local-notifications": "^8.0.0","@capacitor/share": "^8.0.0","jsqr": "^1.4.0",+ "leaflet": "^1.9.4","lean-qr": "^2.7.3","react": "^19.2.7","react-dom": "^19.2.7",diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 998c45ce3..3ad471d7e 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -11,6 +11,7 @@ import { effectiveLang } from './lib/default-lang.js'import { setPlayOnSilent, setVibrate, setAlarmBuzzer, setNativeBuzzer } from './lib/sound.js'import { buzzAsAlarm } from './lib/rest-alert.js'import { setNav, notePath, keyBefore, navToWorkout } from './lib/nav.js'+import { onGymReminderOpen } from './lib/gym-reminder.js'import { workoutVolume } from './lib/history.js'import { setSystemBarsLight } from './lib/system-bars.js'import { initBackButton } from './lib/back.js'@@ -368,5 +369,11 @@ export default function App() {startLiveActivitySync({ useStore, useUI }).then(keep).catch(() => {})return () => { gone.v = true; stops.forEach(fn => fn()) }}, [])+ // Phone app: a tap on the gym reminder (lib/gym-reminder.js) opens the Start screen, or the+ // workout already running. Nothing on the web.+ useEffect(() => {+ if (!MOBILE) return+ return onGymReminderOpen(() => { if (!String(window.location.hash || '').startsWith('#/workout')) navToWorkout() })+ }, [])return <HashRouter><Shell /></HashRouter>}diff --git a/frontend/src/components/Icon.jsx b/frontend/src/components/Icon.jsxindex ebf1f858c..0dc49c99a 100644--- a/frontend/src/components/Icon.jsx+++ b/frontend/src/components/Icon.jsx@@ -176,6 +176,8 @@ const P = {steps: <path d="M3.6 19.8h4.6v-4.6h4.6v-4.6h4.6V6h3" />,// a note pinned to show next time (flag is Finish workout)pin: <path d="M9.2 3.8h5.6M10.2 3.8v5.4l-3.4 3.8h10.4l-3.4-3.8V3.8M12 13v7.2" />,+ // a place on a map (the gym reminder, #614)+ mapPin: <><path d="M12 20.6s-6.4-5.6-6.4-10.6a6.4 6.4 0 0 1 12.8 0c0 5-6.4 10.6-6.4 10.6Z" /><circle cx="12" cy="10" r="2.4" /></>,// copy to the clipboard: two overlapping sheetscopy: <><rect x="8.4" y="8.4" width="11.6" height="11.6" rx="2.4" /><path d="M15.6 8.4v-2A2.4 2.4 0 0 0 13.2 4H6.4A2.4 2.4 0 0 0 4 6.4v6.8a2.4 2.4 0 0 0 2.4 2.4h2" /></>,// a passkey (key is the password, lock is "stays on this device")diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 7810ea0ea..e17879c17 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -2169,3 +2169,18 @@ button.wl-summary{width:100%;padding:0 0 10px;text-align:start;border-radius:varleft:calc(-1 * var(--eb-l,0px));right:calc(-1 * var(--eb-r,0px));box-shadow:0 0 28px rgba(0,0,0,.28);}++/* Gym reminder (#614, views/GymReminder.jsx): the map with its pin and radius, and the editor rows */+.gym-map-wrap{margin:0 0 22px}+.gym-map{height:300px;border-radius:12px;overflow:hidden;background:var(--surface-2);z-index:0;isolation:isolate}+.gym-map .leaflet-control-attribution{font-size:10px}+.gym-pin span{display:block;width:30px;height:30px;border-radius:50% 50% 50% 0;background:var(--acc);transform:rotate(-45deg);box-shadow:0 2px 6px rgba(0,0,0,.35);border:2px solid #fff}+.gym-radius{stroke:var(--acc);fill:var(--acc);stroke-width:2}+.gym-search{display:flex;gap:8px;align-items:center;padding:8px 12px}+.gym-search>:first-child{flex:1;min-width:0}+.gym-field{padding:8px 12px}+.gym-field input{width:100%}+.gym-radius-row{display:flex;align-items:center;gap:12px;padding:12px 14px}+.gym-radius-row>:first-child{flex:1}+.gym-radius-val{min-width:64px;text-align:end;font-variant-numeric:tabular-nums;color:var(--label-2)}+.gym-actions{display:flex;flex-direction:column;gap:10px;margin:4px 0 30px}diff --git a/frontend/src/lib/android-backup.test.js b/frontend/src/lib/android-backup.test.jsindex 3681e068f..9256882eb 100644--- a/frontend/src/lib/android-backup.test.js+++ b/frontend/src/lib/android-backup.test.js@@ -29,10 +29,20 @@ describe('Android backup rules', () => {// An <include> would turn either list into an allowlist and drop everything else.expect(legacy).not.toMatch(/<include/)expect(modern).not.toMatch(/<include/)- // Device transfer takes everything but the pairing.+ // Device transfer takes everything but the pairing and the gym reminder's places.const transfer = modern.match(/<device-transfer>([\s\S]*?)<\/device-transfer>/)?.[1] || ''expect(transfer).not.toMatch(EXCLUDE)- expect(transfer.match(/<exclude/g)).toHaveLength(1)+ expect(transfer.match(/<exclude/g)).toHaveLength(2)+ })++ it('the gym reminder\'s places (#614) never leave the phone: out of every backup and transfer', () => {+ const GYMS = /<exclude\s+domain="sharedpref"\s+path="opengym_gym_reminder\.xml"\s*\/>/+ expect(legacy).toMatch(GYMS)+ expect(modern.match(/<cloud-backup>([\s\S]*?)<\/cloud-backup>/)?.[1]).toMatch(GYMS)+ expect(modern.match(/<device-transfer>([\s\S]*?)<\/device-transfer>/)?.[1]).toMatch(GYMS)+ // the file name the native side writes+ const java = readFileSync(new URL('../../android/app/src/main/java/ch/duartesantos/opengym/GymReminder.java', import.meta.url), 'utf8')+ expect(java).toMatch(/PREFS = "opengym_gym_reminder"/)})it('the pairing token is left out of every backup and transfer', () => {diff --git a/frontend/src/lib/gym-reminder.js b/frontend/src/lib/gym-reminder.jsnew file mode 100644index 000000000..f62d4aa24--- /dev/null+++ b/frontend/src/lib/gym-reminder.js@@ -0,0 +1,281 @@+// Gym reminder (#614): a nudge when you walk into your gym, so you never forget to hit Start.+//+// Phone app only. The gyms are places on a map with a radius; the phone itself watches them+// (iOS: CLLocationManager region monitoring, ios/App/App/GymReminderPlugin.swift; Android: the+// platform's proximity alerts, no Google Play Services, android/.../GymReminderPlugin.java) and+// posts the notification on its own, with the app closed. Nothing here ever reaches the server:+// the places live only in the native side's own storage (kept out of device backups too), never+// in the synced state `S`, never in a backup file; the page keeps just an on/off flag.+//+// The no-nag rules are decided by the native side when a gym is entered, since the page is not+// running then. The page hands it what it needs to know (skipReason below spells out the rule the+// native code follows): when you last trained, whether a session is running, a day note that+// excuses today, and the notification text in the app's language.+import { MOBILE } from './mobile.js'+import { t } from './i18n-core.js'+import { isoOf } from './format.js'+import { excusedOn } from './day-notes.js'++export const GYM_KEY = 'gym_reminder_v1'+export const RADIUS = Object.freeze({ min: 50, max: 500, def: 100, step: 10 })+// iOS watches at most 20 regions per app; Android has no such cap, but one rule for both.+export const MAX_GYMS = 20+export const DEFAULT_WINDOW = Object.freeze({ from: '06:00', to: '22:00' })+export const DEFAULTS = Object.freeze({ on: false, gyms: [], window: null })+// A running session older than this is one that was never finished, not one in progress: it does+// not keep the reminder quiet forever.+export const ACTIVE_FRESH_MS = 12 * 3600 * 1000+// The id the notification carries (iOS: its identifier, so a tap is told apart from the others).+export const NOTIFICATION_ID = 3000++export const clampRadius = r => {+ const n = Math.round(Number(r))+ if (!Number.isFinite(n)) return RADIUS.def+ return Math.min(RADIUS.max, Math.max(RADIUS.min, n))+}++export const validLatLng = (lat, lng) =>+ Number.isFinite(lat) && Number.isFinite(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180 && !(lat === 0 && lng === 0)++const TIME = /^([01]\d|2[0-3]):([0-5]\d)$/+export const minuteOf = hhmm => {+ const m = TIME.exec(String(hhmm || ''))+ return m ? Number(m[1]) * 60 + Number(m[2]) : null+}++const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '')+const round6 = n => Math.round(n * 1e6) / 1e6++/** One gym as kept: a name, a place, a radius in metres and an optional text. Null if unusable. */+export function normGym(g) {+ if (!g || typeof g !== 'object') return null+ const lat = Number(g.lat), lng = Number(g.lng)+ if (!validLatLng(lat, lng)) return null+ const id = str(g.id, 40) || 'g' + Math.random().toString(36).slice(2, 10)+ return { id, name: str(g.name, 60), lat: round6(lat), lng: round6(lng), radius: clampRadius(g.radius ?? RADIUS.def), text: str(g.text, 120) }+}++/** The time window, or null for "any time". Both ends must be valid; equal ends mean any time. */+export function normWindow(w) {+ if (!w || typeof w !== 'object') return null+ const from = minuteOf(w.from), to = minuteOf(w.to)+ if (from == null || to == null || from === to) return null+ return { from: w.from, to: w.to }+}++export function normConfig(c) {+ const o = c && typeof c === 'object' ? c : {}+ const seen = new Set()+ const gyms = (Array.isArray(o.gyms) ? o.gyms : []).map(normGym).filter(g => g && !seen.has(g.id) && seen.add(g.id)).slice(0, MAX_GYMS)+ return { on: o.on === true, gyms, window: normWindow(o.window) }+}++/** Whether `date` (local time) falls in the window; an overnight window (22:00 to 02:00) wraps. */+export function inWindow(win, date) {+ const w = normWindow(win)+ if (!w) return true+ const from = minuteOf(w.from), to = minuteOf(w.to)+ const m = date.getHours() * 60 + date.getMinutes()+ return from < to ? m >= from && m < to : m >= from || m < to+}++/**+ * What the native side is told about the profile, re-sent whenever it changes: the last day+ * trained, a day note that excuses today, when the running session started (0: none), and the+ * notification's words in the app's language.+ */+export function statusOf(S, now = new Date()) {+ let trainedOn = ''+ for (const w of S?.workouts || []) if (typeof w?.d === 'string' && w.d > trainedOn) trainedOn = w.d+ const today = isoOf(now)+ const a = S?.active+ const activeSince = a && !a.editingWorkoutId && !a.backfill && Number(a.start) > 0 ? Number(a.start) : 0+ return {+ trainedOn,+ quietOn: S && excusedOn(S, today) ? today : '',+ activeSince,+ title: t('Gym spotted'),+ body: t('Ready for your workout? 💪'),+ // Android's name for the notification channel, in the app's language.+ channel: t('Gym reminder'),+ }+}++/**+ * Why a gym entered at `now` would NOT notify, or null when it should. The native plugins apply+ * exactly this (GymReminderRules.swift, GymReminderRules.java), in this order:+ * off the reminder is switched off (or no gym)+ * fired it already went off today (max once a day, whichever gym)+ * trained a workout is logged for today+ * quiet today has a day note that excuses it (sick, away)+ * active a session is running (started less than 12 hours ago)+ * window outside the optional time window+ */+export function skipReason({ config, status, lastFired = '', now = new Date() }) {+ const c = normConfig(config)+ if (!c.on || !c.gyms.length) return 'off'+ const today = isoOf(now)+ if (lastFired === today) return 'fired'+ if (status?.trainedOn === today) return 'trained'+ if (status?.quietOn === today) return 'quiet'+ const since = Number(status?.activeSince) || 0+ if (since > 0 && now.getTime() - since < ACTIVE_FRESH_MS) return 'active'+ if (!inWindow(c.window, now)) return 'window'+ return null+}++/** The notification for a gym: its own text when it has one, the default otherwise. */+export function copyFor(gym, status = statusOf(null)) {+ return { title: status.title, body: str(gym?.text, 120) || status.body }+}++/** Distance in metres between two points (haversine), for "you are here" checks in the editor. */+export function distanceM(a, b) {+ const R = 6371000, rad = x => x * Math.PI / 180+ const dLat = rad(b.lat - a.lat), dLng = rad(b.lng - a.lng)+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLng / 2) ** 2+ return 2 * R * Math.asin(Math.min(1, Math.sqrt(h)))+}++/* ---------------- this device's copy ---------------- */++/** This device's switch (the places are only on the native side, see writeLocal). */+export function readGymConfig(storage = globalThis.localStorage) {+ try { return normConfig(JSON.parse(storage?.getItem(GYM_KEY) || 'null')) } catch { return normConfig(null) }+}+// Only whether it is on, never the places: WebView storage goes into the phone's own backups+// (iCloud, Google), and the gyms are not to leave the phone. The native side holds the rest.+function writeLocal(config, storage = globalThis.localStorage) {+ try { storage?.setItem(GYM_KEY, JSON.stringify({ on: !!config.on })) } catch { /* private mode: the native copy still holds */ }+}++/* ---------------- the native side ---------------- */++// Registered once and handed out inside an object: a Capacitor plugin proxy answers `then` with a+// native call that never settles, so a promise resolved with the bare proxy hangs (#42).+let pluginP = null+const gymPlugin = () => pluginP || (pluginP = (async () => {+ if (!MOBILE) return null+ const { registerPlugin, Capacitor } = await import('@capacitor/core')+ const p = Capacitor.getPlatform()+ if (p !== 'ios' && p !== 'android') return null+ return { GymReminder: registerPlugin('GymReminder'), platform: p }+})().catch(() => null))++/** Whether this device can have a gym reminder at all: the phone app, nothing else. */+export async function gymReminderAvailable() {+ return !!(await gymPlugin())+}++/**+ * The config as the native side holds it (it outlives an evicted WebView storage), falling back+ * to this page's mirror. Returns { config, permission }.+ */+export async function loadGymConfig() {+ const p = await gymPlugin()+ let config = memory || readGymConfig()+ let permission = null+ if (!p) return { config, permission }+ try {+ const r = await p.GymReminder.get()+ if (r?.config) { config = normConfig(r.config); writeLocal(config); memory = config }+ permission = r?.permission || null+ } catch { /* an older native shell without the plugin: the mirror */ }+ return { config, permission }+}++/**+ * Saves the config on this device and has the phone watch its gyms (or stop). Returns what the+ * native side reports: { watching: number of regions it watches, permission }.+ */+let memory = null+export async function saveGymConfig(next, S = null) {+ const config = normConfig(next)+ writeLocal(config)+ memory = config+ const p = await gymPlugin()+ if (!p) return { watching: 0, permission: null }+ try {+ if (S) await pushGymStatus(S, true)+ return await p.GymReminder.configure({ config }) || { watching: 0, permission: null }+ } catch (e) {+ return { watching: 0, permission: null, error: String(e?.message || e) }+ }+}++let lastStatus = ''+/**+ * 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.+ */+export async function pushGymStatus(S, force = false) {+ if (!MOBILE) return false+ if (!force && !readGymConfig().on) return false+ const status = statusOf(S)+ const key = JSON.stringify(status)+ if (!force && key === lastStatus) return false+ const p = await gymPlugin()+ if (!p) return false+ try { await p.GymReminder.status(status); lastStatus = key; return true } catch { return false }+}++/** { location: 'granted'|'denied'|'prompt', background: 'granted'|'denied'|'prompt', notifications } */+export async function gymPermissions() {+ const p = await gymPlugin()+ if (!p) return null+ try { return await p.GymReminder.permission() } catch { return null }+}+/** While-using location: for "I'm at the gym right now". */+export async function askForegroundLocation() {+ const p = await gymPlugin()+ if (!p) return null+ try { return await p.GymReminder.requestForeground() } catch { return null }+}+/** "Always" (iOS) / "Allow all the time" (Android 10+): asked only after the in-app explainer. */+export async function askBackgroundLocation() {+ const p = await gymPlugin()+ if (!p) return null+ try { return await p.GymReminder.requestBackground() } catch { return null }+}+/** One fix of where the phone is: { lat, lng, accuracy } or null. */+export async function currentPosition() {+ const p = await gymPlugin()+ if (!p) return null+ try {+ const r = await p.GymReminder.currentPosition()+ return r && validLatLng(Number(r.lat), Number(r.lng)) ? { lat: Number(r.lat), lng: Number(r.lng), accuracy: Number(r.accuracy) || null } : null+ } catch { return null }+}+/** The system's settings page for this app, where a denied permission can still be allowed. */+export async function openAppSettings() {+ const p = await gymPlugin()+ if (!p) return false+ try { await p.GymReminder.openSettings(); return true } catch { return false }+}++/**+ * Calls `cb` when the gym notification was tapped. Android: the plugin's own `open` event (kept+ * until a listener is there, so a tap that launched the app still arrives). iOS: the notification+ * goes through Capacitor's local-notifications handler, which reports the tap with our id.+ * Returns a function that stops listening.+ */+export function onGymReminderOpen(cb) {+ if (!MOBILE) return () => {}+ const handles = []+ let gone = false+ const keep = h => { if (gone) h?.remove?.(); else handles.push(h) }+ gymPlugin().then(p => {+ if (!p) return+ if (p.platform === 'android') {+ return Promise.resolve(p.GymReminder.addListener('open', () => cb())).then(keep)+ }+ return import('@capacitor/local-notifications').then(({ LocalNotifications }) =>+ Promise.resolve(LocalNotifications.addListener('localNotificationActionPerformed', e => {+ const n = e?.notification+ if (e?.actionId !== 'dismiss' && (n?.id === NOTIFICATION_ID || n?.extra?.gymReminder)) cb()+ })).then(keep))+ }).catch(() => {})+ return () => { gone = true; handles.splice(0).forEach(h => { try { h?.remove?.() } catch { /* gone already */ } }) }+}++export function _resetGymReminder() { pluginP = null; lastStatus = ''; memory = null }diff --git a/frontend/src/lib/gym-reminder.test.js b/frontend/src/lib/gym-reminder.test.jsnew file mode 100644index 000000000..91754605f--- /dev/null+++ b/frontend/src/lib/gym-reminder.test.js@@ -0,0 +1,220 @@+// @vitest-environment happy-dom+import { beforeEach, describe, expect, it, vi } from 'vitest'++/* The gym reminder (#614): settings kept on this device only, the no-nag rule the native side+ 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,+}))+vi.mock('./mobile.js', () => ({ get MOBILE() { return mocks.MOBILE } }))+vi.mock('@capacitor/core', () => ({+ Capacitor: { getPlatform: () => mocks.platform },+ registerPlugin: name => {+ mocks.registered+++ expect(name).toBe('GymReminder')+ // A Capacitor-style proxy: every property is a native method, `then` included, and a `then`+ // that never calls back is what hung the Coach (#42). Resolving with it would hang here too.+ return new Proxy({}, {+ get: (_, k) => {+ if (k === 'get') return async () => mocks.get+ if (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 === 'addListener') return async (ev, fn) => { mocks.listeners[ev] = fn; return { remove: () => { delete mocks.listeners[ev] } } }+ return () => new Promise(() => {})+ },+ })+ },+}))+const ln = vi.hoisted(() => ({ listeners: {} }))+vi.mock('@capacitor/local-notifications', () => ({+ LocalNotifications: { addListener: async (ev, fn) => { ln.listeners[ev] = fn; return { remove: () => { delete ln.listeners[ev] } } } },+}))++import {+ clampRadius, normGym, normConfig, normWindow, inWindow, skipReason, statusOf, copyFor, distanceM,+ readGymConfig, saveGymConfig, loadGymConfig, pushGymStatus, onGymReminderOpen, _resetGymReminder,+ GYM_KEY, RADIUS, MAX_GYMS, NOTIFICATION_ID,+} from './gym-reminder.js'++const at = (iso, hhmm) => new Date(`${iso}T${hhmm}:00`)+const gym = (over = {}) => ({ id: 'g1', name: 'Downtown', lat: 47.3769, lng: 8.5417, radius: 100, text: '', ...over })+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.get = null; mocks.configure = { watching: 1, permission: { location: 'granted', background: 'granted' } }; mocks.status = undefined+ ln.listeners = {}+ localStorage.clear()+ _resetGymReminder()+})++describe('settings', () => {+ it('radius: 100 m by default, kept between 50 and 500', () => {+ expect(clampRadius(undefined)).toBe(RADIUS.def)+ expect(clampRadius('abc')).toBe(100)+ expect(clampRadius(10)).toBe(50)+ expect(clampRadius(9000)).toBe(500)+ expect(clampRadius(149.6)).toBe(150)+ expect(normGym({ lat: 1, lng: 2 }).radius).toBe(100)+ })+ it('a gym needs a real place; name and text are trimmed and capped', () => {+ expect(normGym({ lat: 95, lng: 0 })).toBe(null)+ expect(normGym({ lat: 0, lng: 0 })).toBe(null)+ expect(normGym({ lat: 'x', lng: 1 })).toBe(null)+ const g = normGym({ id: 'a', lat: 47.123456789, lng: 8.1, name: ' Home gym ', text: 'x'.repeat(500) })+ expect(g).toMatchObject({ id: 'a', lat: 47.123457, name: 'Home gym' })+ expect(g.text).toHaveLength(120)+ expect(normGym({ lat: 1, lng: 2 }).id).toMatch(/^g/)+ })+ it('off by default, several gyms, duplicates dropped, at most 20 (iOS watches 20 regions)', () => {+ expect(normConfig(undefined)).toEqual({ on: false, gyms: [], window: null })+ const many = Array.from({ length: 25 }, (_, i) => gym({ id: 'g' + i, lat: 47 + i / 100 }))+ expect(normConfig({ on: true, gyms: [...many, gym({ id: 'g0' })] }).gyms).toHaveLength(MAX_GYMS)+ expect(normConfig({ gyms: [gym(), gym()] }).gyms).toHaveLength(1)+ expect(normConfig({ on: 'yes' }).on).toBe(false)+ })+ it('the time window: both ends valid, equal ends mean any time', () => {+ expect(normWindow({ from: '06:00', to: '22:00' })).toEqual({ from: '06:00', to: '22:00' })+ expect(normWindow({ from: '06:00', to: '06:00' })).toBe(null)+ expect(normWindow({ from: '6:00', to: '22:00' })).toBe(null)+ expect(normWindow({ from: '24:00', to: '22:00' })).toBe(null)+ })+ it('inWindow, also across midnight', () => {+ const day = { from: '06:00', to: '22:00' }+ expect(inWindow(day, at('2026-10-15', '05:59'))).toBe(false)+ expect(inWindow(day, at('2026-10-15', '06:00'))).toBe(true)+ expect(inWindow(day, at('2026-10-15', '21:59'))).toBe(true)+ expect(inWindow(day, at('2026-10-15', '22:00'))).toBe(false)+ const night = { from: '22:00', to: '02:00' }+ expect(inWindow(night, at('2026-10-15', '23:30'))).toBe(true)+ expect(inWindow(night, at('2026-10-15', '01:30'))).toBe(true)+ expect(inWindow(night, at('2026-10-15', '12:00'))).toBe(false)+ expect(inWindow(null, at('2026-10-15', '03:00'))).toBe(true)+ })+ it('distanceM is about right (Zurich HB to Bellevue ≈ 1.6 km)', () => {+ const d = distanceM({ lat: 47.3779, lng: 8.5403 }, { lat: 47.3667, lng: 8.5450 })+ expect(d).toBeGreaterThan(1200)+ expect(d).toBeLessThan(1400)+ })+})++describe('no-nag rule (what the native side applies when a gym is entered)', () => {+ const now = at('2026-10-15', '18:00')+ const status = (over = {}) => ({ trainedOn: '2026-10-14', quietOn: '', activeSince: 0, ...over })+ it('goes off on a normal day', () => {+ expect(skipReason({ config: on(), status: status(), now })).toBe(null)+ })+ it('off, or no gym: never', () => {+ expect(skipReason({ config: on({ on: false }), status: status(), now })).toBe('off')+ expect(skipReason({ config: on({ gyms: [] }), status: status(), now })).toBe('off')+ })+ it('max once a day', () => {+ expect(skipReason({ config: on(), status: status(), lastFired: '2026-10-15', now })).toBe('fired')+ expect(skipReason({ config: on(), status: status(), lastFired: '2026-10-14', now })).toBe(null)+ })+ it('not after training today, nor on an excused day', () => {+ expect(skipReason({ config: on(), status: status({ trainedOn: '2026-10-15' }), now })).toBe('trained')+ expect(skipReason({ config: on(), status: status({ quietOn: '2026-10-15' }), now })).toBe('quiet')+ })+ it('not while a workout runs; a session left open since yesterday does not count', () => {+ expect(skipReason({ config: on(), status: status({ activeSince: now.getTime() - 3600e3 }), now })).toBe('active')+ expect(skipReason({ config: on(), status: status({ activeSince: now.getTime() - 13 * 3600e3 }), now })).toBe(null)+ })+ it('only inside the optional time window', () => {+ const config = on({ window: { from: '06:00', to: '12:00' } })+ expect(skipReason({ config, status: status(), now })).toBe('window')+ expect(skipReason({ config, status: status(), now: at('2026-10-15', '07:00') })).toBe(null)+ })+})++describe('status for the native side', () => {+ it('the last day trained, a running session, an excused today', () => {+ const S = {+ workouts: [{ d: '2026-10-10' }, { d: '2026-10-14' }, { d: '2026-10-12' }],+ active: { start: 1234, entries: [] },+ dayNotes: { '2026-10-15': { tag: 'sick' } },+ }+ const st = statusOf(S, at('2026-10-15', '09:00'))+ expect(st.trainedOn).toBe('2026-10-14')+ expect(st.activeSince).toBe(1234)+ expect(st.title).toBe('Gym spotted')+ expect(st.body).toBe('Ready for your workout? 💪')+ })+ it('editing an old workout or logging one after the fact is not a running session', () => {+ expect(statusOf({ active: { start: 5, editingWorkoutId: 'w1' } }).activeSince).toBe(0)+ expect(statusOf({ active: { start: 5, backfill: true } }).activeSince).toBe(0)+ expect(statusOf({}).activeSince).toBe(0)+ })+ it('a gym with its own text uses it', () => {+ const st = statusOf({})+ expect(copyFor(gym({ text: 'Leg day lives here' }), st)).toEqual({ title: 'Gym spotted', body: 'Leg day lives here' })+ expect(copyFor(gym(), st).body).toBe('Ready for your workout? 💪')+ })+})++describe('kept on the device, never in the synced state', () => {+ it('saving writes the device key and hands the native side the config', async () => {+ const r = await saveGymConfig(on())+ expect(r.watching).toBe(1)+ expect(readGymConfig().on).toBe(true)+ // only the switch in WebView storage (it lands in phone backups); no place, no name+ expect(JSON.parse(localStorage.getItem(GYM_KEY))).toEqual({ on: true })+ expect(localStorage.getItem(GYM_KEY)).not.toMatch(/47\.37|Downtown/)+ expect(mocks.calls).toEqual([['configure', { config: normConfig(on()) }]])+ // nothing went into the profile's storage key+ expect(localStorage.getItem('gym_state_v1')).toBe(null)+ })+ 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'])+ })+ it('loading prefers the native copy (WebView storage can be evicted)', async () => {+ localStorage.setItem(GYM_KEY, JSON.stringify(on({ on: false })))+ mocks.get = { config: on(), permission: { location: 'granted', background: 'prompt' } }+ const r = await loadGymConfig()+ expect(r.config.on).toBe(true)+ expect(r.permission.background).toBe('prompt')+ expect(readGymConfig().on).toBe(true)+ })+ it('the web build: no plugin, nothing native, settings still readable', async () => {+ mocks.MOBILE = false+ const r = await saveGymConfig(on())+ expect(r.watching).toBe(0)+ expect(mocks.registered).toBe(0)+ expect(await pushGymStatus({ workouts: [] })).toBe(false)+ })+ it('status: only with the reminder on, and only when something changed', async () => {+ expect(await pushGymStatus({ workouts: [] })).toBe(false)+ localStorage.setItem(GYM_KEY, JSON.stringify(on()))+ expect(await pushGymStatus({ workouts: [] })).toBe(true)+ expect(await pushGymStatus({ workouts: [] })).toBe(false)+ expect(await pushGymStatus({ workouts: [{ d: '2026-10-15' }] })).toBe(true)+ expect(mocks.calls.filter(c => c[0] === 'status')).toHaveLength(2)+ })+})++describe('a tap on the notification', () => {+ it('Android: the plugin\'s open event', async () => {+ const cb = vi.fn()+ const stop = onGymReminderOpen(cb)+ await flush(); await flush()+ mocks.listeners.open()+ expect(cb).toHaveBeenCalledTimes(1)+ stop()+ expect(mocks.listeners.open).toBeUndefined()+ })+ it('iOS: Capacitor\'s local-notification tap with our id, not the other notifications', async () => {+ mocks.platform = 'ios'+ const cb = vi.fn()+ onGymReminderOpen(cb)+ await flush(); await flush(); await flush()+ const fire = ln.listeners.localNotificationActionPerformed+ fire({ actionId: 'tap', notification: { id: 1000 } })+ fire({ actionId: 'dismiss', notification: { id: NOTIFICATION_ID } })+ expect(cb).not.toHaveBeenCalled()+ fire({ actionId: 'tap', notification: { id: NOTIFICATION_ID } })+ expect(cb).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.jsindex c77b93f0f..d1562637f 100644--- a/frontend/src/lib/mobile.js+++ b/frontend/src/lib/mobile.js@@ -206,6 +206,9 @@ export function buildNudgeNotifications(S, now = new Date()) {// may just have been edited. `interactive` gates the OS permission prompt to the Settings toggle;// a background resync never pops a dialog.export async function syncReminder(S, interactive = false) {+ // The gym reminder (lib/gym-reminder.js) decides on the phone whether to go off, from what it+ // was last told about today: told again here, after every save and on every return to the app.+ if (MOBILE) import('./gym-reminder.js').then(m => m.pushGymStatus(S)).catch(() => {})try {const { LocalNotifications } = await import('@capacitor/local-notifications')await LocalNotifications.cancel({ notifications: [diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 2618d79ec..f7db38982 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -2469,4 +2469,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'على هذا الجهاز تمرين واحد ليس في هذه النسخة الاحتياطية. الاستبدال يحذفه.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'على هذا الجهاز {0} تمارين ليست في هذه النسخة الاحتياطية. الاستبدال يحذفها.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'تنبيه صغير عندما تدخل صالتك.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'حوالي 100 م تكفي معظم الصالات. أكبر إذا انتبه الهاتف لك متأخرًا، وأصغر إذا نبّهك وأنت ما زلت في الشارع أمامها.',+ 'Add a gym': 'إضافة صالة',+ 'All the time': 'السماح طوال الوقت',+ 'Allow location “All the time”?': 'السماح بالموقع «طوال الوقت»؟',+ 'Allow location “Always”?': 'السماح بالموقع «دائمًا»؟',+ 'Always': 'دائمًا',+ 'Couldn’t find where you are. Try the map instead.': 'لم نجد موقعك. جرّب الخريطة.',+ 'Finding you…': 'نبحث عنك…',+ 'From': 'من',+ 'Gym reminder': 'تذكير الصالة',+ 'Gym spotted': 'تم رصد الصالة',+ 'I’m at the gym right now': 'أنا في الصالة الآن',+ 'Leave it empty for the default.': 'اتركه فارغًا للنص الافتراضي.',+ 'Location access': 'الوصول إلى الموقع',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'لا يملك openGym إذنًا بالموقع. يمكنك تغيير ذلك من إعدادات الهاتف.',+ 'My gym': 'صالتي',+ 'Name': 'الاسم',+ 'No more nudges when you arrive here.': 'لا مزيد من التنبيهات عند وصولك إلى هنا.',+ 'Not asked yet': 'لم يُطلب بعد',+ 'Nothing found. Try a street and a town.': 'لم يُعثر على شيء. جرّب شارعًا ومدينة.',+ 'Notification text': 'نص الإشعار',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'إشعارات openGym متوقفة، لذا لا مكان يظهر فيه التذكير.',+ 'On the next screen, pick “Allow all the time”.': 'في الشاشة التالية اختر «السماح طوال الوقت».',+ 'Only between certain hours': 'في ساعات معيّنة فقط',+ 'Only while using the app': 'أثناء استخدام التطبيق فقط',+ 'Outside these hours the phone stays quiet, even at the gym.': 'خارج هذه الساعات يبقى الهاتف صامتًا، حتى في الصالة.',+ 'Pick it on the map': 'اختر على الخريطة',+ 'Radius': 'نصف القطر',+ 'Ready for your workout? 💪': 'جاهز لتمرينك؟ 💪',+ 'Remove this gym?': 'إزالة هذه الصالة؟',+ 'Search': 'بحث',+ 'Search an address': 'ابحث عن عنوان',+ 'Search an address or drag the pin': 'ابحث عن عنوان أو اسحب الدبوس',+ 'Searching…': 'جارٍ البحث…',+ 'Tap the map or drag the pin onto your gym.': 'اضغط على الخريطة أو اسحب الدبوس إلى صالتك.',+ 'Tap the map to put the pin on your gym first.': 'اضغط على الخريطة أولًا لتضع الدبوس على صالتك.',+ 'That’s 20 gyms, the most a phone can watch.': 'هذه 20 صالة، أقصى ما يستطيع الهاتف مراقبته.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'البحث عن العنوان يسأل OpenStreetMap (Nominatim)، وفقط عندما تضغط بحث.',+ 'The address search didn’t answer. Try again in a moment.': 'لم يستجب البحث عن العنوان. حاول مرة أخرى بعد قليل.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'الهاتف نفسه يراقب الصالات التي أضفتها ولا يوقظ openGym إلا عند وصولك. لا تتبّع بين ذلك، ومواقعك لا تغادر هذا الهاتف أبدًا.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'يحتاج التذكير إلى الموقع في الخلفية. يمكنك السماح به من إعدادات الهاتف.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'لكي يلاحظ openGym أنك دخلت صالتك وهو مغلق، يجب أن يسمح له الهاتف برؤية موقعك في الخلفية.',+ 'Until': 'إلى',+ 'Use my location': 'استخدم موقعي',+ 'Uses where your phone is': 'يستخدم موقع هاتفك',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'ادخل إحدى صالاتك وسينبّهك openGym لتضغط ابدأ. مرة في اليوم على الأكثر، وأبدًا إذا كنت تمرّنت بالفعل. صالاتك تبقى على هذا الهاتف.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'بدون الموقع في الخلفية لا يستطيع الهاتف التعرّف على صالتك وopenGym مغلق.',+ 'Your gyms': 'صالاتك',+ '{0} m': '{0} م',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'الموقع الدقيق متوقف لـ openGym. شغّله من إعدادات الهاتف، وإلا فلن يمكن التعرّف على صالتك.',+ '{0} m around the pin': '{0} م حول الدبوس',+ 'Your gym': 'صالتك',}diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.jsindex 80b006ca5..9f0868d1c 100644--- a/frontend/src/locales/bn.js+++ b/frontend/src/locales/bn.js@@ -2493,4 +2493,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'এই ডিভাইসে ১টি ওয়ার্কআউট আছে যা এই ব্যাকআপে নেই। প্রতিস্থাপন করলে এটি মুছে যাবে।','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'এই ডিভাইসে {0}টি ওয়ার্কআউট আছে যা এই ব্যাকআপে নেই। প্রতিস্থাপন করলে এগুলো মুছে যাবে।',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'জিমে ঢুকলেই একটু খোঁচা।',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'বেশিরভাগ জিমের জন্য প্রায় ১০০ মি. যথেষ্ট। ফোন দেরিতে টের পেলে বাড়ান, বাইরের রাস্তাতেই খোঁচা দিলে কমান।',+ 'Add a gym': 'জিম যোগ করুন',+ 'All the time': 'সব সময় অনুমতি দিন',+ 'Allow location “All the time”?': 'লোকেশন “সব সময় অনুমতি দিন”?',+ 'Allow location “Always”?': 'লোকেশন “সবসময়” অনুমতি দেবেন?',+ 'Always': 'সবসময়',+ 'Couldn’t find where you are. Try the map instead.': 'আপনাকে খুঁজে পাওয়া গেল না। ম্যাপ দিয়ে চেষ্টা করুন।',+ 'Finding you…': 'আপনাকে খুঁজছি…',+ 'From': 'থেকে',+ 'Gym reminder': 'জিম রিমাইন্ডার',+ 'Gym spotted': 'জিম দেখা গেছে',+ 'I’m at the gym right now': 'আমি এখন জিমে আছি',+ 'Leave it empty for the default.': 'ডিফল্ট লেখার জন্য ফাঁকা রাখুন।',+ 'Location access': 'লোকেশন অ্যাক্সেস',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym-এর লোকেশনের অনুমতি নেই। ফোনের সেটিংসে বদলাতে পারেন।',+ 'My gym': 'আমার জিম',+ 'Name': 'নাম',+ 'No more nudges when you arrive here.': 'এখানে পৌঁছালে আর খোঁচা নয়।',+ 'Not asked yet': 'এখনও জিজ্ঞেস করা হয়নি',+ 'Nothing found. Try a street and a town.': 'কিছু পাওয়া যায়নি। একটা রাস্তা আর শহর দিয়ে চেষ্টা করুন।',+ 'Notification text': 'নোটিফিকেশনের লেখা',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'openGym-এর নোটিফিকেশন বন্ধ, তাই রিমাইন্ডার দেখানোর কোনো জায়গা নেই।',+ 'On the next screen, pick “Allow all the time”.': 'পরের স্ক্রিনে “সব সময় অনুমতি দিন” বেছে নিন।',+ 'Only between certain hours': 'শুধু নির্দিষ্ট সময়ে',+ 'Only while using the app': 'শুধু অ্যাপ ব্যবহারের সময়',+ 'Outside these hours the phone stays quiet, even at the gym.': 'এই সময়ের বাইরে ফোন চুপ থাকে, জিমে থাকলেও।',+ 'Pick it on the map': 'ম্যাপে বেছে নিন',+ 'Radius': 'ব্যাসার্ধ',+ 'Ready for your workout? 💪': 'ওয়ার্কআউটের জন্য তৈরি? 💪',+ 'Remove this gym?': 'এই জিম সরাবেন?',+ 'Search': 'খুঁজুন',+ 'Search an address': 'ঠিকানা খুঁজুন',+ 'Search an address or drag the pin': 'ঠিকানা খুঁজুন বা পিন টেনে আনুন',+ 'Searching…': 'খুঁজছি…',+ 'Tap the map or drag the pin onto your gym.': 'ম্যাপে ট্যাপ করুন বা পিনটা আপনার জিমের ওপর টেনে আনুন।',+ 'Tap the map to put the pin on your gym first.': 'আগে ম্যাপে ট্যাপ করে পিনটা আপনার জিমে বসান।',+ 'That’s 20 gyms, the most a phone can watch.': '২০টা জিম হয়ে গেছে, ফোন এর বেশি নজর রাখতে পারে না।',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'ঠিকানা খোঁজা OpenStreetMap (Nominatim)-কে জিজ্ঞেস করে, আর শুধু তখনই যখন আপনি খুঁজুন ট্যাপ করেন।',+ 'The address search didn’t answer. Try again in a moment.': 'ঠিকানা খোঁজা সাড়া দেয়নি। একটু পরে আবার চেষ্টা করুন।',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'আপনার যোগ করা জিমগুলোর ওপর ফোন নিজেই নজর রাখে আর আপনি পৌঁছালেই শুধু openGym-কে জাগায়। মাঝে কোনো ট্র্যাকিং নেই, আর আপনার জায়গাগুলো কখনও এই ফোন ছেড়ে যায় না।',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'রিমাইন্ডারের ব্যাকগ্রাউন্ডে লোকেশন দরকার। ফোনের সেটিংসে অনুমতি দিতে পারেন।',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'openGym বন্ধ থাকা অবস্থায় আপনি জিমে ঢুকেছেন তা টের পেতে, ফোনকে ব্যাকগ্রাউন্ডে আপনার লোকেশন দেখতে দিতে হবে।',+ 'Until': 'পর্যন্ত',+ 'Use my location': 'আমার লোকেশন ব্যবহার করুন',+ 'Uses where your phone is': 'ফোনের লোকেশন নেয়',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'আপনার কোনো জিমে ঢুকুন, openGym আপনাকে স্টার্ট চাপার খোঁচা দেবে। দিনে বড়জোর একবার, আর আগেই ট্রেনিং করে থাকলে কখনও না। আপনার জিমগুলো এই ফোনেই থাকে।',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'ব্যাকগ্রাউন্ড লোকেশন ছাড়া openGym বন্ধ থাকলে ফোন আপনার জিম চিনতে পারে না।',+ 'Your gyms': 'আপনার জিমগুলো',+ '{0} m': '{0} মি.',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'openGym-এর জন্য সুনির্দিষ্ট লোকেশন বন্ধ। ফোনের সেটিংসে চালু করুন, নইলে আপনার জিম চেনা যাবে না।',+ '{0} m around the pin': 'পিনের চারপাশে {0} মি.',+ 'Your gym': 'আপনার জিম',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex e092e5278..a599b3585 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -2434,4 +2434,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Auf diesem Gerät ist 1 Training, das nicht in diesem Backup ist. Ersetzen löscht es.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Auf diesem Gerät sind {0} Trainings, die nicht in diesem Backup sind. Ersetzen löscht sie.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Ein Stupser, wenn du dein Gym betrittst.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Rund 100 m passen für die meisten Gyms. Größer, wenn das Handy dich spät bemerkt, kleiner, wenn es dich schon auf der Straße davor anstupst.',+ 'Add a gym': 'Gym hinzufügen',+ 'All the time': 'Immer zulassen',+ 'Allow location “All the time”?': 'Standort „Immer zulassen“?',+ 'Allow location “Always”?': 'Standort „Immer“ erlauben?',+ 'Always': 'Immer',+ 'Couldn’t find where you are. Try the map instead.': 'Wir finden dich gerade nicht. Versuch es mit der Karte.',+ 'Finding you…': 'Suche dich…',+ 'From': 'Von',+ 'Gym reminder': 'Gym-Erinnerung',+ '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.',+ 'Location access': 'Standortzugriff',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym darf deinen Standort nicht sehen. Das kannst du in den Einstellungen des Handys ändern.',+ 'My gym': 'Mein Gym',+ 'Name': 'Name',+ 'No more nudges when you arrive here.': 'Hier gibt es dann keinen Stupser mehr, wenn du ankommst.',+ 'Not asked yet': 'Noch nicht gefragt',+ 'Nothing found. Try a street and a town.': 'Nichts gefunden. Versuch es mit Straße und Ort.',+ 'Notification text': 'Text der Mitteilung',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'Mitteilungen sind für openGym aus, also kann die Erinnerung nirgends auftauchen.',+ 'On the next screen, pick “Allow all the time”.': 'Wähle auf dem nächsten Bildschirm „Immer zulassen“.',+ 'Only between certain hours': 'Nur zu bestimmten Zeiten',+ 'Only while using the app': 'Nur während der Nutzung der App',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Außerhalb dieser Zeiten bleibt das Handy still, auch im Gym.',+ 'Pick it on the map': 'Auf der Karte wählen',+ 'Radius': 'Radius',+ 'Ready for your workout? 💪': 'Bereit fürs Training? 💪',+ 'Remove this gym?': 'Dieses Gym entfernen?',+ 'Search': 'Suchen',+ 'Search an address': 'Adresse suchen',+ 'Search an address or drag the pin': 'Adresse suchen oder die Nadel ziehen',+ 'Searching…': 'Suche…',+ 'Tap the map or drag the pin onto your gym.': 'Tippe auf die Karte oder zieh die Nadel auf dein Gym.',+ 'Tap the map to put the pin on your gym first.': 'Tippe zuerst auf die Karte, damit die Nadel auf deinem Gym steht.',+ 'That’s 20 gyms, the most a phone can watch.': 'Das sind 20 Gyms, mehr kann ein Handy nicht beobachten.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'Die Adresssuche fragt OpenStreetMap (Nominatim), und nur, wenn du auf Suchen tippst.',+ 'The address search didn’t answer. Try again in a moment.': 'Die Adresssuche hat nicht geantwortet. Versuch es gleich nochmal.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'Das Handy beobachtet deine Gyms selbst und weckt openGym nur, wenn du ankommst. Kein Tracking dazwischen, und deine Orte verlassen dieses Handy nie.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'Die Erinnerung braucht Standortzugriff im Hintergrund. Den kannst du in den Einstellungen des Handys erlauben.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Damit openGym merkt, dass du dein Gym betreten hast, während die App zu ist, muss das Handy openGym deinen Standort im Hintergrund sehen lassen.',+ 'Until': 'Bis',+ 'Use my location': 'Meinen Standort nehmen',+ 'Uses where your phone is': 'Nimmt den Standort deines Handys',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Betrittst du eines deiner Gyms, stupst openGym dich an, auf Start zu drücken. Höchstens einmal am Tag und nie, wenn du schon trainiert hast. Deine Gyms bleiben auf diesem Handy.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Ohne Standort im Hintergrund kann das Handy dein Gym nicht erkennen, solange openGym zu ist.',+ 'Your gyms': 'Deine Gyms',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'Genauer Standort ist für openGym aus. Schalte ihn in den Einstellungen des Handys ein, sonst kann dein Gym nicht erkannt werden.',+ '{0} m around the pin': '{0} m um die Nadel',+ 'Your gym': 'Dein Gym',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 27517af80..2d1725864 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tiene 1 entrenamiento que no está en esta copia. Reemplazar lo elimina.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tiene {0} entrenamientos que no están en esta copia. Reemplazar los elimina.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Un toque cuando entras en tu gimnasio.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Unos 100 m sirven para casi todos los gimnasios. Más si el móvil te detecta tarde, menos si ya te avisa en la calle de enfrente.',+ 'Add a gym': 'Añadir un gimnasio',+ 'All the time': 'Permitir todo el tiempo',+ 'Allow location “All the time”?': '¿Permitir la ubicación «Todo el tiempo»?',+ 'Allow location “Always”?': '¿Permitir la ubicación «Siempre»?',+ 'Always': 'Siempre',+ 'Couldn’t find where you are. Try the map instead.': 'No pudimos encontrarte. Prueba con el mapa.',+ 'Finding you…': 'Buscándote…',+ 'From': 'Desde',+ 'Gym reminder': 'Recordatorio del 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.',+ 'Location access': 'Acceso a la ubicación',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym no tiene permiso de ubicación. Puedes cambiarlo en los ajustes del móvil.',+ 'My gym': 'Mi gimnasio',+ 'Name': 'Nombre',+ 'No more nudges when you arrive here.': 'Ya no habrá aviso al llegar aquí.',+ 'Not asked yet': 'Aún no se ha pedido',+ 'Nothing found. Try a street and a town.': 'No se encontró nada. Prueba con una calle y una ciudad.',+ 'Notification text': 'Texto de la notificación',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'Las notificaciones de openGym están desactivadas, así que el recordatorio no tiene dónde aparecer.',+ 'On the next screen, pick “Allow all the time”.': 'En la siguiente pantalla, elige «Permitir todo el tiempo».',+ 'Only between certain hours': 'Solo a ciertas horas',+ 'Only while using the app': 'Solo mientras se usa la app',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Fuera de este horario el móvil se queda callado, incluso en el gimnasio.',+ 'Pick it on the map': 'Elegir en el mapa',+ 'Radius': 'Radio',+ 'Ready for your workout? 💪': '¿Listo para entrenar? 💪',+ 'Remove this gym?': '¿Quitar este gimnasio?',+ 'Search': 'Buscar',+ 'Search an address': 'Buscar una dirección',+ 'Search an address or drag the pin': 'Busca una dirección o arrastra el pin',+ 'Searching…': 'Buscando…',+ 'Tap the map or drag the pin onto your gym.': 'Toca el mapa o arrastra el pin hasta tu gimnasio.',+ 'Tap the map to put the pin on your gym first.': 'Primero toca el mapa para poner el pin en tu gimnasio.',+ 'That’s 20 gyms, the most a phone can watch.': 'Son 20 gimnasios, lo máximo que un móvil puede vigilar.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'La búsqueda de direcciones consulta OpenStreetMap (Nominatim), y solo cuando tocas Buscar.',+ 'The address search didn’t answer. Try again in a moment.': 'La búsqueda de direcciones no respondió. Inténtalo de nuevo en un momento.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'El propio móvil vigila los gimnasios que añadiste y solo despierta a openGym cuando llegas. Nada de rastreo entre medias, y tus lugares nunca salen de este móvil.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'El recordatorio necesita la ubicación en segundo plano. Puedes permitirla en los ajustes del móvil.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Para notar que entraste en tu gimnasio con openGym cerrado, el móvil tiene que dejarle ver tu ubicación en segundo plano.',+ 'Until': 'Hasta',+ 'Use my location': 'Usar mi ubicación',+ 'Uses where your phone is': 'Usa la ubicación de tu móvil',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Entra en uno de tus gimnasios y openGym te da un toque para que pulses Empezar. Como mucho una vez al día, y nunca si ya entrenaste. Tus gimnasios se quedan en este móvil.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Sin ubicación en segundo plano, el móvil no puede detectar tu gimnasio con openGym cerrado.',+ 'Your gyms': 'Tus gimnasios',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'La ubicación precisa está desactivada para openGym. Actívala en los ajustes del móvil o no se podrá detectar tu gimnasio.',+ '{0} m around the pin': '{0} m alrededor del pin',+ 'Your gym': 'Tu gimnasio',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 314f49ae5..91d608303 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Cet appareil a 1 séance absente de cette sauvegarde. Remplacer la supprime.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Cet appareil a {0} séances absentes de cette sauvegarde. Remplacer les supprime.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Un petit rappel quand tu entres dans ta salle.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Environ 100 m conviennent à la plupart des salles. Plus grand si le téléphone te repère tard, plus petit s’il te relance déjà dans la rue devant.',+ 'Add a gym': 'Ajouter une salle',+ 'All the time': 'Toujours autoriser',+ 'Allow location “All the time”?': 'Autoriser la position « Toujours autoriser » ?',+ 'Allow location “Always”?': 'Autoriser la position « Toujours » ?',+ 'Always': 'Toujours',+ 'Couldn’t find where you are. Try the map instead.': 'Impossible de te localiser. Essaie plutôt la carte.',+ 'Finding you…': 'On te cherche…',+ 'From': 'De',+ 'Gym reminder': 'Rappel à 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.',+ 'Location access': 'Accès à la position',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym n’a pas accès à ta position. Tu peux changer ça dans les réglages du téléphone.',+ 'My gym': 'Ma salle',+ 'Name': 'Nom',+ 'No more nudges when you arrive here.': 'Plus de rappel quand tu arrives ici.',+ 'Not asked yet': 'Pas encore demandé',+ 'Nothing found. Try a street and a town.': 'Rien trouvé. Essaie une rue et une ville.',+ 'Notification text': 'Texte de la notification',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'Les notifications sont coupées pour openGym, le rappel n’a donc nulle part où s’afficher.',+ 'On the next screen, pick “Allow all the time”.': 'Sur l’écran suivant, choisis « Toujours autoriser ».',+ 'Only between certain hours': 'Seulement à certaines heures',+ 'Only while using the app': 'Seulement quand l’app est utilisée',+ 'Outside these hours the phone stays quiet, even at the gym.': 'En dehors de ces heures, le téléphone reste silencieux, même à la salle.',+ 'Pick it on the map': 'Choisir sur la carte',+ 'Radius': 'Rayon',+ 'Ready for your workout? 💪': 'Prêt pour ta séance ? 💪',+ 'Remove this gym?': 'Retirer cette salle ?',+ 'Search': 'Rechercher',+ 'Search an address': 'Rechercher une adresse',+ 'Search an address or drag the pin': 'Cherche une adresse ou déplace l’épingle',+ 'Searching…': 'Recherche…',+ 'Tap the map or drag the pin onto your gym.': 'Touche la carte ou déplace l’épingle sur ta salle.',+ 'Tap the map to put the pin on your gym first.': 'Touche d’abord la carte pour placer l’épingle sur ta salle.',+ 'That’s 20 gyms, the most a phone can watch.': 'Ça fait 20 salles, le maximum qu’un téléphone peut surveiller.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'La recherche d’adresse interroge OpenStreetMap (Nominatim), et seulement quand tu touches Rechercher.',+ 'The address search didn’t answer. Try again in a moment.': 'La recherche d’adresse n’a pas répondu. Réessaie dans un instant.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'Le téléphone surveille lui-même les salles que tu as ajoutées et ne réveille openGym qu’à ton arrivée. Aucun suivi entre-temps, et tes lieux ne quittent jamais ce téléphone.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'Le rappel a besoin de la position en arrière-plan. Tu peux l’autoriser dans les réglages du téléphone.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Pour remarquer que tu es entré dans ta salle quand openGym est fermé, le téléphone doit lui laisser voir ta position en arrière-plan.',+ 'Until': 'À',+ 'Use my location': 'Utiliser ma position',+ 'Uses where your phone is': 'Utilise la position de ton téléphone',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Entre dans une de tes salles et openGym te pousse à appuyer sur Démarrer. Une fois par jour au plus, et jamais si tu t’es déjà entraîné. Tes salles restent sur ce téléphone.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Sans la position en arrière-plan, le téléphone ne peut pas repérer ta salle quand openGym est fermé.',+ 'Your gyms': 'Tes salles',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'La position exacte est désactivée pour openGym. Active-la dans les réglages du téléphone, sinon ta salle ne peut pas être repérée.',+ '{0} m around the pin': '{0} m autour de l’épingle',+ 'Your gym': 'Ta salle',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 9890c6b8f..a43ad8b94 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'इस डिवाइस पर 1 वर्कआउट है जो इस बैकअप में नहीं है। बदलने से यह मिट जाएगा।','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'इस डिवाइस पर {0} वर्कआउट हैं जो इस बैकअप में नहीं हैं। बदलने से ये मिट जाएँगे।',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'जिम में घुसते ही एक छोटा सा इशारा।',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'ज़्यादातर जिम के लिए करीब 100 मी. ठीक है। फ़ोन देर से पहचाने तो बढ़ाएँ, बाहर सड़क पर ही टोक दे तो घटाएँ।',+ 'Add a gym': 'जिम जोड़ें',+ 'All the time': 'हर समय अनुमति दें',+ 'Allow location “All the time”?': 'लोकेशन को “हर समय अनुमति दें”?',+ 'Allow location “Always”?': 'लोकेशन को “हमेशा” अनुमति दें?',+ 'Always': 'हमेशा',+ 'Couldn’t find where you are. Try the map instead.': 'आपकी लोकेशन नहीं मिली। मैप आज़माएँ।',+ 'Finding you…': 'आपको ढूँढ रहे हैं…',+ 'From': 'से',+ 'Gym reminder': 'जिम रिमाइंडर',+ 'Gym spotted': 'जिम दिख गया',+ 'I’m at the gym right now': 'मैं अभी जिम में हूँ',+ 'Leave it empty for the default.': 'डिफ़ॉल्ट टेक्स्ट के लिए खाली छोड़ें।',+ 'Location access': 'लोकेशन एक्सेस',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym को लोकेशन की अनुमति नहीं है। इसे फ़ोन की सेटिंग्स में बदल सकते हैं।',+ 'My gym': 'मेरा जिम',+ 'Name': 'नाम',+ 'No more nudges when you arrive here.': 'यहाँ पहुँचने पर अब कोई इशारा नहीं।',+ 'Not asked yet': 'अभी पूछा नहीं गया',+ 'Nothing found. Try a street and a town.': 'कुछ नहीं मिला। कोई गली और शहर आज़माएँ।',+ 'Notification text': 'नोटिफ़िकेशन टेक्स्ट',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'openGym के नोटिफ़िकेशन बंद हैं, इसलिए रिमाइंडर कहीं दिख नहीं सकता।',+ 'On the next screen, pick “Allow all the time”.': 'अगली स्क्रीन पर “हर समय अनुमति दें” चुनें।',+ 'Only between certain hours': 'सिर्फ़ कुछ घंटों में',+ 'Only while using the app': 'सिर्फ़ ऐप इस्तेमाल करते समय',+ 'Outside these hours the phone stays quiet, even at the gym.': 'इन घंटों के बाहर फ़ोन चुप रहता है, जिम में भी।',+ 'Pick it on the map': 'मैप पर चुनें',+ 'Radius': 'दायरा',+ 'Ready for your workout? 💪': 'वर्कआउट के लिए तैयार? 💪',+ 'Remove this gym?': 'यह जिम हटाएँ?',+ 'Search': 'खोजें',+ 'Search an address': 'पता खोजें',+ 'Search an address or drag the pin': 'पता खोजें या पिन खींचें',+ 'Searching…': 'खोज रहे हैं…',+ 'Tap the map or drag the pin onto your gym.': 'मैप पर टैप करें या पिन को अपने जिम पर खींचें।',+ 'Tap the map to put the pin on your gym first.': 'पहले मैप पर टैप करके पिन को अपने जिम पर रखें।',+ 'That’s 20 gyms, the most a phone can watch.': 'यह 20 जिम हो गए, फ़ोन इससे ज़्यादा नहीं देख सकता।',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'पता खोज OpenStreetMap (Nominatim) से पूछती है, और सिर्फ़ तब जब आप खोजें पर टैप करें।',+ 'The address search didn’t answer. Try again in a moment.': 'पता खोज ने जवाब नहीं दिया। थोड़ी देर में फिर कोशिश करें।',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'आपके जोड़े गए जिम पर फ़ोन खुद नज़र रखता है और आपके पहुँचने पर ही openGym को जगाता है। बीच में कोई ट्रैकिंग नहीं, और आपकी जगहें कभी इस फ़ोन से बाहर नहीं जातीं।',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'रिमाइंडर को बैकग्राउंड में लोकेशन चाहिए। इसे फ़ोन की सेटिंग्स में अनुमति दे सकते हैं।',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'openGym बंद होने पर भी आपके जिम में घुसने का पता चले, इसके लिए फ़ोन को उसे बैकग्राउंड में आपकी लोकेशन देखने देनी होगी।',+ 'Until': 'तक',+ 'Use my location': 'मेरी लोकेशन इस्तेमाल करें',+ 'Uses where your phone is': 'फ़ोन की लोकेशन लेता है',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'अपने किसी जिम में घुसिए और openGym आपको स्टार्ट दबाने का इशारा करेगा। दिन में ज़्यादा से ज़्यादा एक बार, और अगर आप ट्रेनिंग कर चुके हैं तो कभी नहीं। आपके जिम इसी फ़ोन पर रहते हैं।',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'बैकग्राउंड लोकेशन के बिना openGym बंद होने पर फ़ोन आपका जिम नहीं पहचान सकता।',+ 'Your gyms': 'आपके जिम',+ '{0} m': '{0} मी.',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'openGym के लिए सटीक लोकेशन बंद है। इसे फ़ोन की सेटिंग्स में चालू करें, वरना आपका जिम पहचाना नहीं जा सकता।',+ '{0} m around the pin': 'पिन के आसपास {0} मी.',+ 'Your gym': 'आपका जिम',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 0b91e9e3c..06c811914 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -2417,4 +2417,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Ezen az eszközön 1 edzés van, amely nincs ebben a mentésben. A csere törli.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Ezen az eszközön {0} edzés van, amely nincs ebben a mentésben. A csere törli őket.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Egy kis bökés, amikor belépsz az edzőterembe.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'A legtöbb teremhez kb. 100 m elég. Nagyobb, ha a telefon későn vesz észre, kisebb, ha már az utcán bökdös a bejárat előtt.',+ 'Add a gym': 'Terem hozzáadása',+ 'All the time': 'Engedélyezés mindig',+ 'Allow location “All the time”?': 'Engedélyezed a helyadatokat „Mindig”?',+ 'Allow location “Always”?': 'Engedélyezed a helyadatokat „Mindig” módban?',+ 'Always': 'Mindig',+ 'Couldn’t find where you are. Try the map instead.': 'Nem találunk. Próbáld a térképpel.',+ 'Finding you…': 'Keresünk…',+ 'From': 'Ettől',+ 'Gym reminder': 'Edzőterem-emlékeztető',+ '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.',+ 'Location access': 'Helyhozzáférés',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'Az openGym nem fér hozzá a helyadatokhoz. Ezt a telefon beállításaiban módosíthatod.',+ 'My gym': 'Az én termem',+ 'Name': 'Név',+ 'No more nudges when you arrive here.': 'Itt már nem bökünk meg, amikor megérkezel.',+ 'Not asked yet': 'Még nem kérdeztük',+ 'Nothing found. Try a street and a town.': 'Nincs találat. Próbáld utcával és várossal.',+ 'Notification text': 'Értesítés szövege',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'Az openGym értesítései ki vannak kapcsolva, így az emlékeztető sehol sem jelenhet meg.',+ 'On the next screen, pick “Allow all the time”.': 'A következő képernyőn válaszd az „Engedélyezés mindig” lehetőséget.',+ 'Only between certain hours': 'Csak bizonyos órákban',+ 'Only while using the app': 'Csak az alkalmazás használata közben',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Ezen órákon kívül a telefon csendben marad, a teremben is.',+ 'Pick it on the map': 'Választás a térképen',+ 'Radius': 'Sugár',+ 'Ready for your workout? 💪': 'Indulhat az edzés? 💪',+ 'Remove this gym?': 'Eltávolítod ezt a termet?',+ 'Search': 'Keresés',+ 'Search an address': 'Cím keresése',+ 'Search an address or drag the pin': 'Keress címet, vagy húzd a tűt',+ 'Searching…': 'Keresés…',+ 'Tap the map or drag the pin onto your gym.': 'Koppints a térképre, vagy húzd a tűt a termedre.',+ 'Tap the map to put the pin on your gym first.': 'Előbb koppints a térképre, hogy a tű a termeden legyen.',+ 'That’s 20 gyms, the most a phone can watch.': 'Ez 20 terem, ennél többet a telefon nem tud figyelni.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'A címkeresés az OpenStreetMapet (Nominatim) kérdezi, és csak akkor, ha a Keresésre koppintasz.',+ 'The address search didn’t answer. Try again in a moment.': 'A címkeresés nem válaszolt. Próbáld újra egy kicsit később.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'A hozzáadott termeket maga a telefon figyeli, és csak érkezéskor ébreszti fel az openGymet. Közben nincs követés, és a helyeid sosem hagyják el ezt a telefont.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'Az emlékeztetőhöz háttérben is kell a helyadat. Ezt a telefon beállításaiban engedélyezheted.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Ahhoz, hogy észrevegye, hogy beléptél a terembe, miközben az openGym zárva van, a telefonnak engednie kell, hogy a háttérben is lássa a helyedet.',+ 'Until': 'Eddig',+ 'Use my location': 'Saját hely használata',+ 'Uses where your phone is': 'A telefon helyét használja',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Lépj be valamelyik termedbe, és az openGym megbök, hogy nyomd meg a Startot. Legfeljebb naponta egyszer, és soha, ha már edzettél. A termeid ezen a telefonon maradnak.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Háttérbeli helyadat nélkül a telefon nem ismeri fel a termet, amíg az openGym zárva van.',+ 'Your gyms': 'A termeid',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'A pontos hely ki van kapcsolva az openGymnél. Kapcsold be a telefon beállításaiban, különben a termed nem ismerhető fel.',+ '{0} m around the pin': '{0} m a tű körül',+ 'Your gym': 'A termed',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 2a694f890..c32dbe3b7 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Su questo dispositivo c’è 1 allenamento che non è in questo backup. Sostituire lo elimina.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Su questo dispositivo ci sono {0} allenamenti che non sono in questo backup. Sostituire li elimina.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Una spintarella quando entri in palestra.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Circa 100 m vanno bene per quasi tutte le palestre. Di più se il telefono ti nota tardi, di meno se ti avvisa già sulla strada davanti.',+ 'Add a gym': 'Aggiungi una palestra',+ 'All the time': 'Consenti sempre',+ 'Allow location “All the time”?': 'Consentire la posizione «Consenti sempre»?',+ 'Allow location “Always”?': 'Consentire la posizione «Sempre»?',+ 'Always': 'Sempre',+ 'Couldn’t find where you are. Try the map instead.': 'Non riusciamo a trovarti. Prova con la mappa.',+ 'Finding you…': 'Ti cerchiamo…',+ 'From': 'Dalle',+ 'Gym reminder': 'Promemoria 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.',+ 'Location access': 'Accesso alla posizione',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym non ha accesso alla posizione. Puoi cambiarlo nelle impostazioni del telefono.',+ 'My gym': 'La mia palestra',+ 'Name': 'Nome',+ 'No more nudges when you arrive here.': 'Niente più promemoria quando arrivi qui.',+ 'Not asked yet': 'Non ancora chiesto',+ 'Nothing found. Try a street and a town.': 'Nessun risultato. Prova con via e città.',+ 'Notification text': 'Testo della notifica',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'Le notifiche di openGym sono spente, quindi il promemoria non ha dove comparire.',+ 'On the next screen, pick “Allow all the time”.': 'Nella schermata successiva scegli «Consenti sempre».',+ 'Only between certain hours': 'Solo in certi orari',+ 'Only while using the app': 'Solo mentre usi l’app',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Fuori da questi orari il telefono resta zitto, anche in palestra.',+ 'Pick it on the map': 'Scegli sulla mappa',+ 'Radius': 'Raggio',+ 'Ready for your workout? 💪': 'Pronto per l’allenamento? 💪',+ 'Remove this gym?': 'Rimuovere questa palestra?',+ 'Search': 'Cerca',+ 'Search an address': 'Cerca un indirizzo',+ 'Search an address or drag the pin': 'Cerca un indirizzo o trascina il segnaposto',+ 'Searching…': 'Ricerca…',+ 'Tap the map or drag the pin onto your gym.': 'Tocca la mappa o trascina il segnaposto sulla tua palestra.',+ 'Tap the map to put the pin on your gym first.': 'Prima tocca la mappa per mettere il segnaposto sulla tua palestra.',+ 'That’s 20 gyms, the most a phone can watch.': 'Sono 20 palestre, il massimo che un telefono può tenere d’occhio.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'La ricerca indirizzi chiede a OpenStreetMap (Nominatim), e solo quando tocchi Cerca.',+ 'The address search didn’t answer. Try again in a moment.': 'La ricerca indirizzi non ha risposto. Riprova tra un attimo.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'È il telefono stesso a tenere d’occhio le palestre che hai aggiunto e sveglia openGym solo quando arrivi. Nessun tracciamento nel mezzo, e i tuoi luoghi non lasciano mai questo telefono.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'Il promemoria ha bisogno della posizione in background. Puoi consentirla nelle impostazioni del telefono.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Per accorgersi che sei entrato in palestra mentre openGym è chiuso, il telefono deve lasciargli vedere la tua posizione in background.',+ 'Until': 'Alle',+ 'Use my location': 'Usa la mia posizione',+ 'Uses where your phone is': 'Usa la posizione del telefono',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Entra in una delle tue palestre e openGym ti spinge a premere Inizia. Al massimo una volta al giorno, e mai se ti sei già allenato. Le tue palestre restano su questo telefono.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Senza posizione in background il telefono non può riconoscere la palestra mentre openGym è chiuso.',+ 'Your gyms': 'Le tue palestre',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'La posizione esatta è disattivata per openGym. Attivala nelle impostazioni del telefono, altrimenti la palestra non può essere riconosciuta.',+ '{0} m around the pin': '{0} m attorno al segnaposto',+ 'Your gym': 'La tua palestra',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex d1d796aec..8befb3cc2 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': '이 기기에 이 백업에 없는 운동이 1개 있습니다. 바꾸면 삭제됩니다.','This device has {0} workouts that are not in this backup. Replacing deletes them.': '이 기기에 이 백업에 없는 운동이 {0}개 있습니다. 바꾸면 삭제됩니다.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': '헬스장에 들어서면 살짝 알려줘요.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': '대부분의 헬스장은 100m 정도면 충분해요. 휴대폰이 늦게 알아채면 넓히고, 앞 길거리에서 벌써 알리면 좁혀요.',+ 'Add a gym': '헬스장 추가',+ 'All the time': '항상 허용',+ 'Allow location “All the time”?': '위치를 ‘항상 허용’할까요?',+ 'Allow location “Always”?': '위치를 ‘항상’ 허용할까요?',+ 'Always': '항상',+ 'Couldn’t find where you are. Try the map instead.': '위치를 찾지 못했어요. 지도로 해 보세요.',+ 'Finding you…': '위치 찾는 중…',+ 'From': '시작',+ 'Gym reminder': '헬스장 알림',+ 'Gym spotted': '헬스장 발견',+ 'I’m at the gym right now': '지금 헬스장에 있어요',+ 'Leave it empty for the default.': '비워 두면 기본 문구를 써요.',+ 'Location access': '위치 접근',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym에 위치 권한이 없어요. 휴대폰 설정에서 바꿀 수 있어요.',+ 'My gym': '내 헬스장',+ 'Name': '이름',+ 'No more nudges when you arrive here.': '여기 도착해도 더 이상 알리지 않아요.',+ 'Not asked yet': '아직 묻지 않음',+ 'Nothing found. Try a street and a town.': '결과가 없어요. 도로명과 도시로 검색해 보세요.',+ 'Notification text': '알림 문구',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'openGym 알림이 꺼져 있어서 알림이 뜰 곳이 없어요.',+ 'On the next screen, pick “Allow all the time”.': '다음 화면에서 ‘항상 허용’을 고르세요.',+ 'Only between certain hours': '특정 시간에만',+ 'Only while using the app': '앱 사용 중에만',+ 'Outside these hours the phone stays quiet, even at the gym.': '이 시간 밖에는 헬스장에 있어도 조용히 있어요.',+ 'Pick it on the map': '지도에서 고르기',+ 'Radius': '반경',+ 'Ready for your workout? 💪': '운동할 준비 됐나요? 💪',+ 'Remove this gym?': '이 헬스장을 삭제할까요?',+ 'Search': '검색',+ 'Search an address': '주소 검색',+ 'Search an address or drag the pin': '주소를 검색하거나 핀을 끌어 놓으세요',+ 'Searching…': '검색 중…',+ 'Tap the map or drag the pin onto your gym.': '지도를 탭하거나 핀을 헬스장 위로 끌어 놓으세요.',+ 'Tap the map to put the pin on your gym first.': '먼저 지도를 탭해 헬스장에 핀을 꽂으세요.',+ 'That’s 20 gyms, the most a phone can watch.': '헬스장 20곳, 휴대폰이 지켜볼 수 있는 최대치예요.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': '주소 검색은 OpenStreetMap(Nominatim)에 물어보고, 검색을 탭할 때만 해요.',+ 'The address search didn’t answer. Try again in a moment.': '주소 검색이 응답하지 않았어요. 잠시 후 다시 해 보세요.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': '추가한 헬스장은 휴대폰이 직접 지켜보고, 도착했을 때만 openGym을 깨워요. 그 사이 추적은 없고, 위치는 이 휴대폰 밖으로 나가지 않아요.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': '알림에는 백그라운드 위치 권한이 필요해요. 휴대폰 설정에서 허용할 수 있어요.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'openGym이 닫혀 있을 때 헬스장에 들어온 걸 알아채려면, 휴대폰이 백그라운드에서 위치를 볼 수 있게 해 줘야 해요.',+ 'Until': '종료',+ 'Use my location': '내 위치 사용',+ 'Uses where your phone is': '휴대폰의 현재 위치를 써요',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': '헬스장에 들어서면 openGym이 시작을 누르라고 살짝 알려줘요. 하루 한 번까지, 이미 운동했다면 알리지 않아요. 헬스장 정보는 이 휴대폰에만 있어요.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': '백그라운드 위치가 없으면 openGym이 닫혀 있을 때 헬스장을 알아챌 수 없어요.',+ 'Your gyms': '내 헬스장 목록',+ '{0} m': '{0}m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'openGym의 정확한 위치가 꺼져 있어요. 휴대폰 설정에서 켜야 헬스장을 알아챌 수 있어요.',+ '{0} m around the pin': '핀 주변 {0}m',+ 'Your gym': '내 헬스장',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 2188107d2..99a8d5e00 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Na tym urządzeniu jest 1 trening, którego nie ma w tej kopii. Zastąpienie danych go usunie.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Na tym urządzeniu są treningi, których nie ma w tej kopii ({0}). Zastąpienie danych je usunie.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Szturchnięcie, gdy wchodzisz na siłownię.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Około 100 m pasuje do większości siłowni. Więcej, jeśli telefon zauważa cię późno, mniej, jeśli zaczepia cię już na ulicy przed wejściem.',+ 'Add a gym': 'Dodaj siłownię',+ 'All the time': 'Zezwalaj zawsze',+ 'Allow location “All the time”?': 'Zezwolić na lokalizację „Zezwalaj zawsze”?',+ 'Allow location “Always”?': 'Zezwolić na lokalizację „Zawsze”?',+ 'Always': 'Zawsze',+ 'Couldn’t find where you are. Try the map instead.': 'Nie możemy cię znaleźć. Spróbuj mapy.',+ 'Finding you…': 'Szukamy cię…',+ 'From': 'Od',+ 'Gym reminder': 'Przypomnienie 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.',+ 'Location access': 'Dostęp do lokalizacji',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym nie ma dostępu do lokalizacji. Możesz to zmienić w ustawieniach telefonu.',+ 'My gym': 'Moja siłownia',+ 'Name': 'Nazwa',+ 'No more nudges when you arrive here.': 'Koniec szturchnięć, gdy tu przychodzisz.',+ 'Not asked yet': 'Jeszcze nie pytano',+ 'Nothing found. Try a street and a town.': 'Nic nie znaleziono. Spróbuj ulicy i miasta.',+ 'Notification text': 'Tekst powiadomienia',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'Powiadomienia openGym są wyłączone, więc przypomnienie nie ma gdzie się pokazać.',+ 'On the next screen, pick “Allow all the time”.': 'Na następnym ekranie wybierz „Zezwalaj zawsze”.',+ 'Only between certain hours': 'Tylko w określonych godzinach',+ 'Only while using the app': 'Tylko podczas używania aplikacji',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Poza tymi godzinami telefon milczy, nawet na siłowni.',+ 'Pick it on the map': 'Wybierz na mapie',+ 'Radius': 'Promień',+ 'Ready for your workout? 💪': 'Gotowy na trening? 💪',+ 'Remove this gym?': 'Usunąć tę siłownię?',+ 'Search': 'Szukaj',+ 'Search an address': 'Szukaj adresu',+ 'Search an address or drag the pin': 'Wyszukaj adres albo przeciągnij pinezkę',+ 'Searching…': 'Szukam…',+ 'Tap the map or drag the pin onto your gym.': 'Stuknij mapę albo przeciągnij pinezkę na swoją siłownię.',+ 'Tap the map to put the pin on your gym first.': 'Najpierw stuknij mapę, żeby postawić pinezkę na siłowni.',+ 'That’s 20 gyms, the most a phone can watch.': 'To już 20 siłowni, więcej telefon nie upilnuje.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'Wyszukiwanie adresu pyta OpenStreetMap (Nominatim) i tylko wtedy, gdy stukniesz Szukaj.',+ 'The address search didn’t answer. Try again in a moment.': 'Wyszukiwanie adresu nie odpowiedziało. Spróbuj za chwilę.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'Telefon sam pilnuje dodanych siłowni i budzi openGym dopiero, gdy dotrzesz. Żadnego śledzenia pomiędzy, a twoje miejsca nigdy nie opuszczają tego telefonu.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'Przypomnienie potrzebuje lokalizacji w tle. Możesz na nią zezwolić w ustawieniach telefonu.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Żeby zauważyć, że wszedłeś na siłownię, gdy openGym jest zamknięty, telefon musi pozwolić mu widzieć twoją lokalizację w tle.',+ 'Until': 'Do',+ 'Use my location': 'Użyj mojej lokalizacji',+ 'Uses where your phone is': 'Używa lokalizacji telefonu',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Wejdź na jedną ze swoich siłowni, a openGym szturchnie cię, żebyś nacisnął Start. Najwyżej raz dziennie i nigdy, gdy już trenowałeś. Twoje siłownie zostają na tym telefonie.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Bez lokalizacji w tle telefon nie rozpozna siłowni, gdy openGym jest zamknięty.',+ 'Your gyms': 'Twoje siłownie',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'Dokładna lokalizacja jest wyłączona dla openGym. Włącz ją w ustawieniach telefonu, inaczej siłownia nie zostanie rozpoznana.',+ '{0} m around the pin': '{0} m wokół pinezki',+ 'Your gym': 'Twoja siłownia',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 8722ba9e7..13455ebef 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1535,6 +1535,60 @@ export const PT_BR_OVERRIDES = {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tem 1 treino que não está neste backup. Substituir exclui esse treino.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tem {0} treinos que não estão neste backup. Substituir exclui esses treinos.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Um toque quando você entra na sua academia.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Uns 100 m servem para a maioria das academias. Maior se o celular perceber você tarde, menor se ele avisar já na rua em frente.',+ 'Add a gym': 'Adicionar uma academia',+ 'All the time': 'Permitir o tempo todo',+ 'Allow location “All the time”?': 'Permitir a localização “Permitir o tempo todo”?',+ 'Allow location “Always”?': 'Permitir a localização “Sempre”?',+ 'Always': 'Sempre',+ 'Couldn’t find where you are. Try the map instead.': 'Não conseguimos achar você. Tente o mapa.',+ 'Finding you…': 'Procurando você…',+ 'From': 'Das',+ 'Gym reminder': 'Lembrete da 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.',+ 'Location access': 'Acesso à localização',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'O openGym não tem acesso à localização. Você pode mudar isso nas configurações do celular.',+ 'My gym': 'Minha academia',+ 'Name': 'Nome',+ 'No more nudges when you arrive here.': 'Você não recebe mais o toque quando chegar aqui.',+ 'Not asked yet': 'Ainda não pedido',+ 'Nothing found. Try a street and a town.': 'Nada encontrado. Tente uma rua e uma cidade.',+ 'Notification text': 'Texto da notificação',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'As notificações do openGym estão desligadas, então o lembrete não tem onde aparecer.',+ 'On the next screen, pick “Allow all the time”.': 'Na próxima tela, escolha “Permitir o tempo todo”.',+ 'Only between certain hours': 'Só em certos horários',+ 'Only while using the app': 'Só durante o uso do aplicativo',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Fora desses horários o celular fica quieto, mesmo na academia.',+ 'Pick it on the map': 'Escolher no mapa',+ 'Radius': 'Raio',+ 'Ready for your workout? 💪': 'Pronto para treinar? 💪',+ 'Remove this gym?': 'Remover esta academia?',+ 'Search': 'Pesquisar',+ 'Search an address': 'Pesquisar um endereço',+ 'Search an address or drag the pin': 'Pesquise um endereço ou arraste o alfinete',+ 'Searching…': 'Pesquisando…',+ 'Tap the map or drag the pin onto your gym.': 'Toque no mapa ou arraste o alfinete até a sua academia.',+ 'Tap the map to put the pin on your gym first.': 'Primeiro toque no mapa para colocar o alfinete na sua academia.',+ 'That’s 20 gyms, the most a phone can watch.': 'São 20 academias, o máximo que um celular consegue vigiar.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'A pesquisa de endereços consulta o OpenStreetMap (Nominatim), e só quando você toca em Pesquisar.',+ 'The address search didn’t answer. Try again in a moment.': 'A pesquisa de endereços não respondeu. Tente de novo daqui a pouco.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'O próprio celular vigia as academias que você adicionou e só acorda o openGym quando você chega. Nada de rastreamento no meio, e seus locais nunca saem deste celular.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'O lembrete precisa da localização em segundo plano. Você pode permitir isso nas configurações do celular.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Para perceber que você entrou na academia com o openGym fechado, o celular precisa deixar ele ver sua localização em segundo plano.',+ 'Until': 'Até',+ 'Use my location': 'Usar minha localização',+ 'Uses where your phone is': 'Usa a localização do celular',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Entre em uma das suas academias e o openGym dá um toque para você apertar Começar. No máximo uma vez por dia, e nunca se você já treinou. Suas academias ficam neste celular.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Sem localização em segundo plano, o celular não consegue detectar a academia com o openGym fechado.',+ 'Your gyms': 'Suas academias',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'A localização precisa está desligada para o openGym. Ative nas configurações do celular, senão a academia não pode ser detectada.',+ '{0} m around the pin': '{0} m em volta do alfinete',+ 'Your gym': 'Sua academia',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex ed106827d..95ff3b0d6 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tem 1 treino que não está nesta cópia. Substituir elimina-o.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tem {0} treinos que não estão nesta cópia. Substituir elimina-os.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Um toque quando entras no teu ginásio.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Cerca de 100 m serve para a maioria dos ginásios. Maior se o telemóvel te deteta tarde, menor se te avisa já na rua em frente.',+ 'Add a gym': 'Adicionar um ginásio',+ 'All the time': 'Permitir sempre',+ 'Allow location “All the time”?': 'Permitir a localização “Permitir sempre”?',+ 'Allow location “Always”?': 'Permitir a localização “Sempre”?',+ 'Always': 'Sempre',+ 'Couldn’t find where you are. Try the map instead.': 'Não conseguimos encontrar-te. Experimenta o mapa.',+ 'Finding you…': 'À tua procura…',+ 'From': 'Das',+ 'Gym reminder': 'Lembrete do 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.',+ 'Location access': 'Acesso à localização',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'O openGym não tem acesso à localização. Podes mudar isso nas definições do telemóvel.',+ 'My gym': 'O meu ginásio',+ 'Name': 'Nome',+ 'No more nudges when you arrive here.': 'Deixas de receber o toque quando chegas aqui.',+ 'Not asked yet': 'Ainda não pedido',+ 'Nothing found. Try a street and a town.': 'Nada encontrado. Experimenta uma rua e uma cidade.',+ 'Notification text': 'Texto da notificação',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'As notificações do openGym estão desligadas, por isso o lembrete não tem onde aparecer.',+ 'On the next screen, pick “Allow all the time”.': 'No ecrã seguinte, escolhe “Permitir sempre”.',+ 'Only between certain hours': 'Só a certas horas',+ 'Only while using the app': 'Só durante a utilização da app',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Fora destas horas o telemóvel fica calado, mesmo no ginásio.',+ 'Pick it on the map': 'Escolher no mapa',+ 'Radius': 'Raio',+ 'Ready for your workout? 💪': 'Pronto para treinar? 💪',+ 'Remove this gym?': 'Remover este ginásio?',+ 'Search': 'Pesquisar',+ 'Search an address': 'Pesquisar uma morada',+ 'Search an address or drag the pin': 'Pesquisa uma morada ou arrasta o alfinete',+ 'Searching…': 'A pesquisar…',+ 'Tap the map or drag the pin onto your gym.': 'Toca no mapa ou arrasta o alfinete para o teu ginásio.',+ 'Tap the map to put the pin on your gym first.': 'Primeiro toca no mapa para pôr o alfinete no teu ginásio.',+ 'That’s 20 gyms, the most a phone can watch.': 'São 20 ginásios, o máximo que um telemóvel consegue vigiar.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'A pesquisa de moradas pergunta ao OpenStreetMap (Nominatim), e só quando tocas em Pesquisar.',+ 'The address search didn’t answer. Try again in a moment.': 'A pesquisa de moradas não respondeu. Tenta de novo daqui a pouco.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'É o próprio telemóvel que vigia os ginásios que adicionaste e só acorda o openGym quando chegas. Nada de rastreio pelo meio, e os teus locais nunca saem deste telemóvel.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'O lembrete precisa da localização em segundo plano. Podes permiti-la nas definições do telemóvel.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Para perceber que entraste no ginásio com o openGym fechado, o telemóvel tem de o deixar ver a tua localização em segundo plano.',+ 'Until': 'Até',+ 'Use my location': 'Usar a minha localização',+ 'Uses where your phone is': 'Usa a localização do telemóvel',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Entra num dos teus ginásios e o openGym dá-te um toque para carregares em Começar. No máximo uma vez por dia, e nunca se já treinaste. Os teus ginásios ficam neste telemóvel.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Sem localização em segundo plano, o telemóvel não consegue detetar o ginásio com o openGym fechado.',+ 'Your gyms': 'Os teus ginásios',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'A localização exata está desligada para o openGym. Liga-a nas definições do telemóvel, senão o ginásio não pode ser detetado.',+ '{0} m around the pin': '{0} m à volta do alfinete',+ 'Your gym': 'O teu ginásio',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex c3bfc0ddb..b5b2dd979 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -2418,4 +2418,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'На этом устройстве есть 1 тренировка, которой нет в этой копии. Замена её удалит.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'На этом устройстве есть тренировки, которых нет в этой копии ({0}). Замена их удалит.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Напоминание, когда ты заходишь в зал.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Около 100 м подходит большинству залов. Больше, если телефон замечает тебя поздно, меньше, если он дёргает тебя ещё на улице перед входом.',+ 'Add a gym': 'Добавить зал',+ 'All the time': 'Разрешить в любом режиме',+ 'Allow location “All the time”?': 'Разрешить геолокацию «В любом режиме»?',+ 'Allow location “Always”?': 'Разрешить геолокацию «Всегда»?',+ 'Always': 'Всегда',+ 'Couldn’t find where you are. Try the map instead.': 'Не получилось тебя найти. Попробуй карту.',+ 'Finding you…': 'Ищем тебя…',+ 'From': 'С',+ 'Gym reminder': 'Напоминание в зале',+ 'Gym spotted': 'Зал замечен',+ 'I’m at the gym right now': 'Я сейчас в зале',+ 'Leave it empty for the default.': 'Оставь пустым для текста по умолчанию.',+ 'Location access': 'Доступ к геолокации',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'У openGym нет доступа к геолокации. Это можно изменить в настройках телефона.',+ 'My gym': 'Мой зал',+ 'Name': 'Название',+ 'No more nudges when you arrive here.': 'Больше никаких напоминаний, когда ты приходишь сюда.',+ 'Not asked yet': 'Ещё не спрашивали',+ 'Nothing found. Try a street and a town.': 'Ничего не найдено. Попробуй улицу и город.',+ 'Notification text': 'Текст уведомления',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'Уведомления openGym выключены, так что напоминанию негде появиться.',+ 'On the next screen, pick “Allow all the time”.': 'На следующем экране выбери «Разрешить в любом режиме».',+ 'Only between certain hours': 'Только в определённые часы',+ 'Only while using the app': 'Только при использовании приложения',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Вне этих часов телефон молчит, даже в зале.',+ 'Pick it on the map': 'Выбрать на карте',+ 'Radius': 'Радиус',+ 'Ready for your workout? 💪': 'Готов к тренировке? 💪',+ 'Remove this gym?': 'Убрать этот зал?',+ 'Search': 'Найти',+ 'Search an address': 'Найти адрес',+ 'Search an address or drag the pin': 'Найди адрес или перетащи метку',+ 'Searching…': 'Ищем…',+ 'Tap the map or drag the pin onto your gym.': 'Нажми на карту или перетащи метку на свой зал.',+ 'Tap the map to put the pin on your gym first.': 'Сначала нажми на карту, чтобы поставить метку на зал.',+ 'That’s 20 gyms, the most a phone can watch.': 'Это 20 залов, больше телефон отслеживать не может.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'Поиск адреса спрашивает OpenStreetMap (Nominatim), и только когда ты нажимаешь «Найти».',+ 'The address search didn’t answer. Try again in a moment.': 'Поиск адреса не ответил. Попробуй ещё раз чуть позже.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'Телефон сам следит за добавленными залами и будит openGym, только когда ты приходишь. Никакой слежки в промежутке, а твои места никогда не покидают этот телефон.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'Напоминанию нужна геолокация в фоне. Её можно разрешить в настройках телефона.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Чтобы заметить, что ты зашёл в зал, когда openGym закрыт, телефон должен позволить ему видеть твою геолокацию в фоне.',+ 'Until': 'До',+ 'Use my location': 'Моё местоположение',+ 'Uses where your phone is': 'Берёт местоположение телефона',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Заходишь в один из своих залов, и openGym подталкивает нажать «Старт». Не чаще раза в день и никогда, если ты уже тренировался. Твои залы остаются на этом телефоне.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Без геолокации в фоне телефон не узнает зал, пока openGym закрыт.',+ 'Your gyms': 'Твои залы',+ '{0} m': '{0} м',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'Точная геопозиция для openGym выключена. Включи её в настройках телефона, иначе зал не получится распознать.',+ '{0} m around the pin': '{0} м вокруг метки',+ 'Your gym': 'Твой зал',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex b75bf9b03..7ac57b291 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -2425,4 +2425,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'อุปกรณ์นี้มีการออกกำลังกาย 1 รายการที่ไม่อยู่ในข้อมูลสำรองนี้ การแทนที่จะลบรายการนั้น','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'อุปกรณ์นี้มีการออกกำลังกาย {0} รายการที่ไม่อยู่ในข้อมูลสำรองนี้ การแทนที่จะลบรายการเหล่านั้น',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'สะกิดเบาๆ ตอนคุณเดินเข้ายิม',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'ประมาณ 100 ม. ใช้ได้กับยิมส่วนใหญ่ ขยายถ้ามือถือรู้ตัวช้า ลดลงถ้ามันเตือนตั้งแต่อยู่บนถนนหน้ายิม',+ 'Add a gym': 'เพิ่มยิม',+ 'All the time': 'อนุญาตตลอดเวลา',+ 'Allow location “All the time”?': 'อนุญาตตำแหน่ง “อนุญาตตลอดเวลา” ไหม',+ 'Allow location “Always”?': 'อนุญาตตำแหน่ง “ตลอด” ไหม',+ 'Always': 'ตลอด',+ 'Couldn’t find where you are. Try the map instead.': 'หาตำแหน่งคุณไม่เจอ ลองใช้แผนที่แทน',+ 'Finding you…': 'กำลังหาคุณ…',+ 'From': 'ตั้งแต่',+ 'Gym reminder': 'เตือนเมื่อถึงยิม',+ 'Gym spotted': 'เจอยิมแล้ว',+ 'I’m at the gym right now': 'ตอนนี้ฉันอยู่ที่ยิม',+ 'Leave it empty for the default.': 'เว้นว่างไว้เพื่อใช้ข้อความเริ่มต้น',+ 'Location access': 'การเข้าถึงตำแหน่ง',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym ไม่ได้รับอนุญาตให้ใช้ตำแหน่ง เปลี่ยนได้ในการตั้งค่าของมือถือ',+ 'My gym': 'ยิมของฉัน',+ 'Name': 'ชื่อ',+ 'No more nudges when you arrive here.': 'จะไม่มีการสะกิดอีกเมื่อคุณมาถึงที่นี่',+ 'Not asked yet': 'ยังไม่ได้ถาม',+ 'Nothing found. Try a street and a town.': 'ไม่พบอะไรเลย ลองใส่ถนนและเมือง',+ 'Notification text': 'ข้อความแจ้งเตือน',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'การแจ้งเตือนของ openGym ปิดอยู่ การเตือนจึงไม่มีที่ให้แสดง',+ 'On the next screen, pick “Allow all the time”.': 'ในหน้าถัดไป เลือก “อนุญาตตลอดเวลา”',+ 'Only between certain hours': 'เฉพาะบางช่วงเวลา',+ 'Only while using the app': 'เฉพาะขณะใช้แอป',+ 'Outside these hours the phone stays quiet, even at the gym.': 'นอกช่วงเวลานี้มือถือจะเงียบ แม้อยู่ที่ยิม',+ 'Pick it on the map': 'เลือกบนแผนที่',+ 'Radius': 'รัศมี',+ 'Ready for your workout? 💪': 'พร้อมออกกำลังหรือยัง 💪',+ 'Remove this gym?': 'ลบยิมนี้ไหม',+ 'Search': 'ค้นหา',+ 'Search an address': 'ค้นหาที่อยู่',+ 'Search an address or drag the pin': 'ค้นหาที่อยู่หรือลากหมุด',+ 'Searching…': 'กำลังค้นหา…',+ 'Tap the map or drag the pin onto your gym.': 'แตะแผนที่หรือลากหมุดไปที่ยิมของคุณ',+ 'Tap the map to put the pin on your gym first.': 'แตะแผนที่ก่อนเพื่อวางหมุดบนยิมของคุณ',+ 'That’s 20 gyms, the most a phone can watch.': 'ครบ 20 ยิมแล้ว มือถือเฝ้าได้มากสุดเท่านี้',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'การค้นหาที่อยู่จะถาม OpenStreetMap (Nominatim) และเฉพาะตอนที่คุณแตะค้นหา',+ 'The address search didn’t answer. Try again in a moment.': 'การค้นหาที่อยู่ไม่ตอบกลับ ลองใหม่อีกสักครู่',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'มือถือเฝ้ายิมที่คุณเพิ่มไว้เอง และปลุก openGym เฉพาะตอนคุณมาถึง ไม่มีการติดตามระหว่างนั้น และสถานที่ของคุณไม่เคยออกจากมือถือเครื่องนี้',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'การเตือนต้องใช้ตำแหน่งเบื้องหลัง อนุญาตได้ในการตั้งค่าของมือถือ',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'เพื่อให้รู้ว่าคุณเดินเข้ายิมขณะที่ openGym ปิดอยู่ มือถือต้องให้มันเห็นตำแหน่งของคุณในเบื้องหลัง',+ 'Until': 'ถึง',+ 'Use my location': 'ใช้ตำแหน่งของฉัน',+ 'Uses where your phone is': 'ใช้ตำแหน่งของมือถือ',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'เดินเข้ายิมของคุณแล้ว openGym จะสะกิดให้กดเริ่ม วันละครั้งเป็นอย่างมาก และไม่เตือนถ้าคุณออกกำลังไปแล้ว ยิมของคุณอยู่บนมือถือเครื่องนี้เท่านั้น',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'ถ้าไม่มีตำแหน่งเบื้องหลัง มือถือจะจำยิมของคุณไม่ได้ขณะที่ openGym ปิดอยู่',+ 'Your gyms': 'ยิมของคุณ',+ '{0} m': '{0} ม.',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'ตำแหน่งที่แม่นยำของ openGym ปิดอยู่ เปิดได้ในการตั้งค่าของมือถือ ไม่อย่างนั้นจะจำยิมของคุณไม่ได้',+ '{0} m around the pin': '{0} ม. รอบหมุด',+ 'Your gym': 'ยิมของคุณ',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex dad1e4041..73c1446d9 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Bu cihazda bu yedekte olmayan 1 antrenman var. Değiştirmek onu siler.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Bu cihazda bu yedekte olmayan {0} antrenman var. Değiştirmek onları siler.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Spor salonuna girdiğinde küçük bir dürtme.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Çoğu salon için yaklaşık 100 m yeterli. Telefon seni geç fark ediyorsa büyüt, daha önündeki sokakta dürtüyorsa küçült.',+ 'Add a gym': 'Salon ekle',+ 'All the time': 'Her zaman izin ver',+ 'Allow location “All the time”?': 'Konuma “Her zaman izin ver” denilsin mi?',+ 'Allow location “Always”?': 'Konuma “Her Zaman” izin verilsin mi?',+ 'Always': 'Her Zaman',+ 'Couldn’t find where you are. Try the map instead.': 'Seni bulamadık. Haritayı dene.',+ 'Finding you…': 'Seni arıyoruz…',+ 'From': 'Başlangıç',+ 'Gym reminder': 'Salon hatırlatıcısı',+ '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.',+ 'Location access': 'Konum erişimi',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym konumuna erişemiyor. Bunu telefonun ayarlarından değiştirebilirsin.',+ 'My gym': 'Salonum',+ 'Name': 'Ad',+ 'No more nudges when you arrive here.': 'Buraya vardığında artık dürtme yok.',+ 'Not asked yet': 'Henüz sorulmadı',+ 'Nothing found. Try a street and a town.': 'Bir şey bulunamadı. Bir sokak ve şehir dene.',+ 'Notification text': 'Bildirim metni',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'openGym bildirimleri kapalı, yani hatırlatıcının görünecek yeri yok.',+ 'On the next screen, pick “Allow all the time”.': 'Sonraki ekranda “Her zaman izin ver”i seç.',+ 'Only between certain hours': 'Sadece belirli saatlerde',+ 'Only while using the app': 'Sadece uygulama kullanılırken',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Bu saatlerin dışında telefon sessiz kalır, salonda bile.',+ 'Pick it on the map': 'Haritada seç',+ 'Radius': 'Yarıçap',+ 'Ready for your workout? 💪': 'Antrenmana hazır mısın? 💪',+ 'Remove this gym?': 'Bu salon kaldırılsın mı?',+ 'Search': 'Ara',+ 'Search an address': 'Adres ara',+ 'Search an address or drag the pin': 'Adres ara veya iğneyi sürükle',+ 'Searching…': 'Aranıyor…',+ 'Tap the map or drag the pin onto your gym.': 'Haritaya dokun veya iğneyi salonunun üstüne sürükle.',+ 'Tap the map to put the pin on your gym first.': 'Önce haritaya dokunup iğneyi salonuna koy.',+ 'That’s 20 gyms, the most a phone can watch.': 'Bu 20 salon eder, bir telefonun izleyebileceği en fazla sayı.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'Adres araması OpenStreetMap’e (Nominatim) sorar, o da sadece Ara’ya dokunduğunda.',+ 'The address search didn’t answer. Try again in a moment.': 'Adres araması yanıt vermedi. Birazdan tekrar dene.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'Eklediğin salonları telefonun kendisi izler ve openGym’i sadece vardığında uyandırır. Arada takip yok, konumların da bu telefondan hiç çıkmaz.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'Hatırlatıcının arka planda konum erişimine ihtiyacı var. Telefonun ayarlarından izin verebilirsin.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'openGym kapalıyken salona girdiğini fark edebilmesi için telefonun ona konumunu arka planda göstermesi gerekir.',+ 'Until': 'Bitiş',+ 'Use my location': 'Konumumu kullan',+ 'Uses where your phone is': 'Telefonunun konumunu kullanır',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Salonlarından birine gir, openGym seni Başlat’a basman için dürtsün. Günde en fazla bir kez ve zaten antrenman yaptıysan asla. Salonların bu telefonda kalır.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Arka planda konum olmadan telefon, openGym kapalıyken salonunu fark edemez.',+ 'Your gyms': 'Salonların',+ '{0} m': '{0} m',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'openGym için hassas konum kapalı. Telefonun ayarlarından aç, yoksa salonun fark edilemez.',+ '{0} m around the pin': 'İğnenin çevresinde {0} m',+ 'Your gym': 'Salonun',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 90e0836d8..4f20def3d 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -2411,4 +2411,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': 'На цьому пристрої є 1 тренування, якого немає в цій копії. Заміна його видалить.','This device has {0} workouts that are not in this backup. Replacing deletes them.': 'На цьому пристрої є тренування, яких немає в цій копії ({0}). Заміна їх видалить.',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': 'Нагадування, коли ти заходиш у зал.',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': 'Близько 100 м підходить більшості залів. Більше, якщо телефон помічає тебе пізно, менше, якщо він смикає тебе ще на вулиці перед входом.',+ 'Add a gym': 'Додати зал',+ 'All the time': 'Дозволити завжди',+ 'Allow location “All the time”?': 'Дозволити геолокацію «Дозволити завжди»?',+ 'Allow location “Always”?': 'Дозволити геолокацію «Завжди»?',+ 'Always': 'Завжди',+ 'Couldn’t find where you are. Try the map instead.': 'Не вдалося тебе знайти. Спробуй карту.',+ 'Finding you…': 'Шукаємо тебе…',+ 'From': 'З',+ 'Gym reminder': 'Нагадування в залі',+ 'Gym spotted': 'Зал помічено',+ 'I’m at the gym right now': 'Я зараз у залі',+ 'Leave it empty for the default.': 'Залиш порожнім для тексту за замовчуванням.',+ 'Location access': 'Доступ до геолокації',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym не має доступу до геолокації. Це можна змінити в налаштуваннях телефона.',+ 'My gym': 'Мій зал',+ 'Name': 'Назва',+ 'No more nudges when you arrive here.': 'Більше жодних нагадувань, коли ти приходиш сюди.',+ 'Not asked yet': 'Ще не питали',+ 'Nothing found. Try a street and a town.': 'Нічого не знайдено. Спробуй вулицю й місто.',+ 'Notification text': 'Текст сповіщення',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'Сповіщення openGym вимкнені, тож нагадуванню ніде з’явитися.',+ 'On the next screen, pick “Allow all the time”.': 'На наступному екрані вибери «Дозволити завжди».',+ 'Only between certain hours': 'Лише в певні години',+ 'Only while using the app': 'Лише під час використання застосунку',+ 'Outside these hours the phone stays quiet, even at the gym.': 'Поза цими годинами телефон мовчить, навіть у залі.',+ 'Pick it on the map': 'Вибрати на карті',+ 'Radius': 'Радіус',+ 'Ready for your workout? 💪': 'Готовий до тренування? 💪',+ 'Remove this gym?': 'Прибрати цей зал?',+ 'Search': 'Знайти',+ 'Search an address': 'Знайти адресу',+ 'Search an address or drag the pin': 'Знайди адресу або перетягни мітку',+ 'Searching…': 'Шукаємо…',+ 'Tap the map or drag the pin onto your gym.': 'Торкнися карти або перетягни мітку на свій зал.',+ 'Tap the map to put the pin on your gym first.': 'Спершу торкнися карти, щоб поставити мітку на зал.',+ 'That’s 20 gyms, the most a phone can watch.': 'Це 20 залів, більше телефон не відстежить.',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': 'Пошук адреси питає OpenStreetMap (Nominatim), і лише коли ти торкаєшся «Знайти».',+ 'The address search didn’t answer. Try again in a moment.': 'Пошук адреси не відповів. Спробуй ще раз трохи згодом.',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': 'Телефон сам стежить за доданими залами й будить openGym, лише коли ти приходиш. Жодного стеження між тим, а твої місця ніколи не залишають цей телефон.',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': 'Нагадуванню потрібна геолокація у фоні. Її можна дозволити в налаштуваннях телефона.',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': 'Щоб помітити, що ти зайшов у зал, коли openGym закритий, телефон має дозволити йому бачити твою геолокацію у фоні.',+ 'Until': 'До',+ 'Use my location': 'Моє місцезнаходження',+ 'Uses where your phone is': 'Бере місцезнаходження телефона',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': 'Заходиш в один зі своїх залів, і openGym підштовхує натиснути «Старт». Не частіше разу на день і ніколи, якщо ти вже тренувався. Твої зали залишаються на цьому телефоні.',+ 'Without background location the phone can’t spot your gym while openGym is closed.': 'Без геолокації у фоні телефон не впізнає зал, поки openGym закритий.',+ 'Your gyms': 'Твої зали',+ '{0} m': '{0} м',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'Точне місцезнаходження для openGym вимкнене. Увімкни його в налаштуваннях телефона, інакше зал не вдасться розпізнати.',+ '{0} m around the pin': '{0} м навколо мітки',+ 'Your gym': 'Твій зал',}diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex 5077a4e61..c7e8bdfd1 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -2407,4 +2407,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': '此裝置上有 1 筆訓練紀錄不在此備份中。覆蓋將會刪除它。','This device has {0} workouts that are not in this backup. Replacing deletes them.': '此裝置上有 {0} 筆訓練紀錄不在此備份中。覆蓋將會將其全數刪除。',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': '走進健身房時提醒你一下。',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': '大約 100 公尺適合大多數健身房。手機太晚發現你就調大,在門口街上就提醒你就調小。',+ 'Add a gym': '新增健身房',+ 'All the time': '一律允許',+ 'Allow location “All the time”?': '允許位置「一律允許」?',+ 'Allow location “Always”?': '允許位置「永遠」?',+ 'Always': '永遠',+ 'Couldn’t find where you are. Try the map instead.': '找不到你的位置。試試地圖吧。',+ 'Finding you…': '正在定位…',+ 'From': '從',+ 'Gym reminder': '健身房提醒',+ 'Gym spotted': '發現健身房',+ 'I’m at the gym right now': '我現在就在健身房',+ 'Leave it empty for the default.': '留空則使用預設文字。',+ 'Location access': '位置存取權',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym 沒有位置存取權。可以在手機設定裡修改。',+ 'My gym': '我的健身房',+ 'Name': '名稱',+ 'No more nudges when you arrive here.': '到這裡時不再提醒你。',+ 'Not asked yet': '尚未詢問',+ 'Nothing found. Try a street and a town.': '沒有找到。試試街道加城市。',+ 'Notification text': '通知文字',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'openGym 的通知已關閉,提醒沒地方顯示。',+ 'On the next screen, pick “Allow all the time”.': '在下一個畫面選擇「一律允許」。',+ 'Only between certain hours': '僅在特定時段',+ 'Only while using the app': '僅在使用 App 期間',+ 'Outside these hours the phone stays quiet, even at the gym.': '在這些時間之外,手機保持安靜,即使在健身房也一樣。',+ 'Pick it on the map': '在地圖上選擇',+ 'Radius': '半徑',+ 'Ready for your workout? 💪': '準備好訓練了嗎?💪',+ 'Remove this gym?': '移除這個健身房?',+ 'Search': '搜尋',+ 'Search an address': '搜尋地址',+ 'Search an address or drag the pin': '搜尋地址或拖曳圖釘',+ 'Searching…': '搜尋中…',+ 'Tap the map or drag the pin onto your gym.': '點一下地圖,或把圖釘拖到你的健身房上。',+ 'Tap the map to put the pin on your gym first.': '先點一下地圖,把圖釘放到你的健身房上。',+ 'That’s 20 gyms, the most a phone can watch.': '已經 20 個健身房了,這是手機能監測的上限。',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': '地址搜尋會詢問 OpenStreetMap(Nominatim),而且只在你點搜尋時。',+ 'The address search didn’t answer. Try again in a moment.': '地址搜尋沒有回應。稍後再試。',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': '由手機自己監測你新增的健身房,只在你抵達時喚醒 openGym。中間不做任何追蹤,你的地點也永遠不會離開這支手機。',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': '提醒需要背景位置存取權。可以在手機設定裡允許。',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': '為了在 openGym 關閉時發現你走進了健身房,手機需要允許它在背景查看你的位置。',+ 'Until': '到',+ 'Use my location': '使用我的位置',+ 'Uses where your phone is': '使用手機目前位置',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': '走進你的任一健身房,openGym 會提醒你按開始。每天最多一次,已經練過就不會再提醒。你的健身房只存在這支手機上。',+ 'Without background location the phone can’t spot your gym while openGym is closed.': '沒有背景位置存取權,openGym 關閉時手機無法發現你的健身房。',+ 'Your gyms': '你的健身房',+ '{0} m': '{0} 公尺',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'openGym 的精確位置已關閉。請在手機設定中開啟,否則無法發現你的健身房。',+ '{0} m around the pin': '圖釘周圍 {0} 公尺',+ 'Your gym': '你的健身房',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 7857c181c..5cbe2e163 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -2414,4 +2414,58 @@ export default {// --- import with no account: workouts on this device ---'This device has 1 workout that is not in this backup. Replacing deletes it.': '此设备上有 1 次训练不在此备份中。替换会删除它。','This device has {0} workouts that are not in this backup. Replacing deletes them.': '此设备上有 {0} 次训练不在此备份中。替换会删除它们。',+ // --- gym reminder (#614) ---+ 'A nudge when you walk into your gym.': '走进健身房时提醒你一下。',+ 'About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.': '大约 100 米适合大多数健身房。手机发现你太晚就调大,在门口街上就提醒你就调小。',+ 'Add a gym': '添加健身房',+ 'All the time': '始终允许',+ 'Allow location “All the time”?': '允许位置“始终允许”?',+ 'Allow location “Always”?': '允许位置“始终”?',+ 'Always': '始终',+ 'Couldn’t find where you are. Try the map instead.': '找不到你的位置。试试地图吧。',+ 'Finding you…': '正在定位…',+ 'From': '从',+ 'Gym reminder': '健身房提醒',+ 'Gym spotted': '发现健身房',+ 'I’m at the gym right now': '我现在就在健身房',+ 'Leave it empty for the default.': '留空则使用默认文字。',+ 'Location access': '位置权限',+ 'Location isn’t allowed for openGym. You can change that in the phone’s settings.': 'openGym 没有位置权限。可以在手机设置里修改。',+ 'My gym': '我的健身房',+ 'Name': '名称',+ 'No more nudges when you arrive here.': '到这里时不再提醒你。',+ 'Not asked yet': '尚未询问',+ 'Nothing found. Try a street and a town.': '没有找到。试试街道加城市。',+ 'Notification text': '通知文字',+ 'Notifications are off for openGym, so the reminder has nowhere to show up.': 'openGym 的通知已关闭,提醒没地方显示。',+ 'On the next screen, pick “Allow all the time”.': '在下一个界面选择“始终允许”。',+ 'Only between certain hours': '仅在特定时段',+ 'Only while using the app': '仅在使用应用期间',+ 'Outside these hours the phone stays quiet, even at the gym.': '在这些时间之外,手机保持安静,即使在健身房也一样。',+ 'Pick it on the map': '在地图上选择',+ 'Radius': '半径',+ 'Ready for your workout? 💪': '准备好训练了吗?💪',+ 'Remove this gym?': '移除这个健身房?',+ 'Search': '搜索',+ 'Search an address': '搜索地址',+ 'Search an address or drag the pin': '搜索地址或拖动图钉',+ 'Searching…': '搜索中…',+ 'Tap the map or drag the pin onto your gym.': '点按地图,或把图钉拖到你的健身房上。',+ 'Tap the map to put the pin on your gym first.': '先点按地图,把图钉放到你的健身房上。',+ 'That’s 20 gyms, the most a phone can watch.': '已经 20 个健身房了,这是手机能监测的上限。',+ 'The address search asks OpenStreetMap (Nominatim), and only when you tap Search.': '地址搜索会询问 OpenStreetMap(Nominatim),而且只在你点按搜索时。',+ 'The address search didn’t answer. Try again in a moment.': '地址搜索没有响应。稍后再试。',+ 'The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.': '由手机自己监测你添加的健身房,只在你到达时唤醒 openGym。中间不做任何追踪,你的地点也永远不会离开这部手机。',+ 'The reminder needs location access in the background. You can allow it in the phone’s settings.': '提醒需要后台位置权限。可以在手机设置里允许。',+ 'To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.': '为了在 openGym 关闭时发现你走进了健身房,手机需要允许它在后台查看你的位置。',+ 'Until': '到',+ 'Use my location': '使用我的位置',+ 'Uses where your phone is': '使用手机当前位置',+ 'Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.': '走进你的任一健身房,openGym 会提醒你点开始。每天最多一次,已经练过就不会再提醒。你的健身房只存在这部手机上。',+ 'Without background location the phone can’t spot your gym while openGym is closed.': '没有后台位置权限,openGym 关闭时手机无法发现你的健身房。',+ 'Your gyms': '你的健身房',+ '{0} m': '{0} 米',+ 'Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.': 'openGym 的精确位置已关闭。请在手机设置中打开,否则无法发现你的健身房。',+ '{0} m around the pin': '图钉周围 {0} 米',+ 'Your gym': '你的健身房',}diff --git a/frontend/src/views/GymReminder.jsx b/frontend/src/views/GymReminder.jsxnew file mode 100644index 000000000..0e7c0e67a--- /dev/null+++ b/frontend/src/views/GymReminder.jsx@@ -0,0 +1,307 @@+// Settings → Reminders → Gym reminder (#614), phone app only: the gyms that get you a nudge when+// you walk in, and the editor for one of them (a pin on an OpenStreetMap map, a radius, a text).+// What is kept and how the phone watches it: lib/gym-reminder.js.+import { useEffect, useRef, useState } from 'react'+import { useNavigate, useLocation } from 'react-router-dom'+import { t, getLang } from '../lib/i18n.js'+import { useUI } from '../store/useUI.js'+import { useStore } from '../store/useStore.js'+import { Section, Row, Switch, Slider, TextField, Button } from '../components/ui.jsx'+import Icon from '../components/Icon.jsx'+import { confirmSheet, menuSheet } from '../sheets.jsx'+import { platformNow } from '../lib/platform-now.js'+import { nativeFetch } from '../lib/capacitor-fetch.js'+import {+ RADIUS, MAX_GYMS, DEFAULT_WINDOW, normConfig, normGym, statusOf,+ loadGymConfig, saveGymConfig, gymPermissions, askForegroundLocation, askBackgroundLocation,+ currentPosition, openAppSettings,+} from '../lib/gym-reminder.js'++// Asked only on an explicit tap of Search, never while typing (Nominatim's usage policy), with a+// User-Agent that says who is asking.+const NOMINATIM = 'https://nominatim.openstreetmap.org/search'+const USER_AGENT = 'openGym/' + (typeof __APP_VERSION__ === 'string' ? __APP_VERSION__ : 'dev') + ' (gym reminder; +https://opengym.ch)'+export async function searchAddress(q, fetcher = nativeFetch) {+ const query = String(q || '').trim()+ if (!query) return []+ const url = NOMINATIM + '?format=jsonv2&limit=5&q=' + encodeURIComponent(query) + '&accept-language=' + encodeURIComponent(getLang() || 'en')+ const res = await fetcher(url, { headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' } })+ if (!res.ok) throw new Error('search failed: ' + res.status)+ const rows = await res.json()+ return (Array.isArray(rows) ? rows : []).map(r => ({ lat: Number(r.lat), lng: Number(r.lon), label: String(r.display_name || '') }))+ .filter(r => Number.isFinite(r.lat) && Number.isFinite(r.lng))+}++const ios = () => platformNow() === 'ios'++// The one place a permission is explained before the system asks for it.+const explainAlways = () => new Promise(resolve => confirmSheet({+ title: ios() ? t('Allow location “Always”?') : t('Allow location “All the time”?'),+ message: <>+ <p>{t('To notice that you walked into your gym while openGym is closed, the phone needs to let it see your location in the background.')}</p>+ <p style={{ marginTop: 8 }}>{t('The phone itself watches the gyms you added and only wakes openGym when you arrive. No tracking in between, and your locations never leave this phone.')}</p>+ {!ios() && <p style={{ marginTop: 8 }}>{t('On the next screen, pick “Allow all the time”.')}</p>}+ </>,+ confirmText: t('Continue'),+ cancelText: t('Not now'),+ onConfirm: () => resolve(true),+ onCancel: () => resolve(false),+}))++const permLabel = p => !p ? '' : p.background === 'granted' ? (ios() ? t('Always') : t('All the time'))+ : p.location === 'granted' ? t('Only while using the app') : p.location === 'denied' ? t('Not allowed') : t('Not asked yet')++export default function GymReminderPage() {+ const nav = useNavigate()+ const toast = useUI(s => s.toast)+ const [config, setConfig] = useState(null)+ const [perm, setPerm] = useState(null)+ const [busy, setBusy] = useState(false)+ useEffect(() => {+ let gone = false+ loadGymConfig().then(r => { if (!gone) { setConfig(r.config); setPerm(r.permission) } })+ return () => { gone = true }+ }, [])+ // Back from the system settings: the answer may have changed there.+ useEffect(() => {+ const again = () => { if (document.visibilityState === 'visible') gymPermissions().then(p => p && setPerm(p)) }+ document.addEventListener('visibilitychange', again)+ return () => document.removeEventListener('visibilitychange', again)+ }, [])+ if (!config) return <Section><Row icon="mapPin" iconTint="var(--green)" title={t('Checking…')} /></Section>++ const save = async next => {+ const c = normConfig(next)+ setConfig(c)+ const r = await saveGymConfig(c, useStore.getState().S)+ if (r?.permission) setPerm(r.permission)+ return r+ }++ // Off → on: explain, then ask for location while in use, "Always", and notifications.+ const turnOn = async () => {+ setBusy(true)+ try {+ let p = await gymPermissions()+ if (p?.background !== 'granted') {+ if (!(await explainAlways())) return+ p = await askForegroundLocation()+ if (p?.location !== 'granted') { setPerm(p); toast(t('Location isn’t allowed for openGym. You can change that in the phone’s settings.')); return }+ p = await askBackgroundLocation()+ setPerm(p)+ if (p?.background !== 'granted') { toast(t('Without background location the phone can’t spot your gym while openGym is closed.')); return }+ }+ try {+ const { LocalNotifications } = await import('@capacitor/local-notifications')+ let n = await LocalNotifications.checkPermissions()+ if (n.display !== 'granted') n = await LocalNotifications.requestPermissions()+ if (n.display !== 'granted') toast(t('Notifications are off for openGym, so the reminder has nowhere to show up.'))+ } catch { /* no plugin: the native side posts anyway where it may */ }+ await save({ ...config, on: true })+ } finally { setBusy(false) }+ }+ const toggle = v => (v ? turnOn() : save({ ...config, on: false }))++ const full = config.gyms.length >= MAX_GYMS+ const addHere = async () => {+ let p = await gymPermissions()+ if (p?.location !== 'granted') p = await askForegroundLocation()+ if (p?.location !== 'granted') { toast(t('Location isn’t allowed for openGym. You can change that in the phone’s settings.')); return }+ toast(t('Finding you…'))+ const here = await currentPosition()+ if (!here) { toast(t('Couldn’t find where you are. Try the map instead.')); return }+ nav('/settings/gym-edit', { state: { draft: { lat: here.lat, lng: here.lng } } })+ }+ const add = () => menuSheet({+ title: t('Add a gym'),+ items: [+ { icon: 'mapPin', label: t('I’m at the gym right now'), sub: t('Uses where your phone is'), onClick: addHere },+ { icon: 'globe', label: t('Pick it on the map'), sub: t('Search an address or drag the pin'), onClick: () => nav('/settings/gym-edit', { state: { draft: {} } }) },+ ],+ })++ const win = config.window+ const setWin = patch => save({ ...config, window: { ...(win || DEFAULT_WINDOW), ...patch } })++ return <>+ <Section footer={t('Walk into one of your gyms and openGym nudges you to hit Start. Once a day at most, and never when you already trained. Your gyms stay on this phone.')}>+ <Row icon="mapPin" iconTint="var(--green)" title={t('Gym reminder')}>+ <Switch checked={config.on} disabled={busy} onChange={toggle} aria-label={t('Gym reminder')} />+ </Row>+ </Section>+ <Section title={t('Your gyms')} footer={full ? t('That’s 20 gyms, the most a phone can watch.') : null}>+ {config.gyms.map(g => (+ <Row key={g.id} icon="mapPin" iconTint="var(--orange)" title={g.name || t('My gym')}+ subtitle={t('{0} m around the pin', g.radius) + (g.text ? ' · ' + g.text : '')} accessory="chevron"+ onClick={() => nav('/settings/gym-edit', { state: { id: g.id } })} />+ ))}+ {!full && <Row icon="plusCircle" iconTint="var(--green)" title={t('Add a gym')} accessory="chevron" onClick={add} />}+ </Section>+ <Section footer={win ? t('Outside these hours the phone stays quiet, even at the gym.') : null}>+ <Row icon="clock" iconTint="var(--purple)" title={t('Only between certain hours')}>+ <Switch checked={!!win} onChange={v => save({ ...config, window: v ? { ...DEFAULT_WINDOW } : null })} aria-label={t('Only between certain hours')} />+ </Row>+ {win && <Row icon="sunrise" iconTint="var(--orange)" title={t('From')}>+ <input type="time" className="timef" value={win.from} aria-label={t('From')} onChange={e => e.target.value && setWin({ from: e.target.value })} />+ </Row>}+ {win && <Row icon="moon" iconTint="var(--indigo)" title={t('Until')}>+ <input type="time" className="timef" value={win.to} aria-label={t('Until')} onChange={e => e.target.value && setWin({ to: e.target.value })} />+ </Row>}+ </Section>+ {perm && <Section footer={perm.background === 'granted' ? null : perm.precise === false+ ? t('Precise location is off for openGym. Turn it on in the phone’s settings, or your gym can’t be spotted.')+ : t('The reminder needs location access in the background. You can allow it in the phone’s settings.')}>+ <Row icon="lock" iconTint="var(--grey)" title={t('Location access')} value={permLabel(perm)}+ accessory={perm.background === 'granted' ? 'none' : 'chevron'}+ onClick={perm.background === 'granted' ? undefined : () => openAppSettings()} />+ </Section>}+ </>+}++/* ---------------- one gym ---------------- */++// The map: OpenStreetMap tiles through Leaflet, loaded only when this page opens (and only in the+// phone app; the web build never has the page). Tap the map or drag the pin; the circle is the radius.+function GymMap({ pos, radius, onPick, label }) {+ const host = useRef(null)+ const live = useRef(null)+ const pick = useRef(onPick)+ pick.current = onPick+ useEffect(() => {+ let gone = false+ Promise.all([import('leaflet'), import('leaflet/dist/leaflet.css')]).then(([mod]) => {+ const L = mod.default || mod+ if (gone || !host.current) return+ const start = pos || { lat: 20, lng: 0 }+ const map = L.map(host.current, { zoomControl: true, attributionControl: true }).setView([start.lat, start.lng], pos ? 17 : 2)+ map.attributionControl.setPrefix('<a href="https://leafletjs.com" target="_blank" rel="noopener">Leaflet</a>')+ L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {+ maxZoom: 19,+ attribution: '© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors',+ }).addTo(map)+ const icon = L.divIcon({ className: 'gym-pin', html: '<span></span>', iconSize: [30, 30], iconAnchor: [15, 30] })+ const marker = L.marker([start.lat, start.lng], { draggable: true, icon, title: label, alt: label, opacity: pos ? 1 : 0 }).addTo(map)+ const circle = L.circle([start.lat, start.lng], { radius, className: 'gym-radius', interactive: false, opacity: pos ? 1 : 0, fillOpacity: pos ? 0.15 : 0 }).addTo(map)+ const moveTo = ll => { marker.setLatLng(ll); circle.setLatLng(ll); marker.setOpacity(1); circle.setStyle({ opacity: 1, fillOpacity: 0.15 }); pick.current({ lat: ll.lat, lng: ll.lng }) }+ marker.on('drag', e => circle.setLatLng(e.target.getLatLng()))+ marker.on('dragend', e => moveTo(e.target.getLatLng()))+ map.on('click', e => moveTo(e.latlng))+ live.current = { map, marker, circle }+ // The page may still be sliding in: measure once it sits.+ setTimeout(() => { if (!gone) map.invalidateSize() }, 350)+ }).catch(() => {})+ return () => { gone = true; live.current?.map.remove(); live.current = null }+ }, [])+ // A new place from outside (a search result, "use my location"): the pin and the view follow.+ useEffect(() => {+ const m = live.current+ if (!m || !pos) return+ const cur = m.marker.getLatLng()+ if (Math.abs(cur.lat - pos.lat) < 1e-7 && Math.abs(cur.lng - pos.lng) < 1e-7 && m.marker.options.opacity === 1) return+ m.marker.setLatLng([pos.lat, pos.lng]); m.circle.setLatLng([pos.lat, pos.lng])+ m.marker.setOpacity(1); m.circle.setStyle({ opacity: 1, fillOpacity: 0.15 })+ m.map.setView([pos.lat, pos.lng], Math.max(m.map.getZoom(), 16))+ }, [pos?.lat, pos?.lng])+ useEffect(() => { live.current?.circle.setRadius(radius) }, [radius])+ return <div className="gym-map" ref={host} role="application" aria-label={label} />+}++export function GymEditPage() {+ const nav = useNavigate()+ const loc = useLocation()+ const toast = useUI(s => s.toast)+ const S = useStore(s => s.S)+ const [config, setConfig] = useState(null)+ const [gym, setGym] = useState(null)+ const [q, setQ] = useState('')+ const [hits, setHits] = useState(null)+ const [searching, setSearching] = useState(false)+ const editId = loc.state?.id || null+ useEffect(() => {+ let gone = false+ loadGymConfig().then(({ config: c }) => {+ if (gone) return+ setConfig(c)+ const have = editId && c.gyms.find(g => g.id === editId)+ const d = loc.state?.draft || {}+ setGym(have ? { ...have } : { id: null, name: '', lat: d.lat ?? null, lng: d.lng ?? null, radius: RADIUS.def, text: '' })+ })+ return () => { gone = true }+ }, [])+ // Opened with nothing to show (no draft, a gym that is gone): back to the list.+ useEffect(() => { if (config && !gym) nav('/settings/gym', { replace: true }) }, [config, gym])+ if (!config || !gym) return null++ const pos = Number.isFinite(gym.lat) && Number.isFinite(gym.lng) ? { lat: gym.lat, lng: gym.lng } : null+ const set = patch => setGym(g => ({ ...g, ...patch }))+ const close = () => { if ((window.history.state?.idx || 0) > 0) nav(-1); else nav('/settings/gym', { replace: true }) }++ const search = async () => {+ if (!q.trim()) return+ setSearching(true)+ try {+ const r = await searchAddress(q)+ setHits(r)+ if (r.length === 1) { set({ lat: r[0].lat, lng: r[0].lng }); setHits(null) }+ } catch { toast(t('The address search didn’t answer. Try again in a moment.')) }+ setSearching(false)+ }+ const here = async () => {+ let p = await gymPermissions()+ if (p?.location !== 'granted') p = await askForegroundLocation()+ if (p?.location !== 'granted') { toast(t('Location isn’t allowed for openGym. You can change that in the phone’s settings.')); return }+ const h = await currentPosition()+ if (h) set({ lat: h.lat, lng: h.lng })+ else toast(t('Couldn’t find where you are. Try the map instead.'))+ }+ const save = async () => {+ const g = normGym({ ...gym, id: gym.id || undefined })+ if (!g) { toast(t('Tap the map to put the pin on your gym first.')); return }+ const gyms = gym.id ? config.gyms.map(x => (x.id === gym.id ? g : x)) : [...config.gyms, g]+ await saveGymConfig({ ...config, gyms }, S)+ close()+ }+ const remove = () => confirmSheet({+ title: t('Remove this gym?'),+ message: t('No more nudges when you arrive here.'),+ confirmText: t('Remove'), danger: true,+ onConfirm: async () => { await saveGymConfig({ ...config, gyms: config.gyms.filter(x => x.id !== gym.id) }, S); close() },+ })+ const fallback = statusOf(null).body++ return <>+ <Section>+ <div className="gym-search">+ <TextField value={q} onChange={e => setQ(e.target.value)} placeholder={t('Search an address')} aria-label={t('Search an address')}+ inputMode="search" enterKeyHint="search" autoComplete="off" onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); search() } }} />+ <Button variant="tinted" onClick={search} disabled={searching || !q.trim()}>{searching ? t('Searching…') : t('Search')}</Button>+ </div>+ {hits && (hits.length+ ? hits.map((h, i) => <Row key={i} icon="mapPin" iconTint="var(--grey)" title={h.label} onClick={() => { set({ lat: h.lat, lng: h.lng }); setHits(null) }} />)+ : <Row icon="info" iconTint="var(--grey)" title={t('Nothing found. Try a street and a town.')} />)}+ </Section>+ <div className="gym-map-wrap">+ <GymMap pos={pos} radius={gym.radius} onPick={p => set(p)} label={t('Tap the map or drag the pin onto your gym.')} />+ <p className="sect-f">{t('Tap the map or drag the pin onto your gym.')} {t('The address search asks OpenStreetMap (Nominatim), and only when you tap Search.')}</p>+ </div>+ <Section>+ <Row icon="mapPin" iconTint="var(--blue)" title={t('Use my location')} accessory="chevron" onClick={here} />+ </Section>+ <Section title={t('Radius')} footer={t('About 100 m fits most gyms. Bigger if the phone notices you late, smaller if it pings you on the street outside.')}>+ <div className="gym-radius-row">+ <Slider value={gym.radius} min={RADIUS.min} max={RADIUS.max} step={RADIUS.step} onChange={v => set({ radius: v })} />+ <span className="gym-radius-val">{t('{0} m', gym.radius)}</span>+ </div>+ </Section>+ <Section title={t('Name')}>+ <div className="gym-field"><TextField value={gym.name} maxLength={60} onChange={e => set({ name: e.target.value })} placeholder={t('My gym')} aria-label={t('Name')} /></div>+ </Section>+ <Section title={t('Notification text')} footer={t('Leave it empty for the default.')}>+ <div className="gym-field"><TextField value={gym.text} maxLength={120} onChange={e => set({ text: e.target.value })} placeholder={fallback} aria-label={t('Notification text')} /></div>+ </Section>+ <div className="gym-actions">+ <Button variant="primary" onClick={save} disabled={!pos}>{t('Save')}</Button>+ {gym.id && <Button variant="danger" icon="trash" onClick={remove}>{t('Remove')}</Button>}+ </div>+ </>+}diff --git a/frontend/src/views/GymReminder.test.jsx b/frontend/src/views/GymReminder.test.jsxnew file mode 100644index 000000000..44ec82618--- /dev/null+++ b/frontend/src/views/GymReminder.test.jsx@@ -0,0 +1,183 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++// #614: Settings → Reminders → Gym reminder. The native side is mocked (lib/gym-reminder.js has+// its own tests); this checks the page's flow: off by default, the explainer before any system+// prompt, "Always" asked only after it, the gyms list, the time window and the editor's save.+const mocks = vi.hoisted(() => ({+ config: { on: false, gyms: [], window: null },+ perm: { location: 'prompt', background: 'prompt', notifications: 'granted' },+ saved: [], asked: [], confirm: true, nav: vi.fn(), toast: vi.fn(), menu: null, location: { state: null },+ here: { lat: 47.3769, lng: 8.5417, accuracy: 12 },+}))+vi.mock('../lib/gym-reminder.js', async () => {+ const real = await vi.importActual('../lib/gym-reminder.js')+ return {+ ...real,+ loadGymConfig: async () => ({ config: real.normConfig(mocks.config), permission: mocks.perm }),+ saveGymConfig: async c => { mocks.saved.push(real.normConfig(c)); mocks.config = real.normConfig(c); return { watching: c.on ? c.gyms.length : 0, permission: mocks.perm } },+ gymPermissions: async () => mocks.perm,+ askForegroundLocation: async () => { mocks.asked.push('foreground'); mocks.perm = { ...mocks.perm, location: 'granted' }; return mocks.perm },+ askBackgroundLocation: async () => { mocks.asked.push('background'); mocks.perm = { ...mocks.perm, background: 'granted' }; return mocks.perm },+ currentPosition: async () => mocks.here,+ openAppSettings: vi.fn(),+ }+})+vi.mock('../sheets.jsx', () => ({+ confirmSheet: o => { mocks.asked.push('explainer'); if (mocks.confirm) o.onConfirm?.(); else o.onCancel?.() },+ menuSheet: o => { mocks.menu = o },+}))+vi.mock('../store/useUI.js', () => {+ const snap = () => ({ toast: mocks.toast })+ const useUI = sel => (sel ? sel(snap()) : snap())+ useUI.getState = snap+ return { useUI }+})+vi.mock('../store/useStore.js', () => {+ const snap = () => ({ S: { workouts: [] } })+ const useStore = sel => (sel ? sel(snap()) : snap())+ useStore.getState = snap+ return { useStore }+})+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav, useLocation: () => mocks.location }))+vi.mock('@capacitor/local-notifications', () => ({+ LocalNotifications: { checkPermissions: async () => ({ display: 'granted' }), requestPermissions: async () => ({ display: 'granted' }) },+}))+// The map is Leaflet in the phone app; here a stand-in that records what the page asks of it.+vi.mock('leaflet', () => {+ const layer = () => ({ addTo() { return this }, on() { return this }, setLatLng() {}, setOpacity() {}, setStyle() {}, setRadius() {}, getLatLng: () => ({ lat: 0, lng: 0 }), options: { opacity: 0 } })+ const L = {+ map: () => ({ setView() { return this }, attributionControl: { setPrefix() {} }, on() {}, invalidateSize() {}, remove() {}, getZoom: () => 2 }),+ tileLayer: layer, marker: layer, circle: layer, divIcon: () => ({}),+ }+ return { default: L, ...L }+})+vi.mock('leaflet/dist/leaflet.css', () => ({}))++import GymReminderPage, { GymEditPage, searchAddress } from './GymReminder.jsx'++let host, root+const flush = async () => { for (let i = 0; i < 6; i++) await act(async () => { await new Promise(r => setTimeout(r, 0)) }) }+const render = async el => { await act(async () => { root.render(el) }); await flush() }+const rowByText = text => [...host.querySelectorAll('.lrow, .row, [class*="row"]')].find(e => e.textContent.includes(text))+const switchIn = text => rowByText(text)?.querySelector('[role="switch"], input[type="checkbox"], button')+const click = async el => { await act(async () => { el.click() }); await flush() }++beforeEach(() => {+ mocks.config = { on: false, gyms: [], window: null }+ mocks.perm = { location: 'prompt', background: 'prompt', notifications: 'granted' }+ mocks.saved = []; mocks.asked = []; mocks.confirm = true; mocks.menu = null; mocks.location = { state: null }+ mocks.nav.mockClear(); mocks.toast.mockClear()+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+})+afterEach(() => { act(() => root.unmount()); host.remove() })++describe('Gym reminder page', () => {+ it('off by default, with an empty list and an Add row', async () => {+ await render(<GymReminderPage />)+ expect(host.textContent).toContain('Gym reminder')+ expect(host.textContent).toContain('Your gyms')+ expect(host.textContent).toContain('Add a gym')+ const sw = switchIn('Gym reminder')+ expect(sw.getAttribute('aria-checked') ?? String(sw.checked)).toMatch(/false/)+ // the places never leave the phone, and it says so+ expect(host.textContent).toContain('Your gyms stay on this phone')+ })++ it('turning it on explains first, then asks while-in-use, then Always, then saves', async () => {+ await render(<GymReminderPage />)+ await click(switchIn('Gym reminder'))+ expect(mocks.asked).toEqual(['explainer', 'foreground', 'background'])+ expect(mocks.saved.at(-1).on).toBe(true)+ })++ it('"Not now" on the explainer: no system prompt, stays off', async () => {+ mocks.confirm = false+ await render(<GymReminderPage />)+ await click(switchIn('Gym reminder'))+ expect(mocks.asked).toEqual(['explainer'])+ expect(mocks.saved).toEqual([])+ })++ it('Always already given: no explainer, straight on', async () => {+ mocks.perm = { location: 'granted', background: 'granted', notifications: 'granted' }+ await render(<GymReminderPage />)+ await click(switchIn('Gym reminder'))+ expect(mocks.asked).toEqual([])+ expect(mocks.saved.at(-1).on).toBe(true)+ })++ it('lists the gyms with their radius; a tap opens the editor', async () => {+ mocks.config = { on: true, gyms: [{ id: 'a', name: 'Downtown', lat: 47.37, lng: 8.54, radius: 150, text: '' }], window: null }+ await render(<GymReminderPage />)+ expect(host.textContent).toContain('Downtown')+ expect(host.textContent).toContain('150 m around the pin')+ await click(rowByText('Downtown'))+ expect(mocks.nav).toHaveBeenCalledWith('/settings/gym-edit', { state: { id: 'a' } })+ })++ it('"I\'m at the gym right now" takes the phone\'s position into the editor', async () => {+ await render(<GymReminderPage />)+ await click(rowByText('Add a gym'))+ expect(mocks.menu.items.map(i => i.label)).toEqual(['I’m at the gym right now', 'Pick it on the map'])+ await act(async () => { await mocks.menu.items[0].onClick() })+ expect(mocks.asked).toEqual(['foreground'])+ expect(mocks.nav).toHaveBeenCalledWith('/settings/gym-edit', { state: { draft: { lat: 47.3769, lng: 8.5417 } } })+ })++ it('the optional time window: 06:00 to 22:00 when switched on', async () => {+ await render(<GymReminderPage />)+ await click(switchIn('Only between certain hours'))+ expect(mocks.saved.at(-1).window).toEqual({ from: '06:00', to: '22:00' })+ expect(host.querySelectorAll('input[type="time"]')).toHaveLength(2)+ })++ it('background location refused: the row says so and leads to the settings', async () => {+ mocks.perm = { location: 'granted', background: 'denied', notifications: 'granted' }+ await render(<GymReminderPage />)+ expect(host.textContent).toContain('Only while using the app')+ expect(host.textContent).toContain('needs location access in the background')+ })+})++describe('one gym', () => {+ it('a new gym from a draft: default radius, saved with the place', async () => {+ mocks.location = { state: { draft: { lat: 47.3769, lng: 8.5417 } } }+ await render(<GymEditPage />)+ expect(host.textContent).toContain('100 m')+ expect(host.querySelector('.gym-map')).toBeTruthy()+ // OpenStreetMap is asked only on an explicit Search+ expect(host.textContent).toContain('only when you tap Search')+ const save = [...host.querySelectorAll('button')].find(b => b.textContent === 'Save')+ await click(save)+ expect(mocks.saved.at(-1).gyms).toHaveLength(1)+ expect(mocks.saved.at(-1).gyms[0]).toMatchObject({ lat: 47.3769, lng: 8.5417, radius: 100 })+ })++ it('without a place, Save waits for the pin', async () => {+ mocks.location = { state: { draft: {} } }+ await render(<GymEditPage />)+ const save = [...host.querySelectorAll('button')].find(b => b.textContent === 'Save')+ expect(save.disabled).toBe(true)+ })+})++describe('address search (Nominatim)', () => {+ it('sends a User-Agent that names the app, and reads the answer', async () => {+ const fetcher = vi.fn(async () => ({ ok: true, json: async () => [{ lat: '47.1', lon: '8.2', display_name: 'Gym Street 1, Town' }, { lat: 'x', lon: '1' }] }))+ const r = await searchAddress('Gym Street 1', fetcher)+ expect(r).toEqual([{ lat: 47.1, lng: 8.2, label: 'Gym Street 1, Town' }])+ const [url, init] = fetcher.mock.calls[0]+ expect(url).toMatch(/^https:\/\/nominatim\.openstreetmap\.org\/search\?format=jsonv2&limit=5&q=Gym%20Street%201/)+ expect(init.headers['User-Agent']).toMatch(/^openGym\/.+opengym\.ch/)+ })+ it('an empty query asks nobody', async () => {+ const fetcher = vi.fn()+ expect(await searchAddress(' ', fetcher)).toEqual([])+ expect(fetcher).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 23ccc5958..afce9fa12 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -51,6 +51,8 @@ import { PAGES, ROOT_GROUPS, pageVisible, searchSettings, pageTrail } from './seimport { platformNow } from '../lib/platform-now.js'import { pathBefore } from '../lib/nav.js'import WatchSettingsPage from './WatchSettings.jsx'+import GymReminderPage, { GymEditPage } from './GymReminder.jsx'+import { readGymConfig } from '../lib/gym-reminder.js'/* Settings (v1.3.11). The root is one screen: an account card, eleven rows that each open a page(/settings/<page>), and a search over every row. Rare things live one level further down@@ -73,7 +75,7 @@ export function SettingsRoute() {// that did not know yet sent every visit to it straight back to the root.// (Unknown counts as yes inside the phone app: the page itself then says there is no watch.)const ctx = { user: useStore(s => s.user), mobile: MOBILE, ios: MOBILE && platformNow() !== 'android' }- if (page && (!PAGES[page] || !pageVisible(PAGES[page].parent || page, ctx))) return <Navigate to="/settings" replace />+ if (page && (!PAGES[page] || !pageVisible(PAGES[page].parent || page, ctx) || !pageVisible(page, ctx))) return <Navigate to="/settings" replace />if (page === 'coach') return <Navigate to="/coach/setup" replace />return <Settings key={page || 'root'} page={page || null} find={loc.state?.find || null} via={loc.state?.via || null} entryKey={loc.key} />}@@ -112,6 +114,8 @@ export default function Settings({ page = null, find = null, via = null, entryKeconst importRef = useRef(null)const body = useRef(null)const wakeOK = wakeLockSupported()+ // The gym reminder's switch lives on its own page and on this device only (lib/gym-reminder.js).+ const gymOn = MOBILE && readGymConfig().on// A planner's own queue (no rotationId, or one that doesn't match the saved rotation here) is// not this app's to switch off or overwrite. The Scheduling row goes read-only for it.@@ -490,6 +494,8 @@ export default function Settings({ page = null, find = null, via = null, entryKeconst pages = {watch: () => <WatchSettingsPage />,+ gym: () => <GymReminderPage />,+ 'gym-edit': () => <GymEditPage />,workout: () => <><Section title={t('Rest')} footer={t('Each exercise can have its own rest too. Set it in the exercise settings of a routine.')}>{restRow}@@ -669,7 +675,12 @@ export default function Settings({ page = null, find = null, via = null, entryKe</>},- reminders: () => <NotificationsCard S={S} update={update} toast={toast} />,+ reminders: () => <>+ <NotificationsCard S={S} update={update} toast={toast} />+ {MOBILE && <Section footer={t('A nudge when you walk into your gym.')}>+ <Row icon="mapPin" iconTint="var(--green)" title={t('Gym reminder')} value={gymOn ? t('On') : t('Off')} accessory="chevron" onClick={() => nav('/settings/gym')} />+ </Section>}+ </>,plan: () => <><Section>diff --git a/frontend/src/views/settings-pages.js b/frontend/src/views/settings-pages.jsindex b6c805a3c..1ef0929d0 100644--- a/frontend/src/views/settings-pages.js+++ b/frontend/src/views/settings-pages.js@@ -22,6 +22,9 @@ export const PAGES = {about: { title: 'About & updates', icon: 'info', tint: 'var(--grey)' },account: { title: 'Account', icon: 'personCircle', tint: 'var(--grey)' },advanced: { title: 'Fine-tuning', icon: 'wrench', tint: 'var(--grey)', parent: 'workout' },+ // Phone app only (#614): the gyms that get you a nudge when you arrive, and one of them.+ gym: { title: 'Gym reminder', icon: 'mapPin', tint: 'var(--green)', parent: 'reminders' },+ 'gym-edit': { title: 'Your gym', icon: 'mapPin', tint: 'var(--orange)', parent: 'gym' },}export const PAGE_IDS = Object.keys(PAGES)@@ -38,6 +41,8 @@ export function pageVisible(page, ctx) {if (page === 'coach') return !!ctx.mobile// The iPhone app only: the watch app ships inside it.if (page === 'watch') return !!ctx.ios+ // The phone app only: a browser cannot watch where you are with the page closed.+ if (page === 'gym' || page === 'gym-edit') return !!ctx.mobilereturn page in PAGES}@@ -89,6 +94,7 @@ export const SEARCH = [{ page: 'reminders', title: 'Reminder time', icon: 'clock', tint: 'var(--purple)', kw: 'reminder time clock hour when', when: c => remind(c) && c.reminderOn, via: PUSH },{ page: 'reminders', title: 'Nudge me when I skip a planned workout', icon: 'bell', tint: 'var(--red)', kw: 'nudge skip missed motivation', when: c => remind(c) && c.reminderOn, via: PUSH },{ page: 'reminders', title: 'Nudge tone', icon: 'chat', tint: 'var(--blue)', kw: 'nudge tone friendly guilt drill sergeant', opts: ['Friendly', 'Guilt trip', 'Drill sergeant'], when: c => remind(c) && c.reminderOn && c.nudge, via: PUSH },+ { page: 'reminders', title: 'Gym reminder', icon: 'mapPin', tint: 'var(--green)', kw: 'gym location arrive arrival geofence place map nearby', when: c => !!c.mobile },{ page: 'reminders', title: 'Send test notification', icon: 'bell', tint: 'var(--red)', kw: 'test push notification try', when: c => !c.mobile && c.pushOK, via: PUSH },// Plan & schedule{ page: 'plan', title: 'How you train', icon: 'repeat', tint: 'var(--orange)', kw: 'scheduling schedule rotation fixed week split loop round cycle', opts: ['Fixed Week', 'Rotation'] },diff --git a/scripts/android/gym-reminder-emulator.sh b/scripts/android/gym-reminder-emulator.shnew file mode 100755index 000000000..a6a76f590--- /dev/null+++ b/scripts/android/gym-reminder-emulator.sh@@ -0,0 +1,59 @@+#!/usr/bin/env bash+# Proves the gym reminder (#614) on the Android emulator: a gym is saved through the app's own+# plugin, the emulator's GPS is moved far away and then into the gym, and the notification has to+# show up in the shade. Nothing here touches a real device or the network.+#+# scripts/android/gym-reminder-emulator.sh <debug apk>+#+# Needs a running emulator (adb devices) with the debug build's WebView debuggable, Node 22 and+# the CDP driver (CDP=/root/homelab/scripts/android-repro/cdp.mjs by default). Exits 0 when the+# notification fired, 1 when it did not within the time allowed.+set -euo 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}+# A gym in Zurich, and a point 5 km away.+LAT=47.3769; LNG=8.5417+FAR_LAT=47.4200; FAR_LNG=8.5900+cdp() { PKG=$PKG node --experimental-websocket "$CDP" "$@"; }++$ADB install -r -g "$APK" >/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 || true+$ADB shell cmd notification post -S bigtext -t clear x x >/dev/null 2>&1 || true+$ADB shell cmd notification cancel_all "$PKG" >/dev/null 2>&1 || true++echo "== far away"+$ADB emu geo fix $FAR_LNG $FAR_LAT >/dev/null+$ADB shell am start -n "$PKG/ch.duartesantos.opengym.MainActivity" >/dev/null+sleep 12++echo "== save a gym through the plugin (as Settings does)"+cdp eval "(async () => { const P = window.Capacitor.Plugins.GymReminder;+ await P.status({ trainedOn: '2000-01-01', quietOn: '', activeSince: 0, title: 'Gym spotted', body: 'Ready for your workout? 💪', channel: 'Gym reminder' });+ return JSON.stringify(await P.configure({ config: { on: true, window: null, gyms: [{ id: 'emu', name: 'Emulator gym', lat: $LAT, lng: $LNG, radius: 100, text: '' }] } })) })()"++echo "== app to the background, wait out the 90 s arming grace"+$ADB shell input keyevent KEYCODE_HOME+for i in $(seq 1 10); do $ADB emu geo fix $FAR_LNG $FAR_LAT >/dev/null; sleep 10; done++echo "== walk into the gym"+for step in 0.0300 0.0200 0.0100 0.0050 0.0020 0.0005 0; do+ $ADB emu geo fix "$(python3 -c "print($LNG+$step)")" "$(python3 -c "print($LAT+$step)")" >/dev/null+ sleep 5+done+start=$(date +%s)+while [ $(( $(date +%s) - start )) -lt 240 ]; do+ $ADB emu geo fix $LNG $LAT >/dev/null+ if $ADB shell dumpsys notification --noredact | grep -q "Gym spotted"; then+ echo "== notification fired after $(( $(date +%s) - start )) s inside the radius"+ $ADB shell dumpsys notification --noredact | grep -E "pkg=$PKG|android.title=|android.text=" | grep -A2 "pkg=$PKG" | head -12+ exit 0+ fi+ sleep 5+done+echo "== no notification within 240 s"+exit 1