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.

feat: SHA-256 verification, download progress, native installer, i18n

Sebastian G7958d0fcd4ce
diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle
index 98868cd41..70827d764 100644
--- a/frontend/android/app/build.gradle
+++ b/frontend/android/app/build.gradle
@@ -17,6 +17,9 @@ android {
}
}
buildTypes {
+ debug {
+ applicationIdSuffix ".debug"
+ }
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml
index d137fe653..7c67128b6 100644
--- a/frontend/android/app/src/main/AndroidManifest.xml
+++ b/frontend/android/app/src/main/AndroidManifest.xml
@@ -32,6 +32,7 @@
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- Workout-day reminder: lets the local-notifications plugin fire at the exact minute
on Android 12+. Where it isn't granted, scheduling silently falls back to inexact
alarms — the reminder still arrives, just not to the minute. -->
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/InstallPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/InstallPlugin.java
new file mode 100644
index 000000000..3fdd7c7d6
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/InstallPlugin.java
@@ -0,0 +1,51 @@
+package ch.duartesantos.opengym;
+
+import android.content.Intent;
+import android.net.Uri;
+import androidx.core.content.FileProvider;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+import java.io.File;
+
+/**
+ * Minimal local Capacitor plugin that opens the Android package installer
+ * for an APK file stored in the app's cache directory.
+ *
+ * Usage from JS:
+ * import { registerPlugin } from '@capacitor/core';
+ * const Install = registerPlugin('Install');
+ * await Install.installApk({ fileName: 'opengym-update.apk' });
+ */
+@CapacitorPlugin(name = "Install")
+public class InstallPlugin extends Plugin {
+
+ @PluginMethod
+ public void installApk(PluginCall call) {
+ String fileName = call.getString("fileName");
+ if (fileName == null || fileName.isEmpty()) {
+ call.reject("fileName is required");
+ return;
+ }
+
+ File file = new File(getContext().getCacheDir(), fileName);
+ if (!file.exists()) {
+ call.reject("APK file not found: " + fileName);
+ return;
+ }
+
+ Uri uri = FileProvider.getUriForFile(
+ getContext(),
+ getContext().getPackageName() + ".fileprovider",
+ file
+ );
+
+ Intent intent = new Intent(Intent.ACTION_VIEW);
+ intent.setDataAndType(uri, "application/vnd.android.package-archive");
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
+
+ getContext().startActivity(intent);
+ call.resolve();
+ }
+}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
index 6b41bd561..67cacdbe3 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
@@ -1,5 +1,12 @@
package ch.duartesantos.opengym;
+import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
-public class MainActivity extends BridgeActivity {}
+public class MainActivity extends BridgeActivity {
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ registerPlugin(InstallPlugin.class);
+ super.onCreate(savedInstanceState);
+ }
+}
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index 294e2cccc..35895fd70 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(586)
+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(593)
expect(inherited).toHaveLength(553)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
diff --git a/frontend/src/lib/update.js b/frontend/src/lib/update.js
index a28b77415..7073e4f6c 100644
--- a/frontend/src/lib/update.js
+++ b/frontend/src/lib/update.js
@@ -27,16 +27,17 @@ function compareSemver(a, b) {
/**
* Checks the GitLab releases API for a newer version.
- * Returns { hasUpdate, latestVersion, apkUrl } or throws on network failure.
+ * 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 }
+ if (!releases.length) return { hasUpdate: false, latestVersion: __APP_VERSION__, apkUrl: null, hashUrl: null }
const latest = releases[0]
const latestVersion = latest.tag_name.replace(/^v/, '')
@@ -44,19 +45,37 @@ export async function checkForUpdate() {
// 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 }
+ return { hasUpdate, latestVersion, apkUrl, hashUrl }
}
/**
- * Downloads the APK from `url` and triggers the Android installer.
+ * 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) {
+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')
@@ -65,10 +84,39 @@ export async function downloadAndInstall(url) {
const { Filesystem, Directory } = await import('@capacitor/filesystem')
- // Download the file as a blob, then write to cache as base64
+ // Download with progress tracking via ReadableStream
const res = await fetch(url)
if (!res.ok) throw new Error(`Download failed: ${res.status}`)
- const blob = await res.blob()
+
+ 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) => {
@@ -79,28 +127,14 @@ export async function downloadAndInstall(url) {
})
const fileName = 'opengym-update.apk'
- const written = await Filesystem.writeFile({
+ 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.')
- }
+ // Use the local InstallPlugin to trigger the Android package installer
+ const { registerPlugin } = await import('@capacitor/core')
+ const Install = registerPlugin('Install')
+ await Install.installApk({ fileName })
}
diff --git a/frontend/src/lib/update.test.js b/frontend/src/lib/update.test.js
index 675c01d64..feff94259 100644
--- a/frontend/src/lib/update.test.js
+++ b/frontend/src/lib/update.test.js
@@ -1,9 +1,30 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
-import { checkForUpdate } from './update.js'
+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
@@ -24,6 +45,7 @@ describe('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 () => {
@@ -87,11 +109,50 @@ describe('checkForUpdate', () => {
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')
+ })
+
+ 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 () => {
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 69b1651d7..c44040332 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1099,4 +1099,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Auf 0 stellen, um zum Standard ({0}) zurückzukehren.',
'Applies to this exercise everywhere, not just this plan.': 'Gilt überall für diese Übung, nicht nur in diesem Plan.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Eingetragen wird weiterhin das Gesamtgewicht — die Stange zählt nur für die Scheiben-Rechnung pro Seite.',
+ 'Update to {0}?': 'Auf {0} aktualisieren?',
+ 'The latest version will be downloaded and the installer will open.': 'Die neueste Version wird heruntergeladen und die Installation gestartet.',
+ 'Download & Install': 'Herunterladen & Installieren',
+ 'Update failed: {0}': 'Update fehlgeschlagen: {0}',
+ 'openGym v{0} available': 'openGym v{0} verfügbar',
+ 'Starting download…': 'Download wird gestartet…',
+ 'Downloading update…': 'Update wird heruntergeladen…',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 9ef769797..46b70c6d8 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Pon 0 para volver al valor por defecto ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Se aplica a este ejercicio en todas partes, no solo en este plan.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Sigues registrando el peso total — la barra solo se usa para calcular los discos por lado.',
+ 'Update to {0}?': '¿Actualizar a {0}?',
+ 'The latest version will be downloaded and the installer will open.': 'Se descargará la última versión y se abrirá el instalador.',
+ 'Download & Install': 'Descargar e instalar',
+ 'Update failed: {0}': 'Error en la actualización: {0}',
+ 'openGym v{0} available': 'openGym v{0} disponible',
+ 'Starting download…': 'Iniciando descarga…',
+ 'Downloading update…': 'Descargando actualización…',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 71e0570fa..3dac71124 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Mets 0 pour revenir à la valeur par défaut ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'S’applique à cet exercice partout, pas seulement dans ce plan.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Tu enregistres toujours le poids total — la barre ne sert qu’au calcul des disques par côté.',
+ 'Update to {0}?': 'Mettre à jour vers {0} ?',
+ 'The latest version will be downloaded and the installer will open.': 'La dernière version sera téléchargée et l’installateur s’ouvrira.',
+ 'Download & Install': 'Télécharger et installer',
+ 'Update failed: {0}': 'Échec de la mise à jour : {0}',
+ 'openGym v{0} available': 'openGym v{0} disponible',
+ 'Starting download…': 'Démarrage du téléchargement…',
+ 'Downloading update…': 'Téléchargement de la mise à jour…',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index b263f21d8..689cda9cd 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'डिफ़ॉल्ट ({0}) पर लौटने के लिए 0 सेट करें।',
'Applies to this exercise everywhere, not just this plan.': 'यह इस एक्सरसाइज़ पर हर जगह लागू होता है, सिर्फ़ इसी प्लान पर नहीं।',
'You still log the total weight — the bar only feeds the per-side plate math.': 'आप अब भी कुल वज़न ही दर्ज करते हैं — बार सिर्फ़ हर तरफ़ की प्लेट गिनती में काम आता है।',
+ 'Update to {0}?': '{0} में अपडेट करें?',
+ 'The latest version will be downloaded and the installer will open.': 'नवीनतम संस्करण डाउनलोड होगा और इंस्टॉलर खुलेगा।',
+ 'Download & Install': 'डाउनलोड और इंस्टॉल करें',
+ 'Update failed: {0}': 'अपडेट विफल: {0}',
+ 'openGym v{0} available': 'openGym v{0} उपलब्ध',
+ 'Starting download…': 'डाउनलोड शुरू हो रहा है…',
+ 'Downloading update…': 'अपडेट डाउनलोड हो रहा है…',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index d07d8b1e8..4535f57eb 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1083,4 +1083,11 @@ export default {
'What should change?': 'Mi változzon?',
'Coach is thinking…': 'Az Edző gondolkodik…',
'Message the Coach…': 'Üzenet az Edzőnek…',
+ 'Update to {0}?': 'Frissítés erre: {0}?',
+ 'The latest version will be downloaded and the installer will open.': 'A legújabb verzió letöltődik, és megnyílik a telepítő.',
+ 'Download & Install': 'Letöltés és telepítés',
+ 'Update failed: {0}': 'A frissítés sikertelen: {0}',
+ 'openGym v{0} available': 'openGym v{0} elérhető',
+ 'Starting download…': 'Letöltés indítása…',
+ 'Downloading update…': 'Frissítés letöltése…',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 1a4afd4fc..877384b4e 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Imposta 0 per tornare al valore predefinito ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Vale per questo esercizio ovunque, non solo in questo piano.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Registri comunque il peso totale — il bilanciere serve solo al calcolo dei dischi per lato.',
+ 'Update to {0}?': 'Aggiornare a {0}?',
+ 'The latest version will be downloaded and the installer will open.': 'L’ultima versione verrà scaricata e si aprirà il programma di installazione.',
+ 'Download & Install': 'Scarica e installa',
+ 'Update failed: {0}': 'Aggiornamento fallito: {0}',
+ 'openGym v{0} available': 'openGym v{0} disponibile',
+ 'Starting download…': 'Avvio del download…',
+ 'Downloading update…': 'Download dell’aggiornamento…',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index b00fc36b3..58621a9ae 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': '0으로 두면 기본값({0})으로 돌아갑니다.',
'Applies to this exercise everywhere, not just this plan.': '이 플랜만이 아니라 어디서든 이 운동에 적용됩니다.',
'You still log the total weight — the bar only feeds the per-side plate math.': '기록은 여전히 총 무게입니다 — 바 무게는 한쪽에 끼울 원판 계산에만 쓰입니다.',
+ 'Update to {0}?': '{0}(으)로 업데이트하시겠습니까?',
+ 'The latest version will be downloaded and the installer will open.': '최신 버전이 다운로드되고 설치 프로그램이 열립니다.',
+ 'Download & Install': '다운로드 및 설치',
+ 'Update failed: {0}': '업데이트 실패: {0}',
+ 'openGym v{0} available': 'openGym v{0} 사용 가능',
+ 'Starting download…': '다운로드 시작 중…',
+ 'Downloading update…': '업데이트 다운로드 중…',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 32ba98909..47bfe12ca 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Ustaw 0, aby wrócić do wartości domyślnej ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Dotyczy tego ćwiczenia wszędzie, nie tylko w tym planie.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Nadal zapisujesz ciężar całkowity — gryf służy tylko do wyliczenia talerzy na stronę.',
+ 'Update to {0}?': 'Zaktualizować do {0}?',
+ 'The latest version will be downloaded and the installer will open.': 'Najnowsza wersja zostanie pobrana i otworzy się instalator.',
+ 'Download & Install': 'Pobierz i zainstaluj',
+ 'Update failed: {0}': 'Aktualizacja nie powiodła się: {0}',
+ 'openGym v{0} available': 'openGym v{0} dostępna',
+ 'Starting download…': 'Rozpoczynanie pobierania…',
+ 'Downloading update…': 'Pobieranie aktualizacji…',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 8f9c9fff0..cfc55361e 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -608,7 +608,14 @@ export const PT_BR_OVERRIDES = {
'Default for this bar type.': 'Padrão para este tipo de barra.',
'Set to 0 to go back to the default ({0}).': 'Defina 0 para voltar ao padrão ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Vale para este exercício em todos os lugares, não só neste plano.',
- 'You still log the total weight — the bar only feeds the per-side plate math.': 'Você continua registrando o peso total — a barra só entra no cálculo das anilhas por lado.'
+ 'You still log the total weight — the bar only feeds the per-side plate math.': 'Você continua registrando o peso total — a barra só entra no cálculo das anilhas por lado.',
+ 'Update to {0}?': 'Atualizar para {0}?',
+ 'The latest version will be downloaded and the installer will open.': 'A versão mais recente será baixada e o instalador será aberto.',
+ 'Download & Install': 'Baixar e instalar',
+ 'Update failed: {0}': 'Falha na atualização: {0}',
+ 'openGym v{0} available': 'openGym v{0} disponível',
+ 'Starting download…': 'Iniciando download…',
+ 'Downloading update…': 'Baixando atualização…',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index a4d63fe3d..6fa068361 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Coloca 0 para voltar à predefinição ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Aplica-se a este exercício em todo o lado, não só neste plano.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Continuas a registar o peso total — a barra só conta para o cálculo dos discos por lado.',
+ 'Update to {0}?': 'Atualizar para {0}?',
+ 'The latest version will be downloaded and the installer will open.': 'A versão mais recente será transferida e o instalador será aberto.',
+ 'Download & Install': 'Transferir e instalar',
+ 'Update failed: {0}': 'Falha na atualização: {0}',
+ 'openGym v{0} available': 'openGym v{0} disponível',
+ 'Starting download…': 'A iniciar transferência…',
+ 'Downloading update…': 'A transferir atualização…',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index a2478a256..9dced192c 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Поставь 0, чтобы вернуться к значению по умолчанию ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Действует для этого упражнения везде, а не только в этом плане.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Записывается по-прежнему общий вес — гриф нужен только для расчёта блинов на сторону.',
+ 'Update to {0}?': 'Обновить до {0}?',
+ 'The latest version will be downloaded and the installer will open.': 'Последняя версия будет загружена и откроется установщик.',
+ 'Download & Install': 'Скачать и установить',
+ 'Update failed: {0}': 'Ошибка обновления: {0}',
+ 'openGym v{0} available': 'openGym v{0} доступна',
+ 'Starting download…': 'Начало загрузки…',
+ 'Downloading update…': 'Загрузка обновления…',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index ea2b3194f..eb6913728 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1091,4 +1091,11 @@ export default {
'What should change?': 'ควรเปลี่ยนอะไร',
'Coach is thinking…': 'โค้ชกำลังคิด…',
'Message the Coach…': 'ส่งข้อความถึงโค้ช…',
+ 'Update to {0}?': 'อัปเดตเป็น {0} หรือไม่?',
+ 'The latest version will be downloaded and the installer will open.': 'เวอร์ชันล่าสุดจะถูกดาวน์โหลดและตัวติดตั้งจะเปิดขึ้น',
+ 'Download & Install': 'ดาวน์โหลดและติดตั้ง',
+ 'Update failed: {0}': 'อัปเดตล้มเหลว: {0}',
+ 'openGym v{0} available': 'openGym v{0} พร้อมใช้งาน',
+ 'Starting download…': 'กำลังเริ่มดาวน์โหลด…',
+ 'Downloading update…': 'กำลังดาวน์โหลดอัปเดต…',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 6b69cf69b..34432c2c8 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Varsayılana ({0}) dönmek için 0 yap.',
'Applies to this exercise everywhere, not just this plan.': 'Yalnızca bu planda değil, bu egzersiz için her yerde geçerli.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Yine de toplam ağırlığı kaydedersin — bar yalnızca taraf başına plaka hesabına girer.',
+ 'Update to {0}?': '{0} sürümüne güncellensin mi?',
+ 'The latest version will be downloaded and the installer will open.': 'En son sürüm indirilecek ve yükleyici açılacak.',
+ 'Download & Install': 'İndir ve Kur',
+ 'Update failed: {0}': 'Güncelleme başarısız: {0}',
+ 'openGym v{0} available': 'openGym v{0} mevcut',
+ 'Starting download…': 'İndirme başlatılıyor…',
+ 'Downloading update…': 'Güncelleme indiriliyor…',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index ae6abb5ae..75847caee 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1080,4 +1080,11 @@ export default {
'Set to 0 to go back to the default ({0}).': '设为 0 即恢复默认值({0})。',
'Applies to this exercise everywhere, not just this plan.': '对这个动作处处生效,不只在此计划中。',
'You still log the total weight — the bar only feeds the per-side plate math.': '记录的仍是总重量——杆重只用于每侧杠铃片的计算。',
+ 'Update to {0}?': '更新到 {0}?',
+ 'The latest version will be downloaded and the installer will open.': '将下载最新版本并打开安装程序。',
+ 'Download & Install': '下载并安装',
+ 'Update failed: {0}': '更新失败:{0}',
+ 'openGym v{0} available': 'openGym v{0} 可用',
+ 'Starting download…': '正在开始下载…',
+ 'Downloading update…': '正在下载更新…',
}
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 3c5a60ccb..2dbf65724 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -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 { useUI } from '../store/useUI.js'
@@ -28,28 +28,16 @@ export default function Settings() {
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)
- }
- }
+ // --- update check state ---
+ const [updateInfo, setUpdateInfo] = useState(null) // { hasUpdate, latestVersion, apkUrl, hashUrl } | null
- useEffect(() => { runUpdateCheck() }, [])
+ useEffect(() => {
+ checkForUpdate().then(setUpdateInfo).catch(() => {})
+ }, [])
const onUpdateRowClick = () => {
- if (updateLoading) return
- if (updateInfo?.hasUpdate && updateInfo.apkUrl) {
+ if (!updateInfo?.hasUpdate) return
+ if (updateInfo.apkUrl) {
// Start download & install
const version = updateInfo.latestVersion
confirmSheet({
@@ -57,59 +45,38 @@ export default function Settings() {
message: t('The latest version will be downloaded and the installer will open.'),
confirmText: t('Download & Install'),
onConfirm: async () => {
- toast(t('Downloading update…'))
+ // 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 {
- await downloadAndInstall(updateInfo.apkUrl)
+ // 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 if (updateInfo?.hasUpdate && !updateInfo.apkUrl) {
+ } else {
// 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 => (
- <div style={{ textAlign: 'center', padding: '4px 0' }}>
- <h3>{t('Update check')}</h3>
- <div className="muted" style={{ marginBottom: 18, lineHeight: 1.5 }}>
- {info.hasUpdate
- ? t('{0} is available!', info.latestVersion)
- : t('openGym {0} — you\u2019re up to date.', __APP_VERSION__)}
- </div>
- <Button variant="ghost" className="dim" onClick={close}>{t('OK')}</Button>
- </div>
- ), { kind: 'center' })
- }).catch(e => {
- setUpdateError(e.message || 'Check failed')
- setUpdateLoading(false)
- useUI.getState().openSheet(close => (
- <div style={{ textAlign: 'center', padding: '4px 0' }}>
- <h3>{t('Update check')}</h3>
- <div className="muted" style={{ marginBottom: 18, lineHeight: 1.5 }}>
- {t('Could not check for updates: {0}', e.message || 'unknown error')}
- </div>
- <Button variant="ghost" className="dim" onClick={close}>{t('OK')}</Button>
- </div>
- ), { 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'
@@ -310,9 +277,9 @@ export default function Settings() {
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
<Section title={t('Data')}>
- <Row icon="rocket" iconTint="var(--purple)" title={updateTitle}
- accessory={updateInfo?.hasUpdate ? 'chevron' : 'none'}
- onClick={onUpdateRowClick} />
+ {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 (PPL)')} accessory="chevron" onClick={loadStarterPlan} />
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
@@ -366,6 +333,32 @@ const EFFORT_ROWS = [
// against. Not where the stepper starts; + walks up from the bottom of the scale.
const EFFORT_TYPICAL = 2
+// 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>