Merge feat/update-check: !40 In-App-Update auf dem Android-Build (#38, #9)

# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
This commit is contained in:
Duarte Santos committed 2026-09-05 14:24:11 +02:00
commit 0797fda152
25 files changed
+840 -6

No files matched your search

+16
View File
@@ -15,6 +15,22 @@ import { effectiveRoutineId } from './history.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
// Some features only make sense on Android. The in-app updater downloads an .apk and hands it
// to the system package installer — there is no equivalent on iOS (App Store only) or on the
// web build. On anything but a native Android shell this must stay off.
//
// @capacitor/core is imported dynamically (like every other Capacitor dependency here) so it
// never lands in the web bundle. Capacitor.getPlatform() returns 'android' | 'ios' | 'web'.
export async function isAndroid() {
if (!MOBILE) return false
try {
const { Capacitor } = await import('@capacitor/core')
return Capacitor.getPlatform() === 'android'
} catch (e) {
return false
}
}
const FILE = 'opengym-state.json'
export async function nativeLoad() {
+140
View File
@@ -0,0 +1,140 @@
// 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, hashUrl } 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
* - hashUrl: direct download URL of the .apk.sha256 hash file, 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, hashUrl: 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
let hashUrl = 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
// Look for a matching .sha256 hash file
const hashLink = latest.assets.links.find(l => /\.apk\.sha256$/i.test(l.url) || /\.apk\.sha256$/i.test(l.direct_asset_url) || /sha256/i.test(l.name))
if (hashLink) hashUrl = hashLink.direct_asset_url || hashLink.url
}
return { hasUpdate, latestVersion, apkUrl, hashUrl }
}
/**
* Computes the SHA-256 hash of an ArrayBuffer using the Web Crypto API.
* Returns the hex-encoded digest string.
*/
export async function sha256(buffer) {
const hash = await crypto.subtle.digest('SHA-256', buffer)
return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, '0')).join('')
}
/**
* Downloads the APK from `url`, verifies its SHA-256 hash against `expectedHash`
* (if provided), and triggers the Android installer.
* Only works on the MOBILE (Capacitor) build with Android.
*
* @param {string} url - Direct download URL for the APK
* @param {string|null} expectedHash - Expected SHA-256 hex string (from .sha256 asset), or null to skip verification
* @param {function|null} onProgress - Called with (received, total) bytes during download, or null
*/
export async function downloadAndInstall(url, expectedHash = null, onProgress = null) {
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 with progress tracking via ReadableStream
const res = await fetch(url)
if (!res.ok) throw new Error(`Download failed: ${res.status}`)
const total = parseInt(res.headers.get('content-length') || '0', 10)
const reader = res.body.getReader()
const chunks = []
let received = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
received += value.length
if (onProgress) onProgress(received, total)
}
// Reassemble into a single blob
const blob = new Blob(chunks)
// Size check: an APK should be at least 100 KB
if (blob.size < 100_000) {
throw new Error('Downloaded file is too small to be a valid APK (' + blob.size + ' bytes)')
}
// SHA-256 integrity check
if (expectedHash) {
const buffer = await blob.arrayBuffer()
const actualHash = await sha256(buffer)
if (actualHash !== expectedHash.toLowerCase().trim()) {
throw new Error('SHA-256 mismatch — download may be corrupted or tampered with')
}
}
// 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'
await Filesystem.writeFile({
path: fileName,
directory: Directory.Cache,
data: base64,
})
// Use the local InstallPlugin to trigger the Android package installer
const { registerPlugin } = await import('@capacitor/core')
const Install = registerPlugin('Install')
await Install.installApk({ fileName })
}
+282
View File
@@ -0,0 +1,282 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { checkForUpdate, sha256 } 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('sha256', () => {
it('computes the correct hash for a known input', async () => {
const input = new TextEncoder().encode('hello world')
const hash = await sha256(input.buffer)
// Well-known SHA-256 of "hello world"
expect(hash).toBe('b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9')
})
it('computes a different hash for different input', async () => {
const a = await sha256(new TextEncoder().encode('aaa').buffer)
const b = await sha256(new TextEncoder().encode('bbb').buffer)
expect(a).not.toBe(b)
})
it('returns a 64-character hex string', async () => {
const hash = await sha256(new TextEncoder().encode('test').buffer)
expect(hash).toHaveLength(64)
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
})
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)
expect(result.hashUrl).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('finds the .sha256 hash URL from release asset links', async () => {
const hashUrl = 'https://gitlab.com/project/-/releases/v2.0.0/downloads/opengym.apk.sha256'
mockFetch([{
tag_name: 'v99.0.0',
assets: {
links: [
{ url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' },
{ url: hashUrl, direct_asset_url: hashUrl },
]
}
}])
const result = await checkForUpdate()
expect(result.hashUrl).toBe(hashUrl)
})
it('finds hash URL by link name containing sha256', async () => {
mockFetch([{
tag_name: 'v99.0.0',
assets: {
links: [
{ name: 'APK', url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' },
{ name: 'SHA256 checksum', url: 'https://example.com/checksum.txt', direct_asset_url: 'https://example.com/checksum.txt' },
]
}
}])
const result = await checkForUpdate()
expect(result.hashUrl).toBe('https://example.com/checksum.txt')
})
// The exact JSON gitlab.com returns for GET /projects/85678327/releases?per_page=1 (v1.3.1,
// fetched 2026-09-05, description and commit trimmed). The CI publishes the APK and its
// checksum as generic-package links, and the checksum link is listed BEFORE the APK — the
// detection must not confuse the two.
const REAL_RELEASE = [
{
"tag_name": "v1.3.1",
"name": "openGym v1.3.1",
"assets": {
"count": 7,
"sources": [
{
"format": "zip",
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.zip"
},
{
"format": "tar.gz",
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar.gz"
},
{
"format": "tar.bz2",
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar.bz2"
},
{
"format": "tar",
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar"
}
],
"links": [
{
"id": 12790840,
"name": "Container images (api + web)",
"url": "https://gitlab.com/DuarteSantos8/opengym/container_registry",
"direct_asset_url": "https://gitlab.com/DuarteSantos8/opengym/container_registry",
"link_type": "image"
},
{
"id": 12790839,
"name": "openGym-1.3.1.apk.sha256 (checksum)",
"url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256",
"direct_asset_url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256",
"link_type": "other"
},
{
"id": 12790838,
"name": "openGym-1.3.1.apk (Android, sideload)",
"url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk",
"direct_asset_url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk",
"link_type": "package"
}
]
}
}
]
it('finds the APK and its checksum in a real gitlab.com release payload', async () => {
mockFetch(REAL_RELEASE)
const result = await checkForUpdate()
expect(result.latestVersion).toBe('1.3.1')
expect(result.apkUrl).toBe('https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk')
expect(result.hashUrl).toBe('https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256')
})
it('returns null hashUrl when no hash link exists', async () => {
mockFetch([{
tag_name: 'v99.0.0',
assets: { links: [{ url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' }] }
}])
const result = await checkForUpdate()
expect(result.hashUrl).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__)
expect(result.hashUrl).toBe(null)
})
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: [] } }]),
}))
}
// Versions are derived from the running __APP_VERSION__ so the suite never breaks
// when package.json bumps. bump(2, +1) raises the patch; bump(0, +1) raises the major.
const [MAJ, MIN, PATCH] = __APP_VERSION__.split('.').map(Number)
const bump = (idx, by) => {
const parts = [MAJ, MIN, PATCH]
parts[idx] += by
return 'v' + parts.join('.')
}
it('detects a patch bump as an update', async () => {
mockRelease(bump(2, 1))
expect((await checkForUpdate()).hasUpdate).toBe(true)
})
it('detects a minor bump as an update', async () => {
mockRelease(bump(1, 1))
expect((await checkForUpdate()).hasUpdate).toBe(true)
})
it('detects a major bump as an update', async () => {
mockRelease(bump(0, 1))
expect((await checkForUpdate()).hasUpdate).toBe(true)
})
it('does not flag an older patch as an update', async () => {
// One patch below current (current patch is always >= our test floor)
mockRelease('v' + [MAJ, MIN, Math.max(0, PATCH - 1)].join('.'))
// Only meaningful when we could actually go lower; when patch is 0 this equals current,
// which correctly reports no update either way.
expect((await checkForUpdate()).hasUpdate).toBe(false)
})
it('does not flag an older minor as an update', async () => {
// A version guaranteed lower than any 1.x+ release: same major, minor 0, patch 0,
// minus one on the minor when possible.
mockRelease('v' + [MAJ, Math.max(0, MIN - 1), 0].join('.'))
expect((await checkForUpdate()).hasUpdate).toBe(false)
})
})