Skip to content

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.

android: the in-app update opens the installer once openGym is back in front, reuses a verified APK, cleans it up

Duarte Santos2479b4b50521
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2754c6335..71920c71e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -108,6 +108,12 @@ per muscle. Settings → Workout → Fine-tuning turns it off.
- **Hej, Sverige!** openGym speaks Swedish now, picked in Settings → Units & language or straight
from a Swedish phone (#721, thanks @Grizzly163). Exercise names and instructions stay in English
for now.
+- **The Android update actually installs.** Switch to another app while the new APK comes down
+ and Android quietly refused to open the installer, so the download finished and nothing
+ happened. Now the installer waits until you're back in openGym. Tap the update again after a
+ hiccup and it reuses the APK it already has instead of fetching 300 MB twice, and the leftover
+ APK is cleaned up once you're on the new version. (The fix lives in the updater itself, so it
+ helps from the update after 1.4.3 on: for this one, keep openGym open while it downloads.)
**Security.** Follow-ups to v1.4.2's audit.
- **Pairing the phone app asks you to confirm it's you** (passkey, or your password where that
diff --git a/frontend/src/lib/apk-variant.js b/frontend/src/lib/apk-variant.js
new file mode 100644
index 000000000..3e1034d09
--- /dev/null
+++ b/frontend/src/lib/apk-variant.js
@@ -0,0 +1,16 @@
+// Which of the sideloaded APKs this is: Standard (180 px built in), Plus (240 px) or HD (360 px).
+// The same app each time, only the exercise animations inside differ (scripts/android/build-release.sh
+// sets VITE_APK_VARIANT with VITE_BUILTIN_CLIP_PX). lib/update.js updates each kind only to
+// itself; Settings → About shows which one a phone has. Its own module so the About page can read
+// it without the updater.
+import { BUILTIN_PX } from './anim-quality.js'
+
+const ENV = import.meta.env || {}
+export const APK_VARIANTS = ['standard', 'plus', 'hd']
+/** A build without VITE_APK_VARIANT goes by what it has built in. */
+export const variantFor = (env, px = BUILTIN_PX) => APK_VARIANTS.includes(env)
+ ? env
+ : (px >= 360 ? 'hd' : px > 180 ? 'plus' : 'standard')
+export const APK_VARIANT = variantFor(ENV.VITE_APK_VARIANT)
+/** The kind's name as the download page and the file names call it. */
+export const VARIANT_NAMES = { standard: 'Standard', plus: 'Plus', hd: 'HD' }
diff --git a/frontend/src/lib/apk-variant.test.js b/frontend/src/lib/apk-variant.test.js
new file mode 100644
index 000000000..cdec7b733
--- /dev/null
+++ b/frontend/src/lib/apk-variant.test.js
@@ -0,0 +1,19 @@
+import { describe, it, expect } from 'vitest'
+import { variantFor, APK_VARIANT, VARIANT_NAMES } from './apk-variant.js'
+
+describe('apk-variant: which sideloaded APK this is', () => {
+ it('takes the kind the release build names', () => {
+ expect(variantFor('hd', 180)).toBe('hd')
+ expect(variantFor('plus', 180)).toBe('plus')
+ })
+ it('without one, goes by the animations built in', () => {
+ expect(variantFor(undefined, 180)).toBe('standard')
+ expect(variantFor(undefined, 240)).toBe('plus')
+ expect(variantFor(undefined, 360)).toBe('hd')
+ expect(variantFor('nonsense', 360)).toBe('hd')
+ })
+ it('a test build is Standard, and every kind has the name the download page uses', () => {
+ expect(APK_VARIANT).toBe('standard')
+ expect(VARIANT_NAMES).toEqual({ standard: 'Standard', plus: 'Plus', hd: 'HD' })
+ })
+})
diff --git a/frontend/src/lib/update.install.test.js b/frontend/src/lib/update.install.test.js
new file mode 100644
index 000000000..5f79ff921
--- /dev/null
+++ b/frontend/src/lib/update.install.test.js
@@ -0,0 +1,120 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// The Android half of the updater: download the APK natively, then hand it to the Install plugin.
+// The plugins are stand-ins; what is checked is the order of things and when the installer opens.
+const m = vi.hoisted(() => ({
+ active: true, appListeners: [], calls: [],
+ installApk: null, downloadFile: null, deleteFile: null,
+}))
+vi.mock('./mobile.js', () => ({ MOBILE: true }))
+vi.mock('@capacitor/core', () => ({ registerPlugin: () => ({ installApk: a => m.installApk(a) }) }))
+vi.mock('@capacitor/filesystem', () => ({
+ Directory: { Cache: 'CACHE' },
+ Encoding: { UTF8: 'utf8' },
+ Filesystem: {
+ addListener: () => Promise.resolve({ remove: () => Promise.resolve() }),
+ downloadFile: a => m.downloadFile(a),
+ deleteFile: a => m.deleteFile(a),
+ },
+}))
+vi.mock('@capacitor/app', () => ({
+ App: {
+ getState: () => Promise.resolve({ isActive: m.active }),
+ addListener: (ev, fn) => { m.appListeners.push(fn); return Promise.resolve({ remove: () => { m.appListeners = m.appListeners.filter(f => f !== fn) } }) },
+ },
+}))
+
+import { downloadAndInstall, whenInForeground, forgetDownloadedUpdate } from './update.js'
+
+const HASH = 'a'.repeat(64)
+const tick = async (n = 10) => { for (let i = 0; i < n; i++) await Promise.resolve() }
+const comeBack = () => { m.active = true; for (const fn of [...m.appListeners]) fn({ isActive: true }) }
+
+beforeEach(() => {
+ m.active = true; m.appListeners = []; m.calls = []
+ // Nothing in the cache yet: the plugin refuses the first call, as InstallPlugin.java does.
+ m.cached = false
+ m.installApk = vi.fn(async a => {
+ m.calls.push('install')
+ if (!m.cached) throw new Error('APK file not found: ' + a.fileName)
+ })
+ m.downloadFile = vi.fn(async () => { m.calls.push('download'); m.cached = true })
+ m.deleteFile = vi.fn(async () => {})
+})
+
+describe('downloadAndInstall (Android)', () => {
+ it('opens the installer only once openGym is back in front (lampi_: downloaded, never installed)', async () => {
+ // The person switched apps while the APK came down: Android would block the installer.
+ m.downloadFile = vi.fn(async () => { m.calls.push('download'); m.cached = true; m.active = false })
+ let done = false
+ const run = downloadAndInstall('https://x/openGym-9.9.9.apk', HASH).then(() => { done = true })
+ await vi.waitFor(() => expect(m.appListeners).toHaveLength(1))
+ await tick(30)
+ expect(m.calls).toEqual(['install', 'download']) // the cache check, then the download
+ expect(done).toBe(false)
+ comeBack()
+ await run
+ expect(m.calls).toEqual(['install', 'download', 'install'])
+ expect(m.installApk).toHaveBeenLastCalledWith({ fileName: 'opengym-update.apk', sha256: HASH })
+ expect(m.appListeners).toHaveLength(0) // the listener is gone again
+ })
+
+ it('in front all along: downloads and opens the installer straight away', async () => {
+ await downloadAndInstall('https://x/a.apk', HASH.toUpperCase())
+ expect(m.calls).toEqual(['install', 'download', 'install'])
+ expect(m.installApk).toHaveBeenLastCalledWith({ fileName: 'opengym-update.apk', sha256: HASH })
+ })
+
+ it('an APK already downloaded and matching is installed again without a second download', async () => {
+ m.installApk = vi.fn(async () => { m.calls.push('install') })
+ await downloadAndInstall('https://x/a.apk', HASH)
+ expect(m.calls).toEqual(['install'])
+ expect(m.downloadFile).not.toHaveBeenCalled()
+ })
+
+ it('a failed install after the download still reaches the caller', async () => {
+ m.installApk = vi.fn(async () => { throw new Error('SHA-256 mismatch') })
+ await expect(downloadAndInstall('https://x/a.apk', HASH)).rejects.toThrow('SHA-256 mismatch')
+ expect(m.downloadFile).toHaveBeenCalledTimes(1)
+ })
+
+ it('never without a checksum', async () => {
+ await expect(downloadAndInstall('https://x/a.apk', null)).rejects.toThrow(/checksum/)
+ expect(m.installApk).not.toHaveBeenCalled()
+ expect(m.downloadFile).not.toHaveBeenCalled()
+ })
+})
+
+describe('whenInForeground', () => {
+ it('resolves at once when the app is in front, or when its state cannot be read', async () => {
+ await whenInForeground({ getState: async () => ({ isActive: true }), addListener: vi.fn() })
+ await whenInForeground({ getState: async () => { throw new Error('no plugin') }, addListener: vi.fn() })
+ })
+
+ it('in the background: waits for the app to become active', async () => {
+ let fire = null
+ const app = {
+ getState: vi.fn(async () => ({ isActive: false })),
+ addListener: vi.fn((ev, fn) => { fire = fn; return Promise.resolve({ remove: vi.fn() }) }),
+ }
+ let done = false
+ const p = whenInForeground(app).then(() => { done = true })
+ await tick()
+ expect(done).toBe(false)
+ fire({ isActive: false })
+ await tick()
+ expect(done).toBe(false)
+ fire({ isActive: true })
+ await p
+ expect(app.addListener).toHaveBeenCalledWith('appStateChange', expect.any(Function))
+ })
+})
+
+describe('forgetDownloadedUpdate', () => {
+ it('deletes the update APK from the cache, and is quiet when there is none', async () => {
+ await forgetDownloadedUpdate()
+ expect(m.deleteFile).toHaveBeenCalledWith({ path: 'opengym-update.apk', directory: 'CACHE' })
+ m.deleteFile = vi.fn(async () => { throw new Error('File does not exist') })
+ await expect(forgetDownloadedUpdate()).resolves.toBeUndefined()
+ })
+})
diff --git a/frontend/src/lib/update.js b/frontend/src/lib/update.js
index f821fcf36..5e7e9af4a 100644
--- a/frontend/src/lib/update.js
+++ b/frontend/src/lib/update.js
@@ -10,7 +10,7 @@
// against its SHA-256 by the native Install plugin and handed to the system installer.
import { MOBILE } from './mobile.js'
-import { BUILTIN_PX } from './anim-quality.js'
+import { APK_VARIANTS, APK_VARIANT } from './apk-variant.js'
const REPO = 'DuarteSantos8/openGym'
const LATEST_URL = `https://api.github.com/repos/${REPO}/releases/latest`
@@ -73,19 +73,14 @@ async function fetchLatest() {
* built in: Standard (180 px, openGym-<v>.apk), Plus (240 px, openGym-Plus-<v>.apk) and HD
* (360 px, openGym-HD-<v>.apk). Each installed APK only ever updates to its own kind, so a phone
* that picked HD keeps HD, and nobody is handed a download twice the size they never asked for.
- * The build says which kind it is (VITE_APK_VARIANT, set by scripts/android/build-release.sh); a
- * build without it goes by what it has built in.
+ * The build says which kind it is (lib/apk-variant.js).
* The checksum is the one named after the chosen APK, never just the first .sha256 in the list.
* A release without an APK of this kind: no direct download (the update row then opens the
* releases page), rather than quietly swapping it for another kind.
* Phones from before v1.4.2 take the first .apk of the list, and GitHub sorts assets by name:
* "openGym-1…" comes before "openGym-HD-…" and "openGym-Plus-…", so they land on Standard.
*/
-const ENV = import.meta.env || {}
-export const APK_VARIANTS = ['standard', 'plus', 'hd']
-export const APK_VARIANT = APK_VARIANTS.includes(ENV.VITE_APK_VARIANT)
- ? ENV.VITE_APK_VARIANT
- : (BUILTIN_PX >= 360 ? 'hd' : BUILTIN_PX > 180 ? 'plus' : 'standard')
+export { APK_VARIANTS, APK_VARIANT }
const tagged = (name, tag) => new RegExp(`(^|[-_.])${tag}([-_.]|$)`, 'i').test(name)
/** Which kind an APK file name is: 'hd', 'plus' or 'standard'. */
export const apkKind = name => tagged(name, 'hd') ? 'hd' : tagged(name, 'plus') ? 'plus' : 'standard'
@@ -124,11 +119,43 @@ export async function sha256(buffer) {
return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, '0')).join('')
}
+const UPDATE_FILE = 'opengym-update.apk'
+
+/**
+ * Resolves once openGym is the app in front. The package installer is an activity, and Android
+ * (10 and later) does not let an app start one from the background: it refuses without a word.
+ * The APK is 300 to 760 MB, plenty of time to switch to another app while it comes down, and then
+ * the download finished, the installer never opened and the progress sheet just closed. So the
+ * installer waits for the person to come back. `app` is @capacitor/app (injected in tests).
+ */
+export async function whenInForeground(app) {
+ const App = app || (await import('@capacitor/app')).App
+ try { if ((await App.getState())?.isActive !== false) return } catch { return }
+ await new Promise(resolve => {
+ let handle = null, done = false
+ const finish = () => { if (done) return; done = true; Promise.resolve(handle).then(h => h?.remove?.()).catch(() => {}); resolve() }
+ // The listener first, then a second look: the app may have come back in between.
+ handle = Promise.resolve(App.addListener('appStateChange', st => { if (st?.isActive) finish() })).catch(() => { finish(); return null })
+ Promise.resolve(App.getState()).then(st => { if (st?.isActive) finish() }).catch(() => {})
+ })
+}
+
+const installPlugin = async () => {
+ const { registerPlugin } = await import('@capacitor/core')
+ // Handed out inside an object: a plugin proxy answers `then`, and a promise resolved with
+ // the bare proxy never settles (#42).
+ return { Install: registerPlugin('Install') }
+}
+
/**
* Downloads the APK from `url` into the cache directory, natively and straight to disk, and
* hands it to the Install plugin, which checks it against `expectedHash` before the installer
* opens. Only works on the MOBILE (Capacitor) build with Android.
*
+ * An APK that already came down and matches the hash (the installer did not show the last time,
+ * or was dismissed) is installed again without downloading it twice. One that does not match is
+ * deleted by the plugin and downloaded afresh.
+ *
* @param {string} url - Direct download URL for the APK
* @param {string} expectedHash - Expected SHA-256 hex string (from the .sha256 asset)
* @param {function|null} onProgress - Called with (received, total) bytes during download, or null
@@ -139,19 +166,35 @@ export async function downloadAndInstall(url, expectedHash, onProgress = null) {
return
}
if (!/^[0-9a-f]{64}$/i.test(expectedHash || '')) throw new Error('no checksum to verify the download against')
+ const sha256 = expectedHash.toLowerCase()
+ const { Install } = await installPlugin()
+ // The Install plugin streams the file through SHA-256 natively (300 MB never enter the
+ // WebView) and refuses a mismatch, or a missing file, before the installer opens.
+ try {
+ await Install.installApk({ fileName: UPDATE_FILE, sha256 })
+ return
+ } catch { /* nothing usable in the cache yet: download it */ }
const { Filesystem, Directory } = await import('@capacitor/filesystem')
- const fileName = 'opengym-update.apk'
const listener = onProgress
? await Filesystem.addListener('progress', p => onProgress(p.bytes, p.contentLength))
: null
try {
- await Filesystem.downloadFile({ url, path: fileName, directory: Directory.Cache, progress: !!onProgress })
+ await Filesystem.downloadFile({ url, path: UPDATE_FILE, directory: Directory.Cache, progress: !!onProgress })
} finally {
await listener?.remove()
}
- // The Install plugin streams the file through SHA-256 natively (300 MB never enter the
- // WebView) and refuses a mismatch before the installer opens.
- const { registerPlugin } = await import('@capacitor/core')
- const Install = registerPlugin('Install')
- await Install.installApk({ fileName, sha256: expectedHash.toLowerCase() })
+ await whenInForeground()
+ await Install.installApk({ fileName: UPDATE_FILE, sha256 })
+}
+
+/**
+ * Deletes a downloaded update once there is nothing newer to install: the APK stays in the cache
+ * after the update went in (the new app keeps the old cache), 300 to 760 MB of it.
+ */
+export async function forgetDownloadedUpdate() {
+ if (!MOBILE) return
+ try {
+ const { Filesystem, Directory } = await import('@capacitor/filesystem')
+ await Filesystem.deleteFile({ path: UPDATE_FILE, directory: Directory.Cache })
+ } catch { /* none there */ }
}
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 924d6fc4d..eec60d78a 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -32,7 +32,7 @@ import { getMediaStatus, subscribeMediaStatus, pendingRefCount } from '../lib/me
import { limitsFrom, fmtMB, MB } from '../lib/media-limits.js'
import { setRestAccent } from '../lib/rest-alert.js'
import { CUSTOM, accentKey, adjustedIn, applyAccent, cleanHex, inkOn, isGrey } from '../lib/accent.js'
-import { checkForUpdate, downloadAndInstall, fetchChecksum, RELEASES_PAGE } from '../lib/update.js'
+import { checkForUpdate, downloadAndInstall, fetchChecksum, forgetDownloadedUpdate, RELEASES_PAGE } from '../lib/update.js'
import { selfUpdates } from '../lib/channel.js'
import { forgetCoach } from '../lib/coach-api.js'
import { REST_MAX, REST_PAUSE_MIN, REST_PAUSE_MAX, fmtRest, fmtDuration } from '../lib/duration.js'
@@ -191,7 +191,8 @@ export default function Settings({ page = null, find = null, via = null, entryKe
setIos(!ok)
const own = ok && await selfUpdates()
setSelfUpdate(own)
- if (own && page === 'about') checkForUpdate().then(setUpdateInfo).catch(() => {})
+ // Nothing newer: an update APK still in the cache is the one already installed.
+ if (own && page === 'about') checkForUpdate().then(info => { setUpdateInfo(info); if (!info?.hasUpdate) forgetDownloadedUpdate() }).catch(() => {})
})
}, [page])
@@ -235,7 +236,7 @@ export default function Settings({ page = null, find = null, via = null, entryKe
try {
const info = await checkForUpdate()
setUpdateInfo(info)
- if (!info.hasUpdate) toast(t('You have the latest version.'))
+ if (!info.hasUpdate) { toast(t('You have the latest version.')); forgetDownloadedUpdate() }
} catch {
toast(t('Couldn’t check for updates. Are you online?'))
}
diff --git a/frontend/src/views/Settings.update.test.jsx b/frontend/src/views/Settings.update.test.jsx
index 3aad9b73c..4eeef76a3 100644
--- a/frontend/src/views/Settings.update.test.jsx
+++ b/frontend/src/views/Settings.update.test.jsx
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => {
})
state.checkForUpdate = vi.fn(() => Promise.resolve({ hasUpdate: true, latestVersion: '9.9.9', apkUrl: 'https://x/opengym.apk', hashUrl: null }))
state.confirmSheet = vi.fn()
+ state.forget = vi.fn()
return state
})
vi.mock('../store/useStore.js', () => {
@@ -53,6 +54,7 @@ vi.mock('../lib/mobile.js', () => ({
vi.mock('../lib/update.js', () => ({
checkForUpdate: (...a) => mocks.checkForUpdate(...a),
downloadAndInstall: vi.fn(),
+ forgetDownloadedUpdate: (...a) => mocks.forget(...a),
}))
vi.mock('../lib/channel.js', () => ({ selfUpdates: () => Promise.resolve(mocks.channel === 'sideload') }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
@@ -74,6 +76,7 @@ beforeEach(() => {
mocks.channel = 'sideload'
mocks.checkForUpdate.mockClear()
mocks.confirmSheet.mockClear()
+ mocks.forget.mockClear()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
@@ -153,4 +156,17 @@ describe('Settings — in-app update check', () => {
expect(updateRow()).toBeUndefined()
expect(checkRow()).toBeTruthy()
})
+
+ it('Android: a downloaded APK left in the cache is deleted once nothing newer is out, and kept while one is', async () => {
+ mocks.MOBILE = true
+ mocks.android = true
+ await mount()
+ expect(mocks.forget).not.toHaveBeenCalled() // 9.9.9 is waiting: its APK may be the one in the cache
+ act(() => root.unmount())
+ root = createRoot(host)
+ mocks.checkForUpdate.mockResolvedValueOnce({ hasUpdate: false, latestVersion: 'test', apkUrl: null, hashUrl: null })
+ await mount()
+ expect(mocks.forget).toHaveBeenCalledTimes(1)
+ })
})
+