From 106a3abee042bc93df053ad5c27830bd99461c46 Mon Sep 17 00:00:00 2001 From: Sebastian G Date: Wed, 26 Aug 2026 16:09:46 +0200 Subject: [PATCH] feat: add update check in settings Check GitLab releases API on settings open to determine if a newer version is available. Shows current version (up to date) or the new version number with download/install action. - New lib/update.js: checkForUpdate(), downloadAndInstall() - Settings Data section: update row with auto-check on mount - Dialog for re-check confirmation when already up to date - APK download + installer trigger on Android via Capacitor - Falls back to opening releases page on web - 16 unit tests for version check logic --- frontend/src/lib/update.js | 106 +++++++++++++++++++++++ frontend/src/lib/update.test.js | 145 ++++++++++++++++++++++++++++++++ frontend/src/views/Settings.jsx | 87 +++++++++++++++++++ 3 files changed, 338 insertions(+) create mode 100644 frontend/src/lib/update.js create mode 100644 frontend/src/lib/update.test.js diff --git a/frontend/src/lib/update.js b/frontend/src/lib/update.js new file mode 100644 index 0000000..a28b774 --- /dev/null +++ b/frontend/src/lib/update.js @@ -0,0 +1,106 @@ +// Update check — compares the installed version (__APP_VERSION__) against +// the latest release tag on GitLab and optionally downloads + installs the APK. +// +// The GitLab releases API is public for this project, so no token is needed. +// On Android (Capacitor), the APK asset is downloaded to the cache directory +// and handed to the system installer via a content:// URI. + +import { MOBILE } from './mobile.js' + +const GITLAB_PROJECT_ID = 'DuarteSantos8%2Fopengym' +const RELEASES_URL = `https://gitlab.com/api/v4/projects/${GITLAB_PROJECT_ID}/releases` + +/** + * Compares two semver strings (e.g. "1.2.11" vs "1.3.0"). + * Returns 1 if a > b, -1 if a < b, 0 if equal. + */ +function compareSemver(a, b) { + const pa = a.replace(/^v/, '').split('.').map(Number) + const pb = b.replace(/^v/, '').split('.').map(Number) + for (let i = 0; i < 3; i++) { + const diff = (pa[i] || 0) - (pb[i] || 0) + if (diff > 0) return 1 + if (diff < 0) return -1 + } + return 0 +} + +/** + * Checks the GitLab releases API for a newer version. + * Returns { hasUpdate, latestVersion, apkUrl } or throws on network failure. + * - hasUpdate: true if the latest release tag is newer than the running build + * - latestVersion: the semver string of the latest release (without "v" prefix) + * - apkUrl: direct download URL of the first .apk asset, or null + */ +export async function checkForUpdate() { + const res = await fetch(RELEASES_URL + '?per_page=1') + if (!res.ok) throw new Error(`GitLab API ${res.status}`) + const releases = await res.json() + if (!releases.length) return { hasUpdate: false, latestVersion: __APP_VERSION__, apkUrl: null } + + const latest = releases[0] + const latestVersion = latest.tag_name.replace(/^v/, '') + const hasUpdate = compareSemver(latestVersion, __APP_VERSION__) > 0 + + // Find the APK asset among the release links (generic package links) or assets.sources + let apkUrl = null + if (latest.assets?.links?.length) { + const apkLink = latest.assets.links.find(l => /\.apk$/i.test(l.url) || /\.apk$/i.test(l.direct_asset_url)) + if (apkLink) apkUrl = apkLink.direct_asset_url || apkLink.url + } + + return { hasUpdate, latestVersion, apkUrl } +} + +/** + * Downloads the APK from `url` and triggers the Android installer. + * Only works on the MOBILE (Capacitor) build with Android. + */ +export async function downloadAndInstall(url) { + if (!MOBILE) { + // On web, just open the release page + window.open('https://gitlab.com/DuarteSantos8/opengym/-/releases', '_blank', 'noopener') + return + } + + const { Filesystem, Directory } = await import('@capacitor/filesystem') + + // Download the file as a blob, then write to cache as base64 + const res = await fetch(url) + if (!res.ok) throw new Error(`Download failed: ${res.status}`) + const blob = await res.blob() + + // Convert blob to base64 + const base64 = await new Promise((resolve, reject) => { + const reader = new FileReader() + reader.onload = () => resolve(reader.result.split(',')[1]) + reader.onerror = reject + reader.readAsDataURL(blob) + }) + + const fileName = 'opengym-update.apk' + const written = await Filesystem.writeFile({ + path: fileName, + directory: Directory.Cache, + data: base64, + }) + + // Use the Capacitor App plugin or an intent to open the APK for installation. + // FileOpener is not bundled, so we use the @capacitor/filesystem URI with an intent. + // The approach: open the file URI which triggers the Android package installer. + const { App: CapApp } = await import('@capacitor/app') + // Capacitor's Filesystem.getUri gives us the content URI needed for install + const { uri } = await Filesystem.getUri({ path: fileName, directory: Directory.Cache }) + + // On Android, we need to trigger an install intent. Since we don't have a dedicated + // plugin, we open the URI which — on Android with the right content type — prompts install. + // Use the native intent via a custom URL scheme or window.open as fallback. + try { + // Try using the Capacitor App plugin to open the URI + // This works if the device has a handler for APK content URIs + window.open(uri, '_system') + } catch (e) { + // Fallback: just inform the user where the file is + throw new Error('APK downloaded but could not start installer. Check your Downloads folder.') + } +} diff --git a/frontend/src/lib/update.test.js b/frontend/src/lib/update.test.js new file mode 100644 index 0000000..675c01d --- /dev/null +++ b/frontend/src/lib/update.test.js @@ -0,0 +1,145 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { checkForUpdate } from './update.js' + +// __APP_VERSION__ is defined at build time by vite.config.js (reads package.json). +// In the test environment vitest applies the same define, so it's available here. + +describe('checkForUpdate', () => { + let originalFetch + + beforeEach(() => { originalFetch = globalThis.fetch }) + afterEach(() => { globalThis.fetch = originalFetch }) + + function mockFetch(body, status = 200) { + globalThis.fetch = vi.fn(() => Promise.resolve({ + ok: status >= 200 && status < 300, + status, + json: () => Promise.resolve(body), + })) + } + + it('reports no update when the latest release matches the current version', async () => { + mockFetch([{ tag_name: 'v' + __APP_VERSION__, assets: { links: [] } }]) + const result = await checkForUpdate() + expect(result.hasUpdate).toBe(false) + expect(result.latestVersion).toBe(__APP_VERSION__) + expect(result.apkUrl).toBe(null) + }) + + it('reports no update when the latest release is older than current', async () => { + mockFetch([{ tag_name: 'v0.0.1', assets: { links: [] } }]) + const result = await checkForUpdate() + expect(result.hasUpdate).toBe(false) + expect(result.latestVersion).toBe('0.0.1') + }) + + it('reports an update when the latest release is newer', async () => { + mockFetch([{ tag_name: 'v99.0.0', assets: { links: [] } }]) + const result = await checkForUpdate() + expect(result.hasUpdate).toBe(true) + expect(result.latestVersion).toBe('99.0.0') + }) + + it('strips the v prefix from the tag name', async () => { + mockFetch([{ tag_name: 'v99.1.2', assets: { links: [] } }]) + const result = await checkForUpdate() + expect(result.latestVersion).toBe('99.1.2') + }) + + it('handles tag names without a v prefix', async () => { + mockFetch([{ tag_name: '99.0.0', assets: { links: [] } }]) + const result = await checkForUpdate() + expect(result.hasUpdate).toBe(true) + expect(result.latestVersion).toBe('99.0.0') + }) + + it('finds the APK download URL from release asset links', async () => { + const apkUrl = 'https://gitlab.com/project/-/releases/v2.0.0/downloads/opengym.apk' + mockFetch([{ + tag_name: 'v99.0.0', + assets: { links: [{ url: apkUrl, direct_asset_url: apkUrl }] } + }]) + const result = await checkForUpdate() + expect(result.apkUrl).toBe(apkUrl) + }) + + it('prefers direct_asset_url over url for APK links', async () => { + mockFetch([{ + tag_name: 'v99.0.0', + assets: { + links: [{ + url: 'https://redirect.example/opengym.apk', + direct_asset_url: 'https://direct.example/opengym.apk' + }] + } + }]) + const result = await checkForUpdate() + expect(result.apkUrl).toBe('https://direct.example/opengym.apk') + }) + + it('returns null apkUrl when no .apk link exists', async () => { + mockFetch([{ + tag_name: 'v99.0.0', + assets: { links: [{ url: 'https://example.com/changelog.md', direct_asset_url: 'https://example.com/changelog.md' }] } + }]) + const result = await checkForUpdate() + expect(result.hasUpdate).toBe(true) + expect(result.apkUrl).toBe(null) + }) + + it('returns no update when the releases array is empty', async () => { + mockFetch([]) + const result = await checkForUpdate() + expect(result.hasUpdate).toBe(false) + expect(result.latestVersion).toBe(__APP_VERSION__) + }) + + it('throws when the API responds with an error status', async () => { + mockFetch(null, 500) + await expect(checkForUpdate()).rejects.toThrow('GitLab API 500') + }) + + it('throws on network failure', async () => { + globalThis.fetch = vi.fn(() => Promise.reject(new Error('Network error'))) + await expect(checkForUpdate()).rejects.toThrow('Network error') + }) +}) + +describe('semver comparison (via checkForUpdate behavior)', () => { + let originalFetch + beforeEach(() => { originalFetch = globalThis.fetch }) + afterEach(() => { globalThis.fetch = originalFetch }) + + function mockRelease(tag) { + globalThis.fetch = vi.fn(() => Promise.resolve({ + ok: true, status: 200, + json: () => Promise.resolve([{ tag_name: tag, assets: { links: [] } }]), + })) + } + + // __APP_VERSION__ is "1.2.11" — test that patch, minor, and major bumps are detected + it('detects a patch bump as an update', async () => { + mockRelease('v1.2.12') + expect((await checkForUpdate()).hasUpdate).toBe(true) + }) + + it('detects a minor bump as an update', async () => { + mockRelease('v1.3.0') + expect((await checkForUpdate()).hasUpdate).toBe(true) + }) + + it('detects a major bump as an update', async () => { + mockRelease('v2.0.0') + expect((await checkForUpdate()).hasUpdate).toBe(true) + }) + + it('does not flag an older patch as an update', async () => { + mockRelease('v1.2.10') + expect((await checkForUpdate()).hasUpdate).toBe(false) + }) + + it('does not flag an older minor as an update', async () => { + mockRelease('v1.1.99') + expect((await checkForUpdate()).hasUpdate).toBe(false) + }) +}) diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index 5b94d06..3c5a60c 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -10,6 +10,7 @@ import { wakeLockSupported } from '../lib/wakelock.js' import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js' import { DEMO, REPO } from '../lib/demo.js' import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js' +import { checkForUpdate, downloadAndInstall } from '../lib/update.js' import { ConnectSheet } from './MobileOnboarding.jsx' import { loadStarterPlan, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' @@ -26,6 +27,89 @@ export default function Settings() { const importRef = useRef(null) const wakeOK = wakeLockSupported() + // --- update check state --- + const [updateInfo, setUpdateInfo] = useState(null) // { hasUpdate, latestVersion, apkUrl } | null while loading + const [updateLoading, setUpdateLoading] = useState(true) + const [updateError, setUpdateError] = useState(null) + + const runUpdateCheck = async () => { + setUpdateLoading(true) + setUpdateError(null) + try { + const info = await checkForUpdate() + setUpdateInfo(info) + } catch (e) { + setUpdateError(e.message || 'Check failed') + } finally { + setUpdateLoading(false) + } + } + + useEffect(() => { runUpdateCheck() }, []) + + const onUpdateRowClick = () => { + if (updateLoading) return + if (updateInfo?.hasUpdate && updateInfo.apkUrl) { + // Start download & install + const version = updateInfo.latestVersion + confirmSheet({ + title: t('Update to {0}?', version), + message: t('The latest version will be downloaded and the installer will open.'), + confirmText: t('Download & Install'), + onConfirm: async () => { + toast(t('Downloading update…')) + try { + await downloadAndInstall(updateInfo.apkUrl) + } catch (e) { + toast(t('Update failed: {0}', e.message)) + } + }, + }) + } else if (updateInfo?.hasUpdate && !updateInfo.apkUrl) { + // Update available but no APK asset — open the releases page + window.open('https://gitlab.com/DuarteSantos8/opengym/-/releases', '_blank', 'noopener') + } else { + // Already up to date or error — re-check and show result in a dialog + setUpdateLoading(true) + setUpdateError(null) + checkForUpdate().then(info => { + setUpdateInfo(info) + setUpdateLoading(false) + useUI.getState().openSheet(close => ( +
+

{t('Update check')}

+
+ {info.hasUpdate + ? t('{0} is available!', info.latestVersion) + : t('openGym {0} — you\u2019re up to date.', __APP_VERSION__)} +
+ +
+ ), { kind: 'center' }) + }).catch(e => { + setUpdateError(e.message || 'Check failed') + setUpdateLoading(false) + useUI.getState().openSheet(close => ( +
+

{t('Update check')}

+
+ {t('Could not check for updates: {0}', e.message || 'unknown error')} +
+ +
+ ), { kind: 'center' }) + }) + } + } + + const updateTitle = updateLoading + ? t('Checking for updates…') + : updateError + ? t('Update check failed') + : updateInfo?.hasUpdate + ? t('{0} available', updateInfo.latestVersion) + : t('openGym {0} (up to date)', __APP_VERSION__) + const doExport = async () => { const json = JSON.stringify(S, null, 2) const name = 'opengym-backup-' + todayISO() + '.json' @@ -226,6 +310,9 @@ export default function Settings() { {/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
+