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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Android: auto-backup into a folder you choose, a sync app's for instance (#161)
Duarte Santos5434201bdaed
diff --git a/docs/DATA_IMPORTS.md b/docs/DATA_IMPORTS.mdindex 7d6a4fd9e..18b6f37e2 100644--- a/docs/DATA_IMPORTS.md+++ b/docs/DATA_IMPORTS.md@@ -80,7 +80,7 @@ library.- **Import backup** restores such a file and *replaces* everything currently in the app.- **Auto-backup on changes** (phone app only) saves a dated copy to `Documents/openGym` after eachworkout or routine edit and keeps the newest 14. Point a sync app at that folder to get them off- the phone.+ the phone — or, on Android, choose the sync app's own folder under Settings → **Backup folder**.If you host openGym yourself, backing up the `./data` folder covers every profile at once; see[backups](SELF_HOSTING.md#6-backups).diff --git a/docs/MOBILE.md b/docs/MOBILE.mdindex d602255ef..6476562f6 100644--- a/docs/MOBILE.md+++ b/docs/MOBILE.md@@ -101,6 +101,12 @@ Where the phone keeps things, in case you ever need them by hand:folder. Nothing else is deleted, in that folder or anywhere: other files you keep there, andthe copies versions before 1.3.9 wrote straight into `Documents/`, stay until you removethem yourself. Settings → **Import backup** reads any of them back, wherever it is.+ On Android, Settings → **Backup folder** (under Auto-backup) picks another folder with the+ system folder picker — a sync app's folder, an SD card — and the copies go there instead,+ pruned to the same 14. The choice belongs to this phone and does not sync. If the folder+ stops accepting copies (the permission revoked, the folder deleted), they go to+ `Documents/openGym` again and Settings says so until you choose the folder again or tap+ **Use default folder**.### Photos and videos of your own exercisesdiff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/BackupFolderPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/BackupFolderPlugin.javanew file mode 100644index 000000000..efc34bfd0--- /dev/null+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/BackupFolderPlugin.java@@ -0,0 +1,206 @@+package ch.duartesantos.opengym;++import android.app.Activity;+import android.content.ContentResolver;+import android.content.Intent;+import android.content.UriPermission;+import android.database.Cursor;+import android.net.Uri;+import android.provider.DocumentsContract;+import androidx.activity.result.ActivityResult;+import com.getcapacitor.JSObject;+import com.getcapacitor.Plugin;+import com.getcapacitor.PluginCall;+import com.getcapacitor.PluginMethod;+import com.getcapacitor.annotation.ActivityCallback;+import com.getcapacitor.annotation.CapacitorPlugin;+import java.io.OutputStream;+import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.regex.Pattern;++/**+ * The folder auto-backup writes into, chosen by the person (#161): a sync app's folder, an SD+ * card, anything the system folder picker offers. @capacitor/filesystem only knows its fixed+ * roots (Documents, Data, ...) and cannot write into a folder picked through the Storage Access+ * Framework, so this does the little that needs: pick a folder and keep the right to write it,+ * write one file into it by name, and prune the dated copies. Plain DocumentsContract, no+ * androidx.documentfile.+ *+ * The folder is a fact of this phone (lib/mobile.js keeps it in a private file, never in the+ * synced state): a content:// address means nothing on another device.+ *+ * Usage from JS (lib/mobile.js):+ * const BackupFolder = registerPlugin('BackupFolder');+ * const { uri, label } = await BackupFolder.pick(); // {} when cancelled+ * const { ok } = await BackupFolder.check({ uri }); // still allowed to write there?+ * await BackupFolder.write({ uri, name, data });+ * await BackupFolder.prune({ uri, keep, pattern, written }); // keeps the newest `keep`+ * await BackupFolder.release({ uri });+ */+@CapacitorPlugin(name = "BackupFolder")+public class BackupFolderPlugin extends Plugin {++ private static final int RW = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;+ // Writes and listings go through a content provider, which may be a cloud app: off the main+ // thread, and one at a time so two backups never race for the same name.+ private final ExecutorService io = Executors.newSingleThreadExecutor();++ @PluginMethod+ public void pick(PluginCall call) {+ Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);+ intent.addFlags(RW | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);+ startActivityForResult(call, intent, "pickResult");+ }++ @ActivityCallback+ private void pickResult(PluginCall call, ActivityResult result) {+ if (call == null) return;+ Intent data = result.getData();+ if (result.getResultCode() != Activity.RESULT_OK || data == null || data.getData() == null) {+ call.resolve(new JSObject()); // cancelled: nothing changes+ return;+ }+ Uri tree = data.getData();+ try {+ getContext().getContentResolver().takePersistableUriPermission(tree, RW);+ } catch (SecurityException e) {+ call.reject("this folder cannot be kept for later writes", e);+ return;+ }+ JSObject ret = new JSObject();+ ret.put("uri", tree.toString());+ ret.put("label", labelOf(tree));+ call.resolve(ret);+ }++ @PluginMethod+ public void check(PluginCall call) {+ String uri = call.getString("uri");+ JSObject ret = new JSObject();+ ret.put("ok", uri != null && held(Uri.parse(uri)));+ call.resolve(ret);+ }++ @PluginMethod+ public void write(PluginCall call) {+ String uri = call.getString("uri");+ String name = call.getString("name");+ String data = call.getString("data");+ if (uri == null || name == null || data == null) {+ call.reject("uri, name and data are required");+ return;+ }+ io.execute(() -> {+ try {+ Uri tree = Uri.parse(uri);+ ContentResolver cr = getContext().getContentResolver();+ Uri doc = childNamed(tree, name);+ if (doc == null) doc = DocumentsContract.createDocument(cr, root(tree), "application/json", name);+ if (doc == null) throw new IllegalStateException("the folder refused a new file");+ // "wt": truncate, so a shorter copy does not keep the tail of a longer one.+ try (OutputStream out = cr.openOutputStream(doc, "wt")) {+ if (out == null) throw new IllegalStateException("the file cannot be opened for writing");+ out.write(data.getBytes(StandardCharsets.UTF_8));+ }+ JSObject ret = new JSObject();+ ret.put("ok", true);+ call.resolve(ret);+ } catch (Exception e) {+ call.reject("could not write to the backup folder: " + e.getMessage(), e);+ }+ });+ }++ @PluginMethod+ public void prune(PluginCall call) {+ String uri = call.getString("uri");+ String pattern = call.getString("pattern");+ String written = call.getString("written", "");+ int keep = call.getInt("keep", 14);+ if (uri == null || pattern == null || keep < 1) {+ call.reject("uri, pattern and keep are required");+ return;+ }+ io.execute(() -> {+ int deleted = 0;+ try {+ Uri tree = Uri.parse(uri);+ Pattern only = Pattern.compile(pattern);+ List<String[]> older = new ArrayList<>(); // { name, document id }+ for (String[] child : children(tree)) {+ if (only.matcher(child[0]).matches() && !child[0].equals(written)) older.add(child);+ }+ // Newest first by the date in the name, as the Documents/openGym prune does.+ older.sort((a, b) -> b[0].compareTo(a[0]));+ ContentResolver cr = getContext().getContentResolver();+ for (int i = keep - 1; i < older.size(); i++) {+ try {+ if (DocumentsContract.deleteDocument(cr, DocumentsContract.buildDocumentUriUsingTree(tree, older.get(i)[1]))) deleted++;+ } catch (Exception e) { /* one stuck file does not stop the rest */ }+ }+ } catch (Exception e) { /* pruning is housekeeping; the copy is already written */ }+ JSObject ret = new JSObject();+ ret.put("deleted", deleted);+ call.resolve(ret);+ });+ }++ @PluginMethod+ public void release(PluginCall call) {+ String uri = call.getString("uri");+ if (uri != null) {+ try {+ getContext().getContentResolver().releasePersistableUriPermission(Uri.parse(uri), RW);+ } catch (Exception e) { /* already gone */ }+ }+ call.resolve();+ }++ private boolean held(Uri tree) {+ for (UriPermission p : getContext().getContentResolver().getPersistedUriPermissions()) {+ if (p.getUri().equals(tree) && p.isWritePermission()) return true;+ }+ return false;+ }++ private static Uri root(Uri tree) {+ return DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree));+ }++ /** The folder's name as the picker showed it ("Sync", "Backups"), for Settings. */+ private String labelOf(Uri tree) {+ try (Cursor c = getContext().getContentResolver().query(root(tree),+ new String[] { DocumentsContract.Document.COLUMN_DISPLAY_NAME }, null, null, null)) {+ if (c != null && c.moveToFirst()) return c.getString(0);+ } catch (Exception e) { /* fall through */ }+ return tree.getLastPathSegment();+ }++ /** Every child of the folder as { display name, document id }. */+ private List<String[]> children(Uri tree) {+ Uri list = DocumentsContract.buildChildDocumentsUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree));+ List<String[]> out = new ArrayList<>();+ try (Cursor c = getContext().getContentResolver().query(list,+ new String[] { DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_DOCUMENT_ID,+ DocumentsContract.Document.COLUMN_MIME_TYPE }, null, null, null)) {+ if (c == null) return Collections.emptyList();+ while (c.moveToNext()) {+ if (DocumentsContract.Document.MIME_TYPE_DIR.equals(c.getString(2))) continue;+ out.add(new String[] { c.getString(0), c.getString(1) });+ }+ }+ return out;+ }++ private Uri childNamed(Uri tree, String name) {+ for (String[] child : children(tree)) {+ if (name.equals(child[0])) return DocumentsContract.buildDocumentUriUsingTree(tree, child[1]);+ }+ return null;+ }+}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.javaindex 54bf83884..0c3ffc7b1 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@@ -23,6 +23,7 @@ public class MainActivity extends BridgeActivity {registerPlugin(InstallPlugin.class);registerPlugin(PrintPlugin.class);registerPlugin(RestAlertPlugin.class);+ registerPlugin(BackupFolderPlugin.class);super.onCreate(savedInstanceState);passSystemBarsToPage();}diff --git a/frontend/src/components/BackupFolderRow.jsx b/frontend/src/components/BackupFolderRow.jsxnew file mode 100644index 000000000..b80904e1c--- /dev/null+++ b/frontend/src/components/BackupFolderRow.jsx@@ -0,0 +1,42 @@+import { useEffect, useState } from 'react'+import { t } from '../lib/i18n.js'+import { backupFolder, chooseBackupFolder, resetBackupFolder, onBackupFolderChange } from '../lib/mobile.js'+import { useUI } from '../store/useUI.js'+import { Row } from './ui.jsx'++const DEFAULT_FOLDER = 'Documents/openGym'++/* Where auto-backup puts its copies on this Android phone (#161): Documents/openGym, or a folder+ chosen with the system picker — a sync app's, an SD card's. The choice is this phone's alone+ (lib/mobile.js), so it is read here and not from the synced state. When the chosen folder+ stops taking copies they go to Documents/openGym again, and this says so until the folder is+ chosen again or the default is confirmed. */+export default function BackupFolderRow() {+ const [folder, setFolder] = useState(null)+ useEffect(() => {+ let live = true+ backupFolder().then(f => { if (live) setFolder(f) }).catch(() => { if (live) setFolder({}) })+ const off = onBackupFolderChange(f => { if (live) setFolder(f) })+ return () => { live = false; off() }+ }, [])+ if (!folder) return null++ const choose = async () => {+ try {+ const next = await chooseBackupFolder()+ if (next) setFolder(next)+ } catch (e) { useUI.getState().toast(t('This folder can’t be used for backups.')) }+ }+ const useDefault = async () => { setFolder(await resetBackupFolder()) }++ return <>+ <Row icon="folder" iconTint="var(--blue)" title={t('Backup folder')}+ subtitle={folder.uri ? (folder.label || t('Chosen folder')) : DEFAULT_FOLDER} accessory="chevron" onClick={choose} />+ {folder.lost && <Row icon="warning" iconTint="var(--orange)" className="backup-lost"+ title={folder.lostLabel+ ? t('openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.', folder.lostLabel)+ : t('openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.')} />}+ {(folder.uri || folder.lost) && <Row icon="reset" iconTint="var(--label-3)" title={t('Use default folder')}+ subtitle={DEFAULT_FOLDER} onClick={useDefault} />}+ </>+}diff --git a/frontend/src/components/BackupFolderRow.test.jsx b/frontend/src/components/BackupFolderRow.test.jsxnew file mode 100644index 000000000..b89a96218--- /dev/null+++ b/frontend/src/components/BackupFolderRow.test.jsx@@ -0,0 +1,68 @@+// @vitest-environment happy-dom+// Settings → the auto-backup folder on Android (#161): the folder in use, a way to choose+// another, the way back to the default, and a warning when the chosen one stopped taking copies.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++const m = vi.hoisted(() => ({ folder: {}, listeners: new Set(), picked: null, toast: vi.fn(), pickFails: false }))+vi.mock('../lib/mobile.js', () => ({+ backupFolder: async () => m.folder,+ chooseBackupFolder: async () => { if (m.pickFails) throw new Error('nope'); if (!m.picked) return null; m.folder = m.picked; return m.folder },+ resetBackupFolder: async () => { m.folder = {}; return m.folder },+ onBackupFolderChange: fn => { m.listeners.add(fn); return () => m.listeners.delete(fn) },+}))+vi.mock('../store/useUI.js', () => ({ useUI: { getState: () => ({ toast: m.toast }) } }))++const { default: BackupFolderRow } = await import('./BackupFolderRow.jsx')++let host, root+beforeEach(() => {+ Object.assign(m, { folder: {}, picked: null, pickFails: false })+ m.listeners.clear(); m.toast.mockClear()+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+})+afterEach(() => { act(() => root.unmount()); host.remove() })++const mount = async () => { await act(async () => { root.render(<BackupFolderRow />) }) }+const rows = () => [...host.querySelectorAll('.lrow')]+const rowWith = text => rows().find(r => r.textContent.includes(text))+const tap = async el => { await act(async () => { el.click() }) }++describe('BackupFolderRow', () => {+ it('shows the default folder, and nothing to go back to', async () => {+ await mount()+ expect(rowWith('Backup folder').textContent).toContain('Documents/openGym')+ expect(rowWith('Use default folder')).toBeUndefined()+ })++ it('choosing a folder shows its name; the default is one tap back', async () => {+ await mount()+ m.picked = { uri: 'content://tree/Sync', label: 'Sync' }+ await tap(rowWith('Backup folder'))+ expect(rowWith('Backup folder').textContent).toContain('Sync')+ await tap(rowWith('Use default folder'))+ expect(rowWith('Backup folder').textContent).toContain('Documents/openGym')+ expect(rowWith('Use default folder')).toBeUndefined()+ })++ it('a folder the picker hands back that cannot be kept says so', async () => {+ await mount()+ m.pickFails = true+ await tap(rowWith('Backup folder'))+ expect(m.toast).toHaveBeenCalledWith('This folder can’t be used for backups.')+ })++ it('a folder that stopped taking copies is named in a warning, also when it happens while open', async () => {+ m.folder = { uri: 'content://tree/Sync', label: 'Sync' }+ await mount()+ expect(host.querySelector('.backup-lost')).toBeNull()+ await act(async () => { m.listeners.forEach(fn => fn({ lost: true, lostLabel: 'Sync' })) })+ expect(host.querySelector('.backup-lost').textContent).toContain('openGym can no longer write to “Sync”')+ expect(rowWith('Backup folder').textContent).toContain('Documents/openGym')+ await tap(rowWith('Use default folder'))+ expect(host.querySelector('.backup-lost')).toBeNull()+ })+})diff --git a/frontend/src/lib/mobile.backupfolder.test.js b/frontend/src/lib/mobile.backupfolder.test.jsnew file mode 100644index 000000000..cdef6344c--- /dev/null+++ b/frontend/src/lib/mobile.backupfolder.test.js@@ -0,0 +1,143 @@+// Auto-backup into a folder the person chose (#161, Android): the copy goes there through the+// local BackupFolder plugin and the dated copies are pruned there; a folder that stops taking+// them sends the copy to Documents/openGym after all and leaves a note for Settings. With no+// folder chosen nothing changes. The choice lives in a private file, never in the synced state.+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { todayISO } from './format.js'++const h = vi.hoisted(() => ({ files: new Map(), plugin: null, calls: [], picked: null, held: true, refuse: false }))++vi.mock('@capacitor/filesystem', () => ({+ Directory: { Data: 'DATA', Documents: 'DOCUMENTS', Cache: 'CACHE' },+ Encoding: { UTF8: 'utf8' },+ Filesystem: {+ writeFile: async ({ path, directory, data }) => { h.files.set(directory + '/' + path, data); return { uri: 'file://' + path } },+ readFile: async ({ path, directory }) => {+ const k = directory + '/' + path+ if (!h.files.has(k)) throw new Error('File does not exist')+ return { data: h.files.get(k) }+ },+ readdir: async () => ({ files: [] }),+ deleteFile: async () => {},+ },+}))+vi.mock('@capacitor/core', () => ({+ registerPlugin: name => {+ expect(name).toBe('BackupFolder')+ const call = (method, fn) => async arg => { h.calls.push([method, arg]); return fn(arg) }+ return {+ pick: call('pick', () => h.picked || {}),+ check: call('check', () => ({ ok: h.held })),+ write: call('write', () => { if (h.refuse) throw new Error('could not write to the backup folder'); return { ok: true } }),+ prune: call('prune', () => ({ deleted: 0 })),+ release: call('release', () => undefined),+ }+ },+}))++const mobile = await import('./mobile.js')+const { writeAutoBackup, chooseBackupFolder, resetBackupFolder, backupFolder, onBackupFolderChange, BACKUP_FOLDER_FILE, AUTO_BACKUP_KEEP, _resetBackupFolder } = mobile++const today = 'opengym-backup-' + todayISO() + '.json'+const saved = () => JSON.parse(h.files.get('DATA/' + BACKUP_FOLDER_FILE) || 'null')+const methods = () => h.calls.map(c => c[0])+const SYNC = 'content://com.android.externalstorage.documents/tree/primary%3ASync'++beforeEach(() => {+ h.files.clear(); h.calls.length = 0+ h.picked = null; h.held = true; h.refuse = false+ _resetBackupFolder()+})++describe('with no folder chosen', () => {+ it('writes to Documents/openGym exactly as before and never asks the plugin to write', async () => {+ await writeAutoBackup({ n: 1 })+ expect(JSON.parse(h.files.get('DOCUMENTS/openGym/' + today))).toEqual({ n: 1 })+ expect(methods()).toEqual([])+ expect(await backupFolder()).toEqual({})+ })+})++describe('choosing a folder', () => {+ it('keeps the choice in a private file on this phone', async () => {+ h.picked = { uri: SYNC, label: 'Sync' }+ expect(await chooseBackupFolder()).toEqual({ uri: SYNC, label: 'Sync' })+ expect(saved()).toEqual({ uri: SYNC, label: 'Sync' })+ _resetBackupFolder()+ expect(await backupFolder()).toEqual({ uri: SYNC, label: 'Sync' })+ })++ it('a cancelled picker changes nothing', async () => {+ h.picked = { uri: SYNC, label: 'Sync' }+ await chooseBackupFolder()+ h.picked = {}+ expect(await chooseBackupFolder()).toBeNull()+ expect(saved()).toEqual({ uri: SYNC, label: 'Sync' })+ })++ it('a new folder gives the old one back; the default gives up the chosen one', async () => {+ h.picked = { uri: SYNC, label: 'Sync' }+ await chooseBackupFolder()+ h.picked = { uri: SYNC + 'Two', label: 'Two' }+ await chooseBackupFolder()+ expect(h.calls.filter(c => c[0] === 'release').map(c => c[1].uri)).toEqual([SYNC])+ await resetBackupFolder()+ expect(h.calls.filter(c => c[0] === 'release').map(c => c[1].uri)).toEqual([SYNC, SYNC + 'Two'])+ expect(saved()).toEqual({})+ })+})++describe('writing into the chosen folder', () => {+ beforeEach(async () => {+ h.picked = { uri: SYNC, label: 'Sync' }+ await chooseBackupFolder()+ h.calls.length = 0+ })++ it('writes today\'s copy there and prunes there to the same fourteen, nothing in Documents', async () => {+ await writeAutoBackup({ n: 2 })+ expect(methods()).toEqual(['check', 'write', 'prune'])+ const write = h.calls.find(c => c[0] === 'write')[1]+ expect(write).toMatchObject({ uri: SYNC, name: today })+ expect(JSON.parse(write.data)).toEqual({ n: 2 })+ const prune = h.calls.find(c => c[0] === 'prune')[1]+ expect(prune).toMatchObject({ uri: SYNC, keep: AUTO_BACKUP_KEEP, written: today })+ // The same names the Documents prune keeps to, and nothing else.+ const re = new RegExp(prune.pattern)+ expect(re.test('opengym-backup-2026-01-02.json')).toBe(true)+ expect(re.test('opengym-backup-2026-01-02-2.json')).toBe(true)+ expect(re.test('notes.txt')).toBe(false)+ expect([...h.files.keys()].some(k => k.startsWith('DOCUMENTS/'))).toBe(false)+ })++ it('a folder whose permission is gone: the copy goes to Documents/openGym and Settings hears', async () => {+ const heard = []+ onBackupFolderChange(s => heard.push(s))+ h.held = false+ await writeAutoBackup({ n: 3 })+ expect(JSON.parse(h.files.get('DOCUMENTS/openGym/' + today))).toEqual({ n: 3 })+ expect(methods()).not.toContain('write')+ expect(saved()).toEqual({ lost: true, lostLabel: 'Sync' })+ expect(heard).toEqual([{ lost: true, lostLabel: 'Sync' }])+ })++ it('a write that fails falls back the same way, and the next copy goes straight to Documents', async () => {+ h.refuse = true+ await writeAutoBackup({ n: 4 })+ expect(JSON.parse(h.files.get('DOCUMENTS/openGym/' + today))).toEqual({ n: 4 })+ expect(methods()).not.toContain('prune')+ expect(saved()).toMatchObject({ lost: true })+ h.calls.length = 0+ await writeAutoBackup({ n: 5 })+ expect(methods()).toEqual([])+ expect(JSON.parse(h.files.get('DOCUMENTS/openGym/' + today))).toEqual({ n: 5 })+ })++ it('"Use default folder" puts the warning away', async () => {+ h.held = false+ await writeAutoBackup({})+ expect((await backupFolder()).lost).toBe(true)+ await resetBackupFolder()+ expect(await backupFolder()).toEqual({})+ })+})diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.jsindex 6f5da81e2..f021f5ed3 100644--- a/frontend/src/lib/mobile.js+++ b/frontend/src/lib/mobile.js@@ -236,6 +236,11 @@ const AUTO_BACKUP_NAME = /^opengym-backup-\d{4}-\d{2}-\d{2}(-2)?\.json$/// The other install's files stay where they are; this one cannot see them to prune them.export async function writeAutoBackup(state) {const day = todayISO()+ // A folder the person chose (Android, #161) comes first. When it can no longer be written —+ // the permission revoked, the folder deleted, the sync app gone — the copy goes to the default+ // folder after all, and Settings says so: a backup that silently stops is the one thing this+ // feature must not do.+ if (await writeToChosenFolder(state, day)) returnlet fstry { fs = await import('@capacitor/filesystem') } catch (e) { return }const write = name => fs.Filesystem.writeFile({@@ -270,4 +275,94 @@ async function pruneAutoBackups({ Filesystem, Directory }, written) {for (const n of older.slice(AUTO_BACKUP_KEEP - 1)) {try { await Filesystem.deleteFile({ path: `${AUTO_BACKUP_DIR}/${n}`, directory: Directory.Documents }) } catch (e) { /* one stuck file does not stop the rest */ }}-}\ No newline at end of file+}+/* ------------------------------------------------- the backup folder (#161) --+ Android only: the system folder picker (Storage Access Framework) through the local+ BackupFolder plugin (android/.../BackupFolderPlugin.java), since @capacitor/filesystem cannot+ write into a picked folder. The choice is a fact of this phone, kept in its own private file+ and never in S: S syncs and exports, and a content:// address means nothing anywhere else.++ { uri, label } the chosen folder, and its name as the picker showed it+ { lost, lostLabel } the folder stopped accepting copies; they go to Documents/openGym again+ {} the default, Documents/openGym */+export const BACKUP_FOLDER_FILE = 'opengym-backup-folder.json'++// The plugin proxy lives here and is never handed through a promise: a Capacitor plugin proxy+// answers every property, `then` included, so a promise resolving to it never settles (#42/#58).+let folderPlugin = null+async function loadFolderPlugin() {+ if (folderPlugin) return+ const { registerPlugin } = await import('@capacitor/core')+ folderPlugin = registerPlugin('BackupFolder')+}++let folderState = null // the file's content once read; {} for the default+const folderListeners = new Set()+const setFolderState = async next => {+ folderState = next+ await writeJsonFile(BACKUP_FOLDER_FILE, next)+ folderListeners.forEach(fn => { try { fn(next) } catch (e) { /* a listener's problem */ } })+}++/** Where auto-backup writes on this phone: { uri, label } | { lost, lostLabel } | {}. */+export async function backupFolder() {+ if (!folderState) {+ const saved = await readJsonFile(BACKUP_FOLDER_FILE)+ folderState = saved && typeof saved === 'object' ? saved : {}+ }+ return folderState+}++/** Settings listens, so a fallback in the middle of a backup shows without a reload. */+export function onBackupFolderChange(fn) {+ folderListeners.add(fn)+ return () => folderListeners.delete(fn)+}++/** Opens the system folder picker. Resolves to the new state, or null when cancelled. */+export async function chooseBackupFolder() {+ await loadFolderPlugin()+ const picked = await folderPlugin.pick()+ if (!picked?.uri) return null+ const before = await backupFolder()+ if (before.uri && before.uri !== picked.uri) await releaseFolder(before.uri)+ const next = { uri: picked.uri, label: picked.label || null }+ await setFolderState(next)+ return next+}++/** Back to Documents/openGym; also how the warning about a lost folder is put away. */+export async function resetBackupFolder() {+ const before = await backupFolder()+ if (before.uri) await releaseFolder(before.uri)+ await setFolderState({})+ return folderState+}++async function releaseFolder(uri) {+ try { await loadFolderPlugin(); await folderPlugin.release({ uri }) } catch (e) { /* already gone */ }+}++// True when today's copy is in the chosen folder. False with no folder chosen, and after a+// failure, which is recorded so Settings can say the copies went to the default folder.+async function writeToChosenFolder(state, day) {+ const folder = await backupFolder()+ if (!folder.uri) return false+ const name = `opengym-backup-${day}.json`+ try {+ await loadFolderPlugin()+ const { ok } = await folderPlugin.check({ uri: folder.uri })+ if (!ok) throw new Error('permission lost')+ await folderPlugin.write({ uri: folder.uri, name, data: JSON.stringify(state) })+ } catch (e) {+ await setFolderState({ lost: true, lostLabel: folder.label || null })+ await releaseFolder(folder.uri)+ return false+ }+ // Pruning waits for a successful write, and only ever touches the app's own dated names.+ try { await folderPlugin.prune({ uri: folder.uri, keep: AUTO_BACKUP_KEEP, pattern: AUTO_BACKUP_NAME.source, written: name }) } catch (e) { /* housekeeping */ }+ return true+}++// Tests only: forget the cached choice, as a fresh start of the app would.+export function _resetBackupFolder() { folderState = null; folderPlugin = null; folderListeners.clear() }diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex 4ebbbabe4..00c7be443 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -41,7 +41,7 @@ describe('Brazilian Portuguese locale', () => {// has to be taught is a number nobody reads. What the numbers stood for is asserted above.// If the hash fails, review the changed keys and wording before accepting a new one. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('be7923bf0bb782e6a233cc404a0e988eab8e481a4ca289da42806aaa1ac0d185')+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('671548f652a6f99f8821de3205c0b3d2cc5e5cf705a4886e62b83b42e3897fc5')})test('does not leak European Portuguese UI terms', () => {diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex abb5d4d74..d444b1620 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1725,4 +1725,11 @@ export default {'Show connection status': 'إظهار حالة الاتصال','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'عند الإيقاف: يُخفى الشريط في الأعلى. تبقى نقطة على الرئيسية تنبّهك عندما تتعثر المزامنة.','Connection problem': 'مشكلة في الاتصال',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'مجلد النسخ الاحتياطي',+ 'Chosen folder': 'المجلد المختار',+ 'Use default folder': 'استخدام المجلد الافتراضي',+ 'This folder can’t be used for backups.': 'لا يمكن استخدام هذا المجلد للنسخ الاحتياطية.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'لم يعد بإمكان openGym الكتابة في «{0}» — تُحفظ النسخ في Documents/openGym من جديد. اختر المجلد مرة أخرى للعودة إليه.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'لم يعد بإمكان openGym الكتابة في المجلد المختار — تُحفظ النسخ في Documents/openGym من جديد. اختر المجلد مرة أخرى للعودة إليه.',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 3f166b520..c568a9dbd 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1692,4 +1692,11 @@ export default {'Show connection status': 'Verbindungsstatus anzeigen','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Aus: Die Leiste oben ist ausgeblendet. Ein Punkt auf Start warnt trotzdem, wenn die Synchronisierung hängt.','Connection problem': 'Verbindungsproblem',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Backup-Ordner',+ 'Chosen folder': 'Gewählter Ordner',+ 'Use default folder': 'Standardordner verwenden',+ 'This folder can’t be used for backups.': 'Dieser Ordner kann nicht für Backups verwendet werden.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym kann nicht mehr in „{0}“ schreiben — die Kopien landen wieder in Documents/openGym. Wähle den Ordner erneut, um zu ihm zurückzukehren.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym kann nicht mehr in den gewählten Ordner schreiben — die Kopien landen wieder in Documents/openGym. Wähle den Ordner erneut, um zu ihm zurückzukehren.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex e785a924d..3eaae9bfb 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': 'Mostrar el estado de la conexión','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Desactivado: la barra de arriba se oculta. Un punto en Inicio sigue avisando cuando la sincronización se atasca.','Connection problem': 'Problema de conexión',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Carpeta de copias',+ 'Chosen folder': 'Carpeta elegida',+ 'Use default folder': 'Usar la carpeta predeterminada',+ 'This folder can’t be used for backups.': 'Esta carpeta no se puede usar para las copias.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym ya no puede escribir en «{0}»: las copias vuelven a Documents/openGym. Elige la carpeta otra vez para volver a usarla.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym ya no puede escribir en la carpeta elegida: las copias vuelven a Documents/openGym. Elige la carpeta otra vez para volver a usarla.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 2f2b00402..79adfd3cc 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': 'Afficher l’état de la connexion','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Désactivé : la barre du haut est masquée. Un point sur Accueil prévient quand même si la synchronisation est bloquée.','Connection problem': 'Problème de connexion',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Dossier des sauvegardes',+ 'Chosen folder': 'Dossier choisi',+ 'Use default folder': 'Utiliser le dossier par défaut',+ 'This folder can’t be used for backups.': 'Ce dossier ne peut pas servir aux sauvegardes.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym ne peut plus écrire dans « {0} » — les copies vont de nouveau dans Documents/openGym. Choisis à nouveau le dossier pour y revenir.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym ne peut plus écrire dans le dossier choisi — les copies vont de nouveau dans Documents/openGym. Choisis à nouveau le dossier pour y revenir.',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 4d2fd863b..b64303b14 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': 'कनेक्शन की स्थिति दिखाएँ','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'बंद: ऊपर की पट्टी छिप जाती है। सिंक अटकने पर होम पर एक बिंदु फिर भी चेतावनी देता है।','Connection problem': 'कनेक्शन में समस्या',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'बैकअप फ़ोल्डर',+ 'Chosen folder': 'चुना गया फ़ोल्डर',+ 'Use default folder': 'डिफ़ॉल्ट फ़ोल्डर इस्तेमाल करें',+ 'This folder can’t be used for backups.': 'इस फ़ोल्डर को बैकअप के लिए इस्तेमाल नहीं किया जा सकता।',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym अब “{0}” में नहीं लिख सकता — कॉपियाँ फिर से Documents/openGym में जाती हैं। उसमें वापस जाने के लिए फ़ोल्डर फिर से चुनें।',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym अब चुने गए फ़ोल्डर में नहीं लिख सकता — कॉपियाँ फिर से Documents/openGym में जाती हैं। उसमें वापस जाने के लिए फ़ोल्डर फिर से चुनें।',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 9a467ae4e..e16268be2 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1675,4 +1675,11 @@ export default {'Show connection status': 'Kapcsolat állapotának mutatása','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Kikapcsolva: a felső sáv rejtve marad. Ha a szinkronizálás elakad, egy pont a Kezdőlapon továbbra is jelez.','Connection problem': 'Kapcsolati probléma',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Mentési mappa',+ 'Chosen folder': 'Választott mappa',+ 'Use default folder': 'Alapértelmezett mappa használata',+ 'This folder can’t be used for backups.': 'Ez a mappa nem használható mentésekhez.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'Az openGym már nem tud írni ide: „{0}” — a másolatok ismét a Documents/openGym mappába kerülnek. Válaszd ki újra a mappát, hogy visszatérj hozzá.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'Az openGym már nem tud írni a választott mappába — a másolatok ismét a Documents/openGym mappába kerülnek. Válaszd ki újra a mappát, hogy visszatérj hozzá.',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 2bc78933e..3e2030c66 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': 'Mostra lo stato della connessione','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Disattivato: la barra in alto è nascosta. Un punto su Home avvisa comunque quando la sincronizzazione si blocca.','Connection problem': 'Problema di connessione',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Cartella dei backup',+ 'Chosen folder': 'Cartella scelta',+ 'Use default folder': 'Usa la cartella predefinita',+ 'This folder can’t be used for backups.': 'Questa cartella non si può usare per i backup.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym non può più scrivere in «{0}»: le copie tornano in Documents/openGym. Scegli di nuovo la cartella per tornarci.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym non può più scrivere nella cartella scelta: le copie tornano in Documents/openGym. Scegli di nuovo la cartella per tornarci.',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 216da4f57..6c0d1a96e 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': '연결 상태 표시','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': '끄면 위쪽 막대가 숨겨집니다. 동기화가 멈추면 홈의 점이 계속 알려 줍니다.','Connection problem': '연결 문제',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': '백업 폴더',+ 'Chosen folder': '선택한 폴더',+ 'Use default folder': '기본 폴더 사용',+ 'This folder can’t be used for backups.': '이 폴더는 백업에 사용할 수 없습니다.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym이 더 이상 “{0}”에 쓸 수 없습니다 — 사본은 다시 Documents/openGym에 저장됩니다. 그 폴더로 돌아가려면 다시 선택하세요.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym이 더 이상 선택한 폴더에 쓸 수 없습니다 — 사본은 다시 Documents/openGym에 저장됩니다. 그 폴더로 돌아가려면 다시 선택하세요.',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex f90326d97..b4b90785d 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': 'Pokazuj stan połączenia','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Wyłączone: pasek u góry jest ukryty. Kropka na ekranie Start nadal ostrzega, gdy synchronizacja utknie.','Connection problem': 'Problem z połączeniem',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Folder kopii zapasowych',+ 'Chosen folder': 'Wybrany folder',+ 'Use default folder': 'Użyj domyślnego folderu',+ 'This folder can’t be used for backups.': 'Tego folderu nie można użyć do kopii zapasowych.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym nie może już zapisywać w „{0}” — kopie znów trafiają do Documents/openGym. Wybierz folder ponownie, aby do niego wrócić.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym nie może już zapisywać w wybranym folderze — kopie znów trafiają do Documents/openGym. Wybierz folder ponownie, aby do niego wrócić.',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 2dd70898e..38e603676 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1016,6 +1016,12 @@ export const PT_BR_OVERRIDES = {'Show connection status': 'Mostrar o status da conexão','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Desligado: a barra no topo fica oculta. Um ponto no Início continua avisando quando a sincronização fica parada.','Connection problem': 'Problema de conexão',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Pasta de backup',+ 'Use default folder': 'Usar a pasta padrão',+ 'This folder can’t be used for backups.': 'Esta pasta não pode ser usada para backups.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'O openGym não consegue mais gravar em “{0}” — as cópias voltam para Documents/openGym. Escolha a pasta de novo para voltar a ela.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'O openGym não consegue mais gravar na pasta escolhida — as cópias voltam para Documents/openGym. Escolha a pasta de novo para voltar a ela.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 866891ebf..76bb2ca20 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': 'Mostrar o estado da ligação','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Desligado: a barra no topo fica oculta. Um ponto no Início continua a avisar quando a sincronização fica parada.','Connection problem': 'Problema de ligação',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Pasta das cópias de segurança',+ 'Chosen folder': 'Pasta escolhida',+ 'Use default folder': 'Usar a pasta predefinida',+ 'This folder can’t be used for backups.': 'Esta pasta não pode ser usada para cópias de segurança.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'O openGym já não consegue escrever em «{0}» — as cópias voltam a ir para Documents/openGym. Escolhe a pasta de novo para voltar a ela.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'O openGym já não consegue escrever na pasta escolhida — as cópias voltam a ir para Documents/openGym. Escolhe a pasta de novo para voltar a ela.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex d8e6da60e..8c76e504f 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': 'Показывать состояние подключения','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Выкл.: полоса сверху скрыта. Точка на «Главной» всё равно предупредит, если синхронизация застряла.','Connection problem': 'Проблема с подключением',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Папка резервных копий',+ 'Chosen folder': 'Выбранная папка',+ 'Use default folder': 'Использовать папку по умолчанию',+ 'This folder can’t be used for backups.': 'Эту папку нельзя использовать для резервных копий.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym больше не может записывать в «{0}» — копии снова сохраняются в Documents/openGym. Выбери папку заново, чтобы вернуться к ней.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym больше не может записывать в выбранную папку — копии снова сохраняются в Documents/openGym. Выбери папку заново, чтобы вернуться к ней.',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 74fc09e3d..132f67ded 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1683,4 +1683,11 @@ export default {'Show connection status': 'แสดงสถานะการเชื่อมต่อ','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'ปิด: แถบด้านบนจะถูกซ่อน แต่จุดบนหน้าหลักยังเตือนเมื่อการซิงค์ค้าง','Connection problem': 'การเชื่อมต่อมีปัญหา',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'โฟลเดอร์สำรองข้อมูล',+ 'Chosen folder': 'โฟลเดอร์ที่เลือก',+ 'Use default folder': 'ใช้โฟลเดอร์เริ่มต้น',+ 'This folder can’t be used for backups.': 'ใช้โฟลเดอร์นี้สำหรับสำรองข้อมูลไม่ได้',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym เขียนลงใน “{0}” ไม่ได้แล้ว — สำเนาจะกลับไปเก็บที่ Documents/openGym เลือกโฟลเดอร์อีกครั้งเพื่อกลับไปใช้',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym เขียนลงในโฟลเดอร์ที่เลือกไม่ได้แล้ว — สำเนาจะกลับไปเก็บที่ Documents/openGym เลือกโฟลเดอร์อีกครั้งเพื่อกลับไปใช้',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 83385a791..1f6e94641 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': 'Bağlantı durumunu göster','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Kapalı: üstteki şerit gizlenir. Eşitleme takılırsa Ana sayfadaki bir nokta yine uyarır.','Connection problem': 'Bağlantı sorunu',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Yedek klasörü',+ 'Chosen folder': 'Seçilen klasör',+ 'Use default folder': 'Varsayılan klasörü kullan',+ 'This folder can’t be used for backups.': 'Bu klasör yedekler için kullanılamıyor.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym artık “{0}” klasörüne yazamıyor — kopyalar yeniden Documents/openGym klasörüne gidiyor. Ona dönmek için klasörü yeniden seç.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym artık seçilen klasöre yazamıyor — kopyalar yeniden Documents/openGym klasörüne gidiyor. Ona dönmek için klasörü yeniden seç.',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex b3267b31c..d7b13b5fc 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1669,4 +1669,11 @@ export default {'Show connection status': 'Показувати стан з’єднання','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': 'Вимк.: смугу вгорі приховано. Крапка на «Головній» однаково попередить, якщо синхронізація застрягла.','Connection problem': 'Проблема зі з’єднанням',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': 'Папка резервних копій',+ 'Chosen folder': 'Вибрана папка',+ 'Use default folder': 'Використовувати типову папку',+ 'This folder can’t be used for backups.': 'Цю папку не можна використовувати для резервних копій.',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym більше не може записувати в «{0}» — копії знову зберігаються в Documents/openGym. Вибери папку ще раз, щоб повернутися до неї.',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym більше не може записувати у вибрану папку — копії знову зберігаються в Documents/openGym. Вибери папку ще раз, щоб повернутися до неї.',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 593ffac5d..22393c6b6 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1672,4 +1672,11 @@ export default {'Show connection status': '显示连接状态','Off: the bar at the top is hidden. A dot on Home still warns when syncing is stuck.': '关闭:隐藏顶部的提示栏。同步卡住时,“首页”上的小圆点仍会提醒你。','Connection problem': '连接问题',+ // --- auto-backup into a folder chosen on Android (#161) ---+ 'Backup folder': '备份文件夹',+ 'Chosen folder': '所选文件夹',+ 'Use default folder': '使用默认文件夹',+ 'This folder can’t be used for backups.': '此文件夹无法用于备份。',+ 'openGym can no longer write to “{0}” — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym 无法再写入“{0}”——副本会重新保存到 Documents/openGym。重新选择该文件夹即可改回。',+ 'openGym can no longer write to the chosen folder — the copies go to Documents/openGym again. Choose the folder again to go back to it.': 'openGym 无法再写入所选文件夹——副本会重新保存到 Documents/openGym。重新选择该文件夹即可改回。',}diff --git a/frontend/src/views/Settings.backupfolder.test.jsx b/frontend/src/views/Settings.backupfolder.test.jsxnew file mode 100644index 000000000..3f414a771--- /dev/null+++ b/frontend/src/views/Settings.backupfolder.test.jsx@@ -0,0 +1,97 @@+// @vitest-environment happy-dom+// The backup-folder rows (#161) sit under Auto-backup, on Android only, and only while it is on.+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'+import { bindUI } from '../components/ui.jsx'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++const mocks = vi.hoisted(() => {+ const state = { S: null, MOBILE: true, android: true }+ 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(),+ })+ 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 }))+vi.mock('../lib/mobile.js', () => ({ get MOBILE() { return mocks.MOBILE }, isAndroid: () => Promise.resolve(mocks.android), shareExport: vi.fn(), syncReminder: vi.fn() }))+vi.mock('../components/BackupFolderRow.jsx', () => ({ default: () => <div className="backup-folder-row" /> }))+vi.mock('../lib/update.js', () => ({ checkForUpdate: () => new Promise(() => {}), downloadAndInstall: vi.fn() }))+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))+vi.mock('../sheets.jsx', () => ({+ loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),+}))++// The Settings view reads the build-time version constant at render time.+globalThis.__APP_VERSION__ ??= 'test'++// SelectRow opens its choices through the bound UI store; capture the sheet to render it here.+let sheet = null+bindUI({ getState: () => ({ openSheet: render => { sheet = render; return { close: () => {} } } }) })++let host, root+beforeEach(() => {+ sheet = null+ mocks.S = {+ unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',+ gifSize: 'full', workouts: [], routines: [], exWeights: {},+ }+ mocks.MOBILE = true+ mocks.android = true+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+})++const mount = async () => { await act(async () => { root.render(<Settings />) }) }+const shown = () => !!host.querySelector('.backup-folder-row')++describe('the backup folder rows', () => {+ it('show on Android with auto-backup on', async () => {+ mocks.S.autoBackup = true+ await mount()+ expect(shown()).toBe(true)+ })+ it('not with auto-backup off', async () => {+ mocks.S.autoBackup = false+ await mount()+ expect(shown()).toBe(false)+ })+ it('not on iOS', async () => {+ mocks.S.autoBackup = true+ mocks.android = false+ await mount()+ expect(shown()).toBe(false)+ })+})diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 8cc6b7d56..134a440a4 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -26,6 +26,7 @@ import { checkForUpdate, downloadAndInstall } from '../lib/update.js'import { forgetCoach } from '../lib/coach-api.js'import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, plateInventorySheet, menuSheet } from '../sheets.jsx'import Icon from '../components/Icon.jsx'+import BackupFolderRow from '../components/BackupFolderRow.jsx'import { ServerSyncSection, KeptChangesRows, leaveServer, connectServer, passkeySignIn } from '../components/ServerSync.jsx'import { passwordOn, PasswordRow, openPasswordSignIn, openPasswordRegister } from '../components/PasswordAuth.jsx'import { usePasskeys, PasskeysRow, DeviceLinkRow } from '../components/Passkeys.jsx'@@ -566,6 +567,8 @@ export default function Settings() {subtitle={t('Saves a dated copy to Documents/openGym after finishing a workout or editing a routine, and keeps the newest {0} — point a sync app at that folder, or copy it out by hand.', 14)}><Switch checked={!!S.autoBackup} onChange={v => update(s => { s.autoBackup = v })} /></Row>}+ {/* Android only: the system folder picker (#161). iOS shows Documents in Files already. */}+ {MOBILE && android && S.autoBackup && <BackupFolderRow />}<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={resetEverything} /></Section><input ref={fileRef} type="file" accept=".json,.zip,application/json,application/zip" style={{ display: 'none' }} onChange={doImport} />