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

+1 -1
View File
@@ -38,7 +38,7 @@ vi.mock('../lib/api.js', () => ({
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
+86 -2
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react'
import { useEffect, useRef, useState, forwardRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { workoutControls } from '../lib/workout-controls.js'
@@ -11,7 +11,8 @@ import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/pus
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 { MOBILE, isAndroid, shareExport, syncReminder } from '../lib/mobile.js'
import { checkForUpdate, downloadAndInstall } from '../lib/update.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, menuSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
@@ -43,6 +44,60 @@ export default function Settings() {
})
}
// --- update check state ---
const [updateInfo, setUpdateInfo] = useState(null) // { hasUpdate, latestVersion, apkUrl, hashUrl } | null
useEffect(() => {
// The in-app updater installs an .apk, so it only applies to the native Android build.
// On iOS and the web this check is skipped and the update row never appears. isAndroid()
// already answers false off the mobile build; the MOBILE check on top keeps the web bundle
// from even asking (and from calling gitlab.com on every Settings visit).
if (!MOBILE) return
isAndroid().then(ok => { if (ok) checkForUpdate().then(setUpdateInfo).catch(() => {}) })
}, [])
const onUpdateRowClick = () => {
if (!updateInfo?.hasUpdate) return
if (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 () => {
// Open a progress sheet
let closeProgress = null
let setProgress = null
useUI.getState().openSheet(close => {
closeProgress = close
return <DownloadProgress ref={fn => { setProgress = fn }} />
}, { locked: true })
try {
// Fetch the expected SHA-256 hash if available
let expectedHash = null
if (updateInfo.hashUrl) {
try {
const hashRes = await fetch(updateInfo.hashUrl)
if (hashRes.ok) expectedHash = (await hashRes.text()).split(/\s/)[0]
} catch (e) { /* proceed without hash verification */ }
}
await downloadAndInstall(updateInfo.apkUrl, expectedHash, (received, total) => {
if (setProgress) setProgress(received, total)
})
if (closeProgress) closeProgress()
} catch (e) {
if (closeProgress) closeProgress()
toast(t('Update failed: {0}', e.message))
}
},
})
} else {
// Update available but no APK asset — open the releases page
window.open('https://gitlab.com/DuarteSantos8/opengym/-/releases', '_blank', 'noopener')
}
}
const doExport = async () => {
const json = JSON.stringify(S, null, 2)
const name = 'opengym-backup-' + todayISO() + '.json'
@@ -261,6 +316,9 @@ export default function Settings() {
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
<Section title={t('Data')}>
{MOBILE && updateInfo?.hasUpdate && <Row icon="info" iconTint="var(--purple)" title={t('openGym v{0} available', updateInfo.latestVersion)}
accessory="chevron"
onClick={onUpdateRowClick} />}
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan')} accessory="chevron" onClick={starterPlanSheet} />
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
@@ -344,6 +402,32 @@ function workoutControlsSheet() {
useUI.getState().openSheet(() => <WorkoutControlsSheet />)
}
// Download progress sheet — receives a ref callback that exposes a (received, total) setter.
// Uses forwardRef so the caller can push byte counts in without re-rendering the whole Settings tree.
const DownloadProgress = forwardRef(function DownloadProgress(_, ref) {
const [pct, setPct] = useState(0)
const [text, setText] = useState(t('Starting download…'))
// Expose a setter the caller can invoke directly
if (ref) ref(function update(received, total) {
if (total > 0) {
const p = Math.min(100, Math.round((received / total) * 100))
setPct(p)
setText(t('{0} %', p))
} else {
setText(t('{0} MB', (received / 1_000_000).toFixed(1)))
}
})
return (
<div style={{ textAlign: 'center', padding: '8px 0' }}>
<h3>{t('Downloading update…')}</h3>
<div style={{ margin: '16px 0', height: 6, borderRadius: 3, background: 'var(--fill-3)', overflow: 'hidden' }}>
<div style={{ height: '100%', width: pct + '%', background: 'var(--acc)', borderRadius: 3, transition: 'width .2s' }} />
</div>
<div className="muted small">{text}</div>
</div>
)
})
function effortHelpSheet() {
useUI.getState().openSheet(close => <>
<h3>{t('Effort per set')}</h3>
+132
View File
@@ -0,0 +1,132 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Settings from './Settings.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
// The updater downloads an .apk and hands it to the Android package installer, so its row
// may only ever show on the native Android build: never on the web, never on iOS. Each test
// flips the two gates (MOBILE flag, Capacitor platform) and watches whether Settings even
// asks gitlab.com for the latest release.
const mocks = vi.hoisted(() => {
const state = { S: null, MOBILE: false, android: false }
state.snapshot = () => ({
S: state.S,
user: null,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
state.checkForUpdate = vi.fn(() => Promise.resolve({ hasUpdate: true, latestVersion: '9.9.9', apkUrl: 'https://x/opengym.apk', hashUrl: null }))
state.confirmSheet = vi.fn()
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
useStore.getState = mocks.snapshot
return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
const useUI = selector => selector ? selector(snap()) : snap()
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
// MOBILE is read at render time through a getter so one module mock serves both builds.
vi.mock('../lib/mobile.js', () => ({
get MOBILE() { return mocks.MOBILE },
isAndroid: () => Promise.resolve(mocks.android),
shareExport: vi.fn(), syncReminder: vi.fn(),
}))
vi.mock('../lib/update.js', () => ({
checkForUpdate: (...a) => mocks.checkForUpdate(...a),
downloadAndInstall: vi.fn(),
}))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
starterPlanSheet: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(),
}))
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {},
}
mocks.MOBILE = false
mocks.android = false
mocks.checkForUpdate.mockClear()
mocks.confirmSheet.mockClear()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
// The effect resolves two promises (isAndroid, then checkForUpdate) before the row can render.
const mount = async () => {
await act(async () => { root.render(<Settings />) })
await act(async () => { await Promise.resolve(); await Promise.resolve() })
}
const updateRow = () => [...host.querySelectorAll('.lrow')].find(r => r.textContent.includes('openGym v9.9.9 available'))
describe('Settings — in-app update check', () => {
it('web build: never asks for releases and shows no update row', async () => {
await mount()
expect(mocks.checkForUpdate).not.toHaveBeenCalled()
expect(updateRow()).toBeUndefined()
})
it('mobile build on iOS: no check, no row', async () => {
mocks.MOBILE = true
await mount()
expect(mocks.checkForUpdate).not.toHaveBeenCalled()
expect(updateRow()).toBeUndefined()
})
it('mobile build on Android: checks once and shows the row, tapping it asks before downloading', async () => {
mocks.MOBILE = true
mocks.android = true
await mount()
expect(mocks.checkForUpdate).toHaveBeenCalledTimes(1)
expect(updateRow()).toBeTruthy()
act(() => { updateRow().click() })
expect(mocks.confirmSheet).toHaveBeenCalledTimes(1)
expect(mocks.confirmSheet.mock.calls[0][0].title).toBe('Update to 9.9.9?')
})
it('Android without a newer release: no row', async () => {
mocks.MOBILE = true
mocks.android = true
mocks.checkForUpdate.mockResolvedValueOnce({ hasUpdate: false, latestVersion: 'test', apkUrl: null, hashUrl: null })
await mount()
expect(mocks.checkForUpdate).toHaveBeenCalledTimes(1)
expect(updateRow()).toBeUndefined()
})
it('Android when gitlab.com is unreachable: stays quiet', async () => {
mocks.MOBILE = true
mocks.android = true
mocks.checkForUpdate.mockRejectedValueOnce(new Error('offline'))
await mount()
expect(updateRow()).toBeUndefined()
})
})
@@ -38,7 +38,7 @@ vi.mock('../lib/api.js', () => ({
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
+1 -1
View File
@@ -41,7 +41,7 @@ vi.mock('../lib/api.js', () => ({
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),