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
This commit is contained in:
Sebastian G committed 2026-09-04 13:00:25 +02:00
1 parent d6f0db9b4b
commit 106a3abee0
3 files changed
+338

No files matched your search

+106
View File
@@ -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.')
}
}
+145
View File
@@ -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)
})
})