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
Android app: with Vibrate off, the end of a rest no longer buzzes while the phone is locked or the app is in the background either; the alert goes out on a rest channel that never vibrates, and the stand-in buzz without notifications stays quiet too
Duarte Santos206449a23ec1
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.javaindex 59b07454d..568837912 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java@@ -33,8 +33,15 @@ public final class RestAlert {static final String ACTION_ACCENT = "ch.duartesantos.opengym.rest.ACCENT";static final String ACTION_HOLD = "ch.duartesantos.opengym.rest.HOLD";static final String CHANNEL_ID = "rest-over";+ /**+ * Settings → Vibrate off. Android keeps a channel's vibration as it was when the channel was+ * created (after that it is the user's, in the system settings), so "rest-over" buzzes for+ * good and an end that must not buzz goes out on this channel, which never vibrates.+ */+ static final String QUIET_CHANNEL_ID = "rest-over-quiet";private static String lastAlertTitle = "Rest over";private static boolean lastSound = true;+ private static boolean lastVibrate = true;private static String lastChannel = CHANNEL_ID;private static String labPause = "Pause";private static String labResume = "Resume";@@ -55,14 +62,15 @@ public final class RestAlert {private RestAlert() {}- public static void schedule(Context ctx, long at, int id, String title, boolean sound,+ public static void schedule(Context ctx, long at, int id, String title, boolean sound, boolean vibrate,String channelId, String visibility, String importance, boolean localOnly,String countdownTitle, long totalMs) {- if (channelId == null || channelId.isEmpty()) channelId = CHANNEL_ID;+ channelId = channelFor(channelId, vibrate);Intent intent = alarmIntent(ctx);intent.putExtra("id", id);intent.putExtra("title", title == null ? "" : title);intent.putExtra("sound", sound);+ intent.putExtra("vibrate", vibrate);intent.putExtra("channelId", channelId);intent.putExtra("visibility", visibility == null ? "public" : visibility);intent.putExtra("importance", importance == null ? "high" : importance);@@ -81,10 +89,11 @@ public final class RestAlert {if (!exact) Log.w("openGym", "exact alarms not allowed; the rest countdown sounds the end itself");if (Build.VERSION.SDK_INT >= 26) {NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);- ensureChannel(ctx, nm, channelId, importanceOf(importance), visibilityOf(visibility));+ ensureChannel(ctx, nm, channelId, importanceOf(importance), visibilityOf(visibility), vibrate);}lastAlertTitle = title == null ? "Rest over" : title;lastSound = sound;+ lastVibrate = vibrate;lastChannel = channelId;startCountdown(ctx, at, totalMs, countdownTitle);}@@ -124,6 +133,7 @@ public final class RestAlert {intent.putExtra("id", NOTIFICATION_ID);intent.putExtra("title", lastAlertTitle);intent.putExtra("sound", lastSound);+ intent.putExtra("vibrate", lastVibrate);intent.putExtra("channelId", lastChannel);intent.putExtra("at", at);new Thread(() -> fire(ctx, intent), "opengym-rest").start();@@ -155,8 +165,10 @@ public final class RestAlert {return;}pokeScreen(ctx);+ boolean vibrate = intent.getBooleanExtra("vibrate", true);boolean shown = showNotification(ctx, intent);- if (!shown) vibrateFallback(ctx);+ // Settings → Vibrate off is off here too: without notifications this buzz is the alert.+ if (!shown && vibrate) vibrateFallback(ctx);// The countdown card is the foreground-service notification. Drop it once the// "rest over" alert is up, including when the WebView is frozen.stopCountdown(ctx);@@ -196,14 +208,14 @@ public final class RestAlert {private static boolean showNotification(Context ctx, Intent intent) {String title = intent.getStringExtra("title");if (title == null || title.isEmpty()) title = "Rest over — next set!";- String channelId = intent.getStringExtra("channelId");- if (channelId == null || channelId.isEmpty()) channelId = CHANNEL_ID;+ boolean vibrate = intent.getBooleanExtra("vibrate", true);+ String channelId = channelFor(intent.getStringExtra("channelId"), vibrate);int id = intent.getIntExtra("id", NOTIFICATION_ID);boolean localOnly = intent.getBooleanExtra("localOnly", false);int visibility = visibilityOf(intent.getStringExtra("visibility"));NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);if (Build.VERSION.SDK_INT >= 24 && !nm.areNotificationsEnabled()) return false;- ensureChannel(ctx, nm, channelId, importanceOf(intent.getStringExtra("importance")), visibility);+ ensureChannel(ctx, nm, channelId, importanceOf(intent.getStringExtra("importance")), visibility, vibrate);Notification.Builder b = Build.VERSION.SDK_INT >= 26? new Notification.Builder(ctx, channelId): new Notification.Builder(ctx);@@ -215,8 +227,9 @@ public final class RestAlert {.setCategory(Notification.CATEGORY_ALARM).setVisibility(visibility).setColor(lastAccent)- .setContentIntent(openApp(ctx))- .setVibrate(VIBRATE);+ .setContentIntent(openApp(ctx));+ // Android 8+ takes the vibration from the channel; before that, from the notification.+ if (vibrate) b.setVibrate(VIBRATE);if (Build.VERSION.SDK_INT >= 26) b.setOnlyAlertOnce(false);else b.setPriority(Notification.PRIORITY_HIGH);if (localOnly) b.setLocalOnly(true);@@ -228,15 +241,27 @@ public final class RestAlert {}}- private static void ensureChannel(Context ctx, NotificationManager nm, String channelId, int importance, int visibility) {+ /** The quiet channel when Vibrate is off, whatever channel the page named. */+ static String channelFor(String channelId, boolean vibrate) {+ if (!vibrate) return QUIET_CHANNEL_ID;+ if (channelId == null || channelId.isEmpty() || QUIET_CHANNEL_ID.equals(channelId)) return CHANNEL_ID;+ return channelId;+ }++ private static void ensureChannel(Context ctx, NotificationManager nm, String channelId, int importance, int visibility, boolean vibrate) {if (Build.VERSION.SDK_INT < 26) return;if (nm.getNotificationChannel(channelId) != null) return;NotificationChannel channel = new NotificationChannel(- channelId, ctx.getString(R.string.rest_channel_name), importance);+ channelId, ctx.getString(vibrate ? R.string.rest_channel_name : R.string.rest_quiet_channel_name), importance);channel.setDescription(ctx.getString(R.string.rest_channel_desc));channel.setLockscreenVisibility(visibility);- channel.enableVibration(true);- channel.setVibrationPattern(VIBRATE);+ if (vibrate) {+ channel.enableVibration(true);+ channel.setVibrationPattern(VIBRATE);+ } else {+ channel.enableVibration(false);+ channel.setVibrationPattern(null);+ }// Silent on purpose. The beep is the in-app tone or playSound(), not a second ding// from this channel.channel.setSound(null, null);@@ -282,6 +307,7 @@ public final class RestAlert {intent.putExtra("id", NOTIFICATION_ID);intent.putExtra("title", lastAlertTitle);intent.putExtra("sound", lastSound);+ intent.putExtra("vibrate", lastVibrate);intent.putExtra("channelId", lastChannel);intent.putExtra("visibility", "public");intent.putExtra("importance", "high");diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.javaindex 20c7f6ad0..09383bead 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java@@ -15,7 +15,7 @@ import com.getcapacitor.annotation.CapacitorPlugin;* Usage from JS:* import { registerPlugin } from '@capacitor/core';* const RestAlert = registerPlugin('RestAlert');- * await RestAlert.schedule({ id, at, title, sound, channelId, visibility, importance, localOnly });+ * await RestAlert.schedule({ id, at, title, sound, vibrate, channelId, visibility, importance, localOnly });* await RestAlert.cancel({ id });*/@CapacitorPlugin(name = "RestAlert")@@ -82,6 +82,7 @@ public class RestAlertPlugin extends Plugin {(int) number(call, "id", RestAlert.NOTIFICATION_ID),call.getString("title", "Rest over"),!Boolean.FALSE.equals(call.getBoolean("sound", Boolean.TRUE)),+ !Boolean.FALSE.equals(call.getBoolean("vibrate", Boolean.TRUE)),call.getString("channelId", RestAlert.CHANNEL_ID),call.getString("visibility", "public"),call.getString("importance", "high"),diff --git a/frontend/android/app/src/main/res/values/strings.xml b/frontend/android/app/src/main/res/values/strings.xmlindex 72c1cdce7..0c66475e7 100644--- a/frontend/android/app/src/main/res/values/strings.xml+++ b/frontend/android/app/src/main/res/values/strings.xml@@ -6,5 +6,6 @@<string name="custom_url_scheme">ch.duartesantos.opengym</string><string name="rest_countdown_channel_name">Rest countdown</string><string name="rest_channel_name">Rest timer</string>+ <string name="rest_quiet_channel_name">Rest timer, without vibration</string><string name="rest_channel_desc">Rest between sets, in the notification shade. The lock screen shows it only when notifications are allowed there.</string></resources>diff --git a/frontend/src/lib/rest-alert.js b/frontend/src/lib/rest-alert.jsindex 82fafe3e7..187f2d14f 100644--- a/frontend/src/lib/rest-alert.js+++ b/frontend/src/lib/rest-alert.js@@ -14,6 +14,10 @@ import { MOBILE, isAndroid } from './mobile.js'export const REST_ALERT_ID = 42export const REST_CHANNEL_ID = 'rest-over'+// Settings → Vibrate off. A notification channel's vibration is the system's to keep once the+// channel exists, so the app cannot switch it off on 'rest-over': an end that must not buzz is+// posted on a second channel that never vibrates (RestAlert.java).+export const REST_QUIET_CHANNEL_ID = 'rest-over-quiet'// One object the native side schedules. Public + high is what the notification shade can show.// The lock screen follows the user's notification settings.@@ -22,13 +26,13 @@ export function accentColors(key) {return { accent: argb(ACCENTS[k]), ink: argb(ACCENT_INK[k]) }}-export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, sound = true, now = Date.now() } = {}) {+export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, sound = true, vibrate = true, now = Date.now() } = {}) {if (typeof at !== 'number' || !(at > now)) return nullconst totalMs = Math.max(1000, Math.round((totalSec > 0 ? totalSec : (at - now) / 1000) * 1000))const colors = accentColors(accent)return {id: REST_ALERT_ID,- channelId: REST_CHANNEL_ID,+ channelId: vibrate ? REST_CHANNEL_ID : REST_QUIET_CHANNEL_ID,title: title || t('Rest over — next set!'),countdownTitle: countdownTitle || t('Rest'),pause: t('Pause'),@@ -42,6 +46,7 @@ export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, soat,allowWhileIdle: true,sound: !!sound,+ vibrate: !!vibrate,localOnly: false,visibility: 'public',importance: 'high',@@ -77,7 +82,7 @@ const restPlugin = () => pluginP || (pluginP = (async () => {export function armRestAlert(at, opts = {}) {if (!MOBILE) return Promise.resolve(false)const mine = ++token- const alert = buildRestAlert({ at, title: opts.title, countdownTitle: opts.countdownTitle, totalSec: opts.totalSec, accent: opts.accent, sound: opts.sound })+ const alert = buildRestAlert({ at, title: opts.title, countdownTitle: opts.countdownTitle, totalSec: opts.totalSec, accent: opts.accent, sound: opts.sound, vibrate: opts.vibrate !== false })if (!alert) return Promise.resolve(false)return enqueue(async () => {let kind = 'failed'@@ -154,6 +159,9 @@ async function deliver(alert) {at: alert.at,title: alert.title,sound: alert.sound,+ // The end of a rest the app is not in front for: the notification, or the buzz standing in+ // for it where notifications are off. With the app in front the page buzzes (lib/sound.js).+ vibrate: alert.vibrate,channelId: alert.channelId,visibility: alert.visibility,importance: alert.importance,diff --git a/frontend/src/lib/rest-alert.native.test.js b/frontend/src/lib/rest-alert.native.test.jsindex 9e0830f09..e08d3e016 100644--- a/frontend/src/lib/rest-alert.native.test.js+++ b/frontend/src/lib/rest-alert.native.test.js@@ -4,6 +4,7 @@// it must never become the value of a promise (the Coach hang, #42): here that would hang every// rest alert call.import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { readFileSync } from 'node:fs'const h = vi.hoisted(() => {vi.stubEnv('VITE_MOBILE', '1') // lib/mobile.js: MOBILE = import.meta.env.VITE_MOBILE === '1'@@ -96,4 +97,44 @@ describe('the rest alert in the Android app', () => {accent: (0xff000000 | 0xff453a) >>> 0, ink: 0xffffffff,}))})++ // Settings → Vibrate off, with the phone locked: the notification still buzzed the whole+ // pattern, and so did the stand-in buzz where notifications are off, because neither was told.+ it('tells the plugin whether the end may buzz, on a channel that matches', async () => {+ h.platform = 'android'+ const schedule = vi.fn(async () => {})+ h.registerPlugin = vi.fn(() => new Proxy({}, {+ get: (_, prop) => prop === 'then' ? () => new Promise(() => {}) : prop === 'schedule' ? schedule : async () => ({ remove: async () => {} }),+ }))+ const alert = await import('./rest-alert.js')+ await alert.armRestAlert(Date.now() + 90_000, { totalSec: 90 })+ expect(schedule).toHaveBeenLastCalledWith(expect.objectContaining({ vibrate: true, channelId: 'rest-over' }))+ await alert.armRestAlert(Date.now() + 90_000, { totalSec: 90, vibrate: false })+ expect(schedule).toHaveBeenLastCalledWith(expect.objectContaining({ vibrate: false, channelId: 'rest-over-quiet' }))+ })+})++// The native half cannot run here; what it must do with the flag is read off its source.+describe('the Android side of Vibrate off', () => {+ const src = name => readFileSync(new URL(`../../android/app/src/main/java/ch/duartesantos/opengym/${name}.java`, import.meta.url), 'utf8')+ const alert = src('RestAlert')++ it('reads the flag from the page, defaulting to on for an older page', () => {+ expect(src('RestAlertPlugin')).toMatch(/call\.getBoolean\("vibrate", Boolean\.TRUE\)/)+ })++ it('posts on a channel created without vibration, and only buzzes by hand when allowed to', () => {+ expect(alert).toMatch(/QUIET_CHANNEL_ID = "rest-over-quiet"/)+ expect(alert).toMatch(/if \(!vibrate\) return QUIET_CHANNEL_ID;/)+ expect(alert).toMatch(/channel\.enableVibration\(false\)/)+ expect(alert).toMatch(/if \(!shown && vibrate\) vibrateFallback\(ctx\);/)+ expect(alert).toMatch(/if \(vibrate\) b\.setVibrate\(VIBRATE\);/)+ expect(alert.match(/\.setVibrate\(/g)).toHaveLength(1)+ })++ it('keeps the flag for an end the countdown or a moved alarm fires', () => {+ // fireFromCountdown and updateAlarm build their own intents from the last schedule.+ expect(alert.match(/intent\.putExtra\("vibrate", lastVibrate\);/g)).toHaveLength(2)+ expect(alert).toMatch(/intent\.putExtra\("vibrate", vibrate\);/)+ })})diff --git a/frontend/src/lib/rest-alert.test.js b/frontend/src/lib/rest-alert.test.jsindex 2bf8a60a4..b1ab22717 100644--- a/frontend/src/lib/rest-alert.test.js+++ b/frontend/src/lib/rest-alert.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { armRestAlert, buildRestAlert, disarmRestAlert, REST_ALERT_ID, REST_CHANNEL_ID } from './rest-alert.js'+import { armRestAlert, buildRestAlert, disarmRestAlert, REST_ALERT_ID, REST_CHANNEL_ID, REST_QUIET_CHANNEL_ID } from './rest-alert.js'describe('buildRestAlert', () => {const now = 1_700_000_000_000@@ -31,6 +31,14 @@ describe('buildRestAlert', () => {expect(buildRestAlert({ at: now + 1000, sound: false, now }).sound).toBe(false)})+ // A channel keeps the vibration it was created with, so Vibrate off cannot switch 'rest-over'+ // off: that end goes out on a channel that never buzzes.+ it('buzzes on the rest channel by default, and uses the quiet one when Vibrate is off', () => {+ expect(buildRestAlert({ at: now + 1000, now })).toMatchObject({ vibrate: true, channelId: REST_CHANNEL_ID })+ expect(buildRestAlert({ at: now + 1000, vibrate: false, now })).toMatchObject({ vibrate: false, channelId: REST_QUIET_CHANNEL_ID })+ expect(REST_QUIET_CHANNEL_ID).not.toBe(REST_CHANNEL_ID)+ })+it('refuses a deadline that has already passed', () => {expect(buildRestAlert({ at: now, now })).toBe(null)expect(buildRestAlert({ at: now - 1, now })).toBe(null)diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.jsindex 6de19eb25..74f803eb4 100644--- a/frontend/src/store/useUI.js+++ b/frontend/src/store/useUI.js@@ -21,7 +21,7 @@ const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/pushconst bookRestEnd = (endsAt, totalSec) => {if (!MOBILE) { pushRestTimer(Math.max(1, Math.round((endsAt - Date.now()) / 1000))); return }const { S } = useStore.getState()- armRestAlert(endsAt, { title: t('Rest over — next set!'), countdownTitle: t('Rest'), totalSec, accent: S.accent, sound: !!S.sound })+ armRestAlert(endsAt, { title: t('Rest over — next set!'), countdownTitle: t('Rest'), totalSec, accent: S.accent, sound: !!S.sound, vibrate: S.vibrate !== false }).then(ok => {// Only for the rest that asked: one skipped or moved since then has booked its own end.const tm = useUI.getState().timerdiff --git a/frontend/src/store/useUI.native-rest.test.js b/frontend/src/store/useUI.native-rest.test.jsindex b6ce07f3b..e006f388e 100644--- a/frontend/src/store/useUI.native-rest.test.js+++ b/frontend/src/store/useUI.native-rest.test.js@@ -123,6 +123,17 @@ describe('the rest the app starts, pauses and ends', () => {useUI.getState().startRest(90)expect(armRestAlert).toHaveBeenCalledWith(expect.any(Number), expect.objectContaining({ sound: false }))})++ // Settings → Vibrate off buzzed at the end of every rest the phone was locked for: the page's own+ // buzz was off, but the alarm it armed was never told (Android QA, v1.3.9).+ it('tells the alarm whether the end may buzz', () => {+ useUI.getState().startRest(90)+ expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ vibrate: true }))+ useUI.getState().stopRest()+ useStore.setState({ S: { ...useStore.getState().S, vibrate: false } })+ useUI.getState().startRest(90)+ expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ vibrate: false }))+ })})describe('the server push in the Android app', () => {