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.

Settings: photos and videos in the backup, the sign-out sheet and Reset; plan sharing carries the link, never the file; the Coach writes neither

Duarte Santos0465223584d4
diff --git a/frontend/src/components/ServerSync.jsx b/frontend/src/components/ServerSync.jsx
index 179cf2453..bb07833a0 100644
--- a/frontend/src/components/ServerSync.jsx
+++ b/frontend/src/components/ServerSync.jsx
@@ -9,6 +9,7 @@ import { t } from '../lib/i18n.js'
import { fmtAgo, changeCount } from '../lib/format.js'
import { passkeyLogin, webauthnOK } from '../lib/api.js'
import { MOBILE } from '../lib/mobile.js'
+import { syncMedia } from '../lib/media-sync.js'
import { DEMO } from '../lib/demo.js'
import { askAddDeviceData } from '../sheets.jsx'
import { ConnectSheet } from '../views/MobileOnboarding.jsx'
@@ -125,19 +126,23 @@ async function attempt(kind, opts) {
return null
}
}
-export async function leaveServer(kind, { exportBackup, done }) {
+export async function leaveServer(kind, { exportBackup, exportBackupZip, done }) {
const r = await attempt(kind)
if (!r) return
if (r.owed && !r.stashed) {
- ui().openSheet(close => <OwedSheet kind={kind} count={r.count} exportBackup={exportBackup} done={done} close={close} />, { kind: 'center', locked: true })
+ ui().openSheet(close => <OwedSheet kind={kind} count={r.count} media={r.media || 0} exportBackup={exportBackup} exportBackupZip={exportBackupZip} done={done} close={close} />, { kind: 'center', locked: true })
return
}
done(r)
}
-export function OwedSheet({ kind, count: count0, exportBackup, done, close }) {
+// `media`: photos or videos of custom exercises the server has not confirmed (useStore
+// unsyncedChanges). They are owed like any change, so the sheet names them; while there are any,
+// its export writes the backup with them (the plain JSON would leave exactly those out).
+export function OwedSheet({ kind, count: count0, media: media0 = 0, exportBackup, exportBackupZip, done, close }) {
const sync = useStore(s => s.sync)
const [count, setCount] = useState(count0)
+ const [media, setMedia] = useState(media0)
const [busy, setBusy] = useState(false)
const [tried, setTried] = useState(false)
const view = connectionView(sync)
@@ -148,11 +153,12 @@ export function OwedSheet({ kind, count: count0, exportBackup, done, close }) {
const retry = async () => {
setBusy(true)
await useStore.getState().syncNow()
+ await syncMedia({ force: true })
const r = await attempt(kind)
setBusy(false)
if (!r) return
if (!r.owed || r.stashed) return finish(r)
- setCount(r.count); setTried(true)
+ setCount(r.count); setMedia(r.media || 0); setTried(true)
}
const anyway = async () => {
setBusy(true)
@@ -164,9 +170,10 @@ export function OwedSheet({ kind, count: count0, exportBackup, done, close }) {
}
return <div style={{ textAlign: 'center', padding: '4px 0' }}>
<h3 style={{ marginBottom: 8 }}>{t('Not everything is on your server yet')}</h3>
- <div style={{ marginBottom: 6, fontWeight: 600 }}>
+ {(count !== 0 || !media) && <div style={{ marginBottom: 6, fontWeight: 600 }}>
{count > 0 ? t('Not on your server yet: {0}', changeCount(count)) : t('Some changes on this device have not reached your server.')}
- </div>
+ </div>}
+ {media > 0 && <div style={{ marginBottom: 6, fontWeight: 600 }}>{t('{0} photos or videos have not reached your server yet.', media)}</div>}
{(tried || refused) && view && <div className="small" style={{ color: 'var(--red)', marginBottom: 6 }}>{view.line}</div>}
<div className="muted small" style={{ marginBottom: 18, lineHeight: 1.5 }}>
{t('Try again, or export a backup first. Going ahead anyway keeps a copy of these changes on this device until it connects to this server as this account again — then they are added back.')}
@@ -174,7 +181,9 @@ export function OwedSheet({ kind, count: count0, exportBackup, done, close }) {
{refused && MOBILE && <><button className="btn primary" disabled={busy} onClick={() => { close(); pairAgain() }}>{t('Pair again')}</button><div style={{ height: 8 }} /></>}
{refused && !MOBILE && canSignIn() && <><button className="btn primary" disabled={busy} onClick={() => { close(); signInAgain() }}>{pwOn() ? t('Sign in') : t('Sign in with passkey')}</button><div style={{ height: 8 }} /></>}
{!refused && <><button className="btn primary" disabled={busy} onClick={retry}>{busy ? t('Syncing…') : t('Try again')}</button><div style={{ height: 8 }} /></>}
- <Button icon="download" disabled={busy} onClick={exportBackup}>{t('Export backup (JSON)')}</Button>
+ {media > 0 && exportBackupZip
+ ? <Button icon="download" disabled={busy} onClick={exportBackupZip}>{t('Export with photos & videos (.zip)')}</Button>
+ : <Button icon="download" disabled={busy} onClick={exportBackup}>{t('Export backup (JSON)')}</Button>}
<div style={{ height: 8 }} />
<button className="btn danger" disabled={busy} onClick={anyway}>{LEAVE[kind].anyway()}</button>
<div style={{ height: 8 }} />
diff --git a/frontend/src/components/ServerSync.media.test.jsx b/frontend/src/components/ServerSync.media.test.jsx
new file mode 100644
index 000000000..9e89f25ab
--- /dev/null
+++ b/frontend/src/components/ServerSync.media.test.jsx
@@ -0,0 +1,80 @@
+// @vitest-environment happy-dom
+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
+
+/* The sheet a sign-out shows when the server is missing something names the photos and videos
+ that have not reached it, offers the backup that carries them, and its "Try again" sends them
+ too. */
+const mocks = vi.hoisted(() => ({
+ sync: { status: 'offline', lastError: { status: 0, code: 'network' } },
+ syncNow: null, signOut: null, syncMedia: null
+}))
+vi.mock('../store/useStore.js', () => {
+ const snap = () => ({ sync: mocks.sync, syncNow: mocks.syncNow, signOut: mocks.signOut, config: null })
+ const useStore = selector => (selector ? selector(snap()) : snap())
+ useStore.getState = snap
+ return { useStore }
+})
+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('../lib/media-sync.js', () => ({ syncMedia: (...a) => mocks.syncMedia(...a) }))
+vi.mock('../lib/api.js', () => ({ passkeyLogin: vi.fn(), webauthnOK: () => true }))
+vi.mock('../sheets.jsx', () => ({ askAddDeviceData: vi.fn() }))
+vi.mock('../views/MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
+
+const { OwedSheet } = await import('./ServerSync.jsx')
+
+let host, root
+beforeEach(() => {
+ mocks.syncNow = vi.fn(async () => mocks.sync)
+ mocks.syncMedia = vi.fn(async () => {})
+ mocks.signOut = vi.fn(async () => ({ owed: true, count: 0, media: 1 }))
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(() => { act(() => root.unmount()); host.remove() })
+
+const button = text => [...host.querySelectorAll('button')].find(b => b.textContent.includes(text))
+
+describe('OwedSheet with photos and videos waiting', () => {
+ it('names them, and exports the backup that carries them', () => {
+ const zip = vi.fn(), json = vi.fn()
+ act(() => root.render(<OwedSheet kind="signout" count={0} media={2} exportBackup={json} exportBackupZip={zip} done={vi.fn()} close={vi.fn()} />))
+ expect(host.textContent).toContain('2 photos or videos have not reached your server yet.')
+ expect(host.textContent).not.toContain('Some changes on this device')
+ act(() => { button('Export with photos & videos (.zip)').click() })
+ expect(zip).toHaveBeenCalledTimes(1)
+ expect(json).not.toHaveBeenCalled()
+ })
+
+ it('names the changes and the media when both are waiting', () => {
+ act(() => root.render(<OwedSheet kind="signout" count={3} media={1} exportBackup={vi.fn()} exportBackupZip={vi.fn()} done={vi.fn()} close={vi.fn()} />))
+ expect(host.textContent).toContain('Not on your server yet')
+ expect(host.textContent).toContain('1 photos or videos have not reached your server yet.')
+ })
+
+ it('Try again sends them too, and the sheet follows the new count', async () => {
+ act(() => root.render(<OwedSheet kind="signout" count={0} media={1} exportBackup={vi.fn()} exportBackupZip={vi.fn()} done={vi.fn()} close={vi.fn()} />))
+ mocks.signOut = vi.fn(async () => ({ owed: true, count: 0, media: 1 }))
+ mocks.sync = { status: 'pending' }
+ await act(async () => { button('Try again').click(); await new Promise(r => setTimeout(r, 0)) })
+ expect(mocks.syncMedia).toHaveBeenCalledWith({ force: true })
+ expect(mocks.signOut).toHaveBeenCalled()
+ })
+
+ it('without media, it is the sheet it always was', () => {
+ const json = vi.fn()
+ act(() => root.render(<OwedSheet kind="signout" count={2} exportBackup={json} done={vi.fn()} close={vi.fn()} />))
+ expect(host.textContent).not.toContain('photos or videos')
+ act(() => { button('Export backup (JSON)').click() })
+ expect(json).toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/lib/backup-media.js b/frontend/src/lib/backup-media.js
new file mode 100644
index 000000000..5b0129ec3
--- /dev/null
+++ b/frontend/src/lib/backup-media.js
@@ -0,0 +1,125 @@
+/* Backups that carry the photos and videos of custom exercises.
+ *
+ * "Export backup (JSON)" stays what it always was: the state, with each exercise's small
+ * reference to its file and never the file. "Export with photos & videos" writes a store-only zip
+ * (lib/zip.js) instead:
+ *
+ * opengym-backup.json the very same JSON
+ * media/<sha256>.<ext> every photo, GIF, video and poster the state refers to
+ * README.txt what this is and how to bring it back
+ *
+ * "Import backup" takes either. From a zip, only files the backup's state refers to are taken,
+ * and each one only after its type, its size cap and its sha256 agree with its name; they go into
+ * the local store as pending, and the usual sync sends them to the server once the imported state
+ * is pushed. A file that fails a check is skipped, and its exercise shows the fallback tile until
+ * someone adds the picture again.
+ *
+ * A backup file is someone else's data as much as a plan file is: the imported state's media refs
+ * and links go through the same gates as everywhere else (sanitizeCustomMedia).
+ */
+import { zipStore, readZip, looksLikeZip } from './zip.js'
+import { referencedFiles, normalizeMediaRef, cleanUrl, MEDIA_MIMES } from './media-refs.js'
+import { sniffKind } from './media-sniff.js'
+import { sha256Hex } from './sha256.js'
+import { mediaStore } from './media-store.js'
+import { DEFAULT_LIMITS, MB } from './media-limits.js'
+
+export const BACKUP_JSON = 'opengym-backup.json'
+const MEDIA_ENTRY = /^media\/([0-9a-f]{64})\.(jpg|png|webp|gif|mp4|mov|webm)$/
+
+const README = `openGym backup with photos and videos
+=====================================
+
+opengym-backup.json your data - the same file "Export backup (JSON)" writes.
+media/ the photos, GIFs and videos of your own exercises, each named
+ by its SHA-256, plus the small previews shown in lists.
+
+To bring it back: openGym -> Settings -> Import backup, and pick this .zip as it is.
+Do not unpack and re-zip it: the app reads zips that are stored, not compressed.
+`
+
+/** The customEx media refs and links of an imported state, kept only where they pass the same
+ * checks as anywhere else; the rest of the state is left as it is. Mutates and returns it. */
+export function sanitizeCustomMedia(state) {
+ for (const c of Array.isArray(state?.customEx) ? state.customEx : []) {
+ if (!c || typeof c !== 'object') continue
+ if ('media' in c) { const m = normalizeMediaRef(c.media); if (m) c.media = m; else delete c.media }
+ if ('url' in c) { const u = cleanUrl(c.url); if (u) c.url = u; else delete c.url }
+ }
+ return state
+}
+
+/**
+ * The zip for "Export with photos & videos": { blob, included, missing }. Each file comes from the
+ * local store, or — signed in — is fetched into it first (`fetchOne`, lib/media-sync.js
+ * fetchToStore). `missing` counts those that could not be had; the export goes ahead without them.
+ */
+export async function exportBackupZip(S, { media = mediaStore, fetchOne = null, now } = {}) {
+ const entries = [{ name: BACKUP_JSON, blob: new Blob([JSON.stringify(S, null, 2)], { type: 'application/json' }) }]
+ let missing = 0
+ for (const f of referencedFiles(S)) {
+ let rec = await media.get(f.hash)
+ if (!rec && fetchOne) {
+ try { await fetchOne(f.hash, f); rec = await media.get(f.hash) } catch { /* counted below */ }
+ }
+ if (!rec || !MEDIA_MIMES[rec.mime]) { missing++; continue }
+ entries.push({ name: `media/${f.hash}.${MEDIA_MIMES[rec.mime].ext}`, blob: rec.blob })
+ }
+ entries.push({ name: 'README.txt', blob: new Blob([README], { type: 'text/plain' }) })
+ const blob = await zipStore(entries, now ? { now } : undefined)
+ return { blob, included: entries.length - 2, missing }
+}
+
+const isBackup = d => !!d && typeof d === 'object' && !Array.isArray(d) && Array.isArray(d.workouts) && Array.isArray(d.routines)
+
+/**
+ * Reads a picked backup, .json or .zip (told apart by its first bytes, not its name):
+ * { state, files: [{ hash, entry }], zip }. `files` are the zip's media entries the state refers
+ * to, not yet checked or stored — storeBackupMedia does that, once the import is confirmed.
+ * Throws on anything that is not an openGym backup.
+ */
+export async function readBackupFile(file) {
+ let state, files = []
+ const zip = await looksLikeZip(file)
+ if (zip) {
+ const entries = await readZip(file)
+ const json = entries.find(e => e.name === BACKUP_JSON)
+ if (!json) throw new Error('not an openGym backup')
+ state = JSON.parse(await json.blob.text())
+ if (!isBackup(state)) throw new Error('not an openGym backup')
+ const wanted = new Set(referencedFiles(state).map(f => f.hash))
+ const seen = new Set()
+ for (const e of entries) {
+ const m = MEDIA_ENTRY.exec(e.name)
+ if (!m || !wanted.has(m[1]) || seen.has(m[1])) continue
+ seen.add(m[1])
+ files.push({ hash: m[1], entry: e })
+ }
+ } else {
+ state = JSON.parse(await file.text())
+ if (!isBackup(state)) throw new Error('not an openGym backup')
+ }
+ return { state: sanitizeCustomMedia(state), files, zip }
+}
+
+/**
+ * Checks and keeps a backup's media files: each must sniff as a stored type, stay under that
+ * kind's cap, and hash to its name. Kept as pending — the server has not seen them from this
+ * device. Resolves { stored, skipped }.
+ */
+export async function storeBackupMedia(files, { media = mediaStore, limits = DEFAULT_LIMITS } = {}) {
+ let stored = 0, skipped = 0
+ const cap = { image: limits.imageMB, gif: limits.gifMB, video: limits.videoMB }
+ for (const { hash, entry } of files) {
+ try {
+ const head = new Uint8Array(await entry.blob.slice(0, 64).arrayBuffer())
+ const s = sniffKind(head)
+ if (!s || !MEDIA_MIMES[s.mime] || entry.size > (cap[s.kind] || 0) * MB) throw new Error('refused')
+ const bytes = new Uint8Array(await entry.blob.arrayBuffer())
+ if ((await sha256Hex(bytes)) !== hash) throw new Error('tampered')
+ await media.put(hash, new Blob([bytes], { type: s.mime }), { mime: s.mime, pending: true })
+ stored++
+ } catch { skipped++ }
+ }
+ return { stored, skipped }
+}
diff --git a/frontend/src/lib/backup-media.test.js b/frontend/src/lib/backup-media.test.js
new file mode 100644
index 000000000..1ec8c195d
--- /dev/null
+++ b/frontend/src/lib/backup-media.test.js
@@ -0,0 +1,88 @@
+import { describe, it, expect } from 'vitest'
+import { exportBackupZip, readBackupFile, storeBackupMedia, sanitizeCustomMedia, BACKUP_JSON } from './backup-media.js'
+import { createMediaStore, memoryBackend } from './media-store.js'
+import { zipStore, readZip } from './zip.js'
+import { sha256Hex } from './sha256.js'
+import { jpeg, png, mp4 } from './media-samples.test-util.js'
+
+const refFor = async (bytes, mime, kind = 'image') => ({ kind, hash: await sha256Hex(bytes), mime, size: bytes.length, width: 4, height: 3, at: 1 })
+const stateWith = customEx => ({ unit: 'kg', workouts: [], routines: [], bodyweight: [], customEx })
+
+describe('export with photos & videos', () => {
+ it('writes the same JSON, every file the state refers to under its hash, and a README; counts what it could not get', async () => {
+ const media = createMediaStore(memoryBackend())
+ const photo = jpeg(), poster = png(), clip = mp4().file
+ const main = await refFor(photo, 'image/jpeg')
+ const vid = await refFor(clip, 'video/quicktime', 'video')
+ main.poster = { hash: await sha256Hex(poster), mime: 'image/webp', size: poster.length, width: 2, height: 2 }
+ await media.put(main.hash, new Blob([photo]), { mime: 'image/jpeg' })
+ await media.put(main.poster.hash, new Blob([poster]), { mime: 'image/png' })
+ await media.put(vid.hash, new Blob([clip]), { mime: 'video/quicktime' })
+ const gone = { ...main, hash: 'f'.repeat(64), poster: undefined }
+ const S = stateWith([{ id: 'a', n: 'a', media: main }, { id: 'b', n: 'b', media: vid }, { id: 'c', n: 'c', media: gone }])
+ const fetched = []
+ const out = await exportBackupZip(S, { media, fetchOne: async h => { fetched.push(h); throw new Error('404') } })
+ expect(out.missing).toBe(1)
+ expect(out.included).toBe(3)
+ expect(fetched).toEqual(['f'.repeat(64)])
+ const entries = await readZip(out.blob)
+ expect(entries.map(e => e.name)).toEqual([BACKUP_JSON, `media/${main.poster.hash}.png`, `media/${main.hash}.jpg`, `media/${vid.hash}.mov`, 'README.txt'])
+ expect(JSON.parse(await entries[0].blob.text())).toEqual(JSON.parse(JSON.stringify(S, null, 2)))
+ })
+})
+
+describe('import', () => {
+ it('a zip brings its state and, once stored, its files as pending', async () => {
+ const photo = jpeg()
+ const main = await refFor(photo, 'image/jpeg')
+ const S = stateWith([{ id: 'a', n: 'a', media: main, url: 'youtu.be/x' }])
+ const zip = await zipStore([{ name: BACKUP_JSON, blob: new Blob([JSON.stringify(S)]) }, { name: `media/${main.hash}.jpg`, blob: new Blob([photo]) }, { name: 'media/' + 'e'.repeat(64) + '.jpg', blob: new Blob([photo]) }])
+ const read = await readBackupFile(new File([zip], 'backup.zip'))
+ expect(read.zip).toBe(true)
+ expect(read.state.customEx[0].url).toBe('https://youtu.be/x')
+ expect(read.files.map(f => f.hash)).toEqual([main.hash]) // only what the state refers to
+ const media = createMediaStore(memoryBackend())
+ expect(await storeBackupMedia(read.files, { media })).toEqual({ stored: 1, skipped: 0 })
+ expect(await media.get(main.hash)).toMatchObject({ mime: 'image/jpeg', pending: true })
+ })
+
+ it('a tampered file is skipped, and so is one over its cap or of a type that is not stored', async () => {
+ const photo = jpeg()
+ const main = await refFor(photo, 'image/jpeg')
+ const tampered = photo.slice(); tampered[tampered.length - 1] ^= 1
+ const html = new TextEncoder().encode('<!doctype html><script>alert(1)</script>')
+ const htmlRef = { ...main, hash: await sha256Hex(html) }
+ const big = new Uint8Array(3 * 1024 * 1024); big.set(photo)
+ const bigRef = { ...main, hash: await sha256Hex(big), size: big.length }
+ const S = stateWith([{ id: 'a', media: main }, { id: 'b', media: htmlRef }, { id: 'c', media: bigRef }])
+ const zip = await zipStore([
+ { name: BACKUP_JSON, blob: new Blob([JSON.stringify(S)]) },
+ { name: `media/${main.hash}.jpg`, blob: new Blob([tampered]) },
+ { name: `media/${htmlRef.hash}.jpg`, blob: new Blob([html]) },
+ { name: `media/${bigRef.hash}.jpg`, blob: new Blob([big]) }
+ ])
+ const read = await readBackupFile(new File([zip], 'b.zip'))
+ const media = createMediaStore(memoryBackend())
+ expect(await storeBackupMedia(read.files, { media })).toEqual({ stored: 0, skipped: 3 })
+ expect(await media.list()).toEqual([])
+ })
+
+ it('a JSON backup reads as before, with its refs and links through the same gates', async () => {
+ const S = stateWith([{ id: 'a', media: { kind: 'image', hash: 'nope' }, url: 'javascript:alert(1)' }, { id: 'b', media: await refFor(jpeg(), 'image/jpeg') }])
+ const read = await readBackupFile(new File([JSON.stringify(S)], 'b.json', { type: 'application/json' }))
+ expect(read.zip).toBe(false)
+ expect(read.files).toEqual([])
+ expect(read.state.customEx[0]).toEqual({ id: 'a' })
+ expect(read.state.customEx[1].media.mime).toBe('image/jpeg')
+ })
+
+ it('refuses what is not an openGym backup, zipped or not', async () => {
+ await expect(readBackupFile(new File(['{"hello":1}'], 'x.json'))).rejects.toThrow()
+ const zip = await zipStore([{ name: 'something.txt', blob: new Blob(['x']) }])
+ await expect(readBackupFile(new File([zip], 'x.zip'))).rejects.toThrow()
+ })
+
+ it('sanitizeCustomMedia leaves a state without custom exercises alone', () => {
+ expect(sanitizeCustomMedia({ workouts: [] })).toEqual({ workouts: [] })
+ })
+})
diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.js
index 229b62001..5b13ab95d 100644
--- a/frontend/src/lib/coach.js
+++ b/frontend/src/lib/coach.js
@@ -392,9 +392,13 @@ export function applyCreatedPlan(s, proposal, { schedule } = {}) {
pushSnapshot(s, proposal.id, t('Before the Coach’s plan'))
const bundle = proposal.bundle
// The Coach's `why` texts are for the review screen; they have no place in the routine data.
+ // A link is never the Coach's to write: validatePlan already drops one from the model's plan,
+ // and this drops it again on the way into mergePlan, which would otherwise carry a `url` on a
+ // plan's own exercises through to the profile (cleanCustom keeps links for shared plans).
const stripped = {
...bundle,
- routines: bundle.routines.map(r => ({ ...r, why: undefined, ex: r.ex.map(e => ({ ...e, why: undefined, name: undefined })) }))
+ routines: bundle.routines.map(r => ({ ...r, why: undefined, ex: r.ex.map(e => ({ ...e, why: undefined, name: undefined })) })),
+ customEx: (bundle.customEx || []).map(c => { const { url, media, ...rest } = c || {}; return rest })
}
const res = mergePlan(s, stripped, { schedule })
// Only when the week actually moved — with the switch off the old schedule still stands, and
diff --git a/frontend/src/lib/coach.test.js b/frontend/src/lib/coach.test.js
index 9ead78e1e..b9a2c7322 100644
--- a/frontend/src/lib/coach.test.js
+++ b/frontend/src/lib/coach.test.js
@@ -498,6 +498,23 @@ describe('created plans', () => {
customEx: []
}
+ // A link is never the Coach's to write, and a file ref never travels in a plan: validatePlan
+ // drops both from the model's answer, and applying the plan drops them again, since mergePlan
+ // keeps a link on a plan's own exercises for a plan shared by a person.
+ it('never writes a link or a media ref onto the exercises it creates', () => {
+ const s = JSON.parse(JSON.stringify(state()))
+ const withLink = {
+ ...bundle,
+ routines: [...bundle.routines, { id: 'x3', name: 'C', ex: [{ id: 'cx1', sets: 3, reps: 8, mode: 'reps' }] }],
+ customEx: [{ id: 'cx1', n: 'Sled drag', bp: 'legs', url: 'https://evil.example/phish', media: { kind: 'image', hash: 'a'.repeat(64), mime: 'image/webp', size: 1, width: 1, height: 1, at: 1 } }]
+ }
+ applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle: withLink }, { schedule: false })
+ const made = s.customEx.find(c => c.n === 'Sled drag')
+ expect(made).toBeTruthy()
+ expect(made.url).toBeUndefined()
+ expect(made.media).toBeUndefined()
+ })
+
it('adds routines as new ones and never modifies what was already there', () => {
const s = JSON.parse(JSON.stringify(state()))
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: false })
diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js
index 179406f37..ca3f12413 100644
--- a/frontend/src/lib/plan-share.js
+++ b/frontend/src/lib/plan-share.js
@@ -9,6 +9,7 @@
// a page break — each exercise, and each routine that fits, stays in one place.
import { EXIDX, isBodyweightEq } from './exercises.js'
+import { cleanUrl } from './media-refs.js'
import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from './history.js'
import { deriveSessionName } from './session-merge.js'
import { uid, todayISO, DAYN, weekOrder, weekStartOf, fmtNum, exCount } from './format.js'
@@ -149,6 +150,11 @@ const muscleList = v => inMuscleOrder([...new Set((Array.isArray(v) ? v : []).fi
function cleanCustom(c) {
const o = { id: c.id, n: c.n, bp: c.bp }
if (c.desc) o.desc = c.desc
+ // The link to a video or guide travels with a shared plan (#246), cleaned both ways like any
+ // other field of someone else's file; the exercise's own photo or video never does — it is a
+ // file on the sender's device and server, and a plan file is plain JSON.
+ const url = cleanUrl(c.url)
+ if (url) o.url = url
if (typeof c.eq === 'string' && c.eq) o.eq = c.eq
const prim = muscleList(c.primaries)
const sm = muscleList(c.secondaries).filter(m => !prim.includes(m))
diff --git a/frontend/src/lib/plan-share.test.js b/frontend/src/lib/plan-share.test.js
index a114faf3a..7ad086daa 100644
--- a/frontend/src/lib/plan-share.test.js
+++ b/frontend/src/lib/plan-share.test.js
@@ -256,3 +256,38 @@ describe('custom exercises in a shared plan', () => {
expect(target.routines[0].ex[0].id).toBe('mine')
})
})
+
+describe('plan-share links and media (#246)', () => {
+ const photo = { kind: 'image', hash: 'a'.repeat(64), mime: 'image/webp', size: 10, width: 4, height: 3, at: 1 }
+ const withCustom = c => ({
+ unit: 'kg', week: {},
+ routines: [{ id: 'r1', name: 'Push', ex: [{ id: 'cx1', sets: 3, reps: 5 }] }],
+ customEx: [{ id: 'cx1', n: 'Landmine press', bp: 'shoulders', custom: true, ...c }]
+ })
+
+ it('a link travels with the plan and arrives on the new exercise; the photo never travels', () => {
+ const bundle = buildPlanBundle(withCustom({ url: 'https://youtu.be/abc', media: photo }), 'Plan')
+ expect(bundle.customEx[0].url).toBe('https://youtu.be/abc')
+ expect(JSON.stringify(bundle)).not.toContain('media')
+ expect(JSON.stringify(bundle)).not.toContain('a'.repeat(64))
+ const s = { unit: 'kg', week: {}, routines: [], customEx: [], dayPlan: {} }
+ mergePlan(s, parsePlan(JSON.stringify(bundle)))
+ expect(s.customEx[0]).toMatchObject({ n: 'Landmine press', url: 'https://youtu.be/abc', custom: true })
+ expect(s.customEx[0].media).toBeUndefined()
+ })
+
+ it('a link that is not a web address is dropped on the way in, and never backfilled onto an exercise you have', () => {
+ const file = buildPlanBundle(withCustom({}), 'Plan')
+ file.customEx[0].url = 'javascript:alert(document.cookie)'
+ file.customEx[0].media = photo
+ const s = { unit: 'kg', week: {}, routines: [], customEx: [], dayPlan: {} }
+ mergePlan(s, parsePlan(JSON.stringify(file)))
+ expect(s.customEx[0].url).toBeUndefined()
+ expect(s.customEx[0].media).toBeUndefined()
+
+ const mine = { unit: 'kg', week: {}, routines: [], dayPlan: {}, customEx: [{ id: 'mine', n: 'Landmine press', bp: 'shoulders', custom: true }] }
+ mergePlan(mine, parsePlan(JSON.stringify(buildPlanBundle(withCustom({ url: 'https://youtu.be/abc' }), 'Plan'))))
+ expect(mine.customEx).toHaveLength(1)
+ expect(mine.customEx[0].url).toBeUndefined()
+ })
+})
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index bef1ad330..e107e8a79 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState, forwardRef } from 'react'
+import { useEffect, useRef, useState, forwardRef, useSyncExternalStore } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { workoutControls } from '../lib/workout-controls.js'
@@ -15,7 +15,12 @@ import { pushSupported, enablePush, disablePush, sendTestPush, syncPushSubscript
import { wakeLockSupported } from '../lib/wakelock.js'
import { t, LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, baseLang } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
-import { MOBILE, isAndroid, shareExport, syncReminder } from '../lib/mobile.js'
+import { MOBILE, isAndroid, shareExport, shareExportBlob, syncReminder } from '../lib/mobile.js'
+import { referencedFiles } from '../lib/media-refs.js'
+import { mediaStore } from '../lib/media-store.js'
+import { syncMedia, fetchToStore } from '../lib/media-sync.js'
+import { getMediaStatus, subscribeMediaStatus, pendingRefCount } from '../lib/media-owed.js'
+import { limitsFrom, MB } from '../lib/media-limits.js'
import { setRestAccent } from '../lib/rest-alert.js'
import { checkForUpdate, downloadAndInstall } from '../lib/update.js'
import { forgetCoach } from '../lib/coach-api.js'
@@ -146,18 +151,51 @@ export default function Settings() {
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); URL.revokeObjectURL(a.href)
toast(t('Backup exported'))
}
- const doImport = ev => {
- const f = ev.target.files[0]; if (!f) return
- const rd = new FileReader()
- rd.onload = () => {
- try {
- const data = JSON.parse(rd.result)
- if (!data.workouts || !data.routines) throw new Error('not an openGym backup')
- confirmSheet({ title: t('Import backup?'), message: t('This replaces all current data with the backup file.'), confirmText: t('Import'), danger: true, onConfirm: () => { replaceState(Object.assign(JSON.parse(JSON.stringify(DEF)), data), true); toast(t('Backup imported')) } })
- } catch (e) { toast(t('Import failed: {0}', e.message)) }
+ // "Export with photos & videos": the same JSON plus every file the state refers to, in a zip
+ // (lib/backup-media.js). Signed in, a file this device never downloaded is fetched for it; one
+ // nobody has is left out and counted. The sign-out sheet offers it while media are waiting.
+ const doExportZip = async () => {
+ const { exportBackupZip } = await import('../lib/backup-media.js')
+ const st = useStore.getState()
+ const signedIn = !!(st.user && st.config?.media)
+ let out
+ try { out = await exportBackupZip(st.S, { fetchOne: signedIn ? fetchToStore : null }) }
+ catch { toast(t('Something went wrong')); return }
+ const name = 'opengym-backup-' + todayISO() + '.zip'
+ if (out.missing) toast(t('{0} files could not be included', out.missing))
+ if (MOBILE) {
+ try { await shareExportBlob(out.blob, name); if (!out.missing) toast(t('Backup exported')) } catch (e) { /* share sheet dismissed */ }
+ return
}
- rd.readAsText(f)
+ const a = document.createElement('a'); a.href = URL.createObjectURL(out.blob); a.download = name; a.click()
+ setTimeout(() => URL.revokeObjectURL(a.href), 60000)
+ if (!out.missing) toast(t('Backup exported'))
+ }
+ // Import takes the JSON backup and the zip alike, told apart by their first bytes. A zip's
+ // files go into the local store only once the import is confirmed, each checked against its
+ // name first; the state's media refs and links pass the usual gates (lib/backup-media.js).
+ const doImport = async ev => {
+ const f = ev.target.files[0]; if (!f) return
+ ev.target.value = ''
+ let read
+ try {
+ const { readBackupFile } = await import('../lib/backup-media.js')
+ read = await readBackupFile(f)
+ } catch (e) { toast(t('Import failed: {0}', e.message)); return }
+ confirmSheet({
+ title: t('Import backup?'), message: t('This replaces all current data with the backup file.'), confirmText: t('Import'), danger: true,
+ onConfirm: async () => {
+ if (read.files.length) {
+ const { storeBackupMedia } = await import('../lib/backup-media.js')
+ await storeBackupMedia(read.files, { limits: limitsFrom(useStore.getState().config) })
+ }
+ replaceState(Object.assign(JSON.parse(JSON.stringify(DEF)), read.state), true)
+ toast(t('Backup imported'))
+ }
+ })
}
+ // Whether any custom exercise has a photo or video: the rows about them only show then.
+ const hasMedia = referencedFiles(S).length > 0
const registerHere = () => useUI.getState().openSheet(close => <RegisterInline close={close} setUser={setUser} pushState={pushState} pullState={pullState} toast={toast} />)
/* Disconnect (phone), Sign out, Sign out everywhere. None of them wipes this device while the
server is missing a change: the confirm no longer promises a sync it never checked, and when
@@ -167,7 +205,7 @@ export default function Settings() {
sign in with, so they have to be paired again, and the confirm says so. Failing, it touches
nothing local: still signed in here, and the toast says so. */
const kept = t('The changes your server has not seen are kept on this device, and added back when it connects as this account again.')
- const leave = (kind, after) => leaveServer(kind, { exportBackup: doExport, done: r => { nav('/home'); if (r.stashed) toast(kept); else if (after) toast(after) } })
+ const leave = (kind, after) => leaveServer(kind, { exportBackup: doExport, exportBackupZip: doExportZip, done: r => { nav('/home'); if (r.stashed) toast(kept); else if (after) toast(after) } })
const disconnect = () => confirmSheet({
title: t('Disconnect from your server?'),
message: t('This phone switches back to local-only and its copy of your account is removed. First it checks that your server has every change — if not, you choose what happens to them.'),
@@ -203,6 +241,7 @@ export default function Settings() {
if (coachLocal?.mode === 'byok') forgetCoach().catch(() => {})
replaceState(JSON.parse(JSON.stringify(DEF)), true)
nav('/home'); toast(t('All data reset'))
+ clearMediaAfterReset(!!user).catch(() => {})
},
})
@@ -488,7 +527,9 @@ export default function Settings() {
subtitle={t('Pull your history with a Hevy Pro API key')}
accessory="chevron" onClick={importFromHevy} />
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
- <Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
+ <Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} subtitle={hasMedia ? t('Without photos and videos') : undefined} accessory="chevron" onClick={doExport} />
+ {hasMedia && <Row icon="download" iconTint="var(--blue)" title={t('Export with photos & videos (.zip)')} accessory="chevron" onClick={doExportZip} />}
+ {hasMedia && <MediaRow />}
{/* 14 is AUTO_BACKUP_KEEP in lib/mobile.js, written out because the Settings tests mock
that module wholesale; mobile.autobackup.test.js pins the two together. */}
{MOBILE && <Row icon="history" iconTint="var(--blue)" title={t('Auto-backup on changes')}
@@ -497,7 +538,7 @@ export default function Settings() {
</Row>}
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={resetEverything} />
</Section>
- <input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />
+ <input ref={fileRef} type="file" accept=".json,.zip,application/json,application/zip" style={{ display: 'none' }} onChange={doImport} />
{/* Reset after reading so picking the same file twice still fires onChange. */}
<input ref={importRef} type="file" accept=".csv,.xml,text/csv,text/xml" style={{ display: 'none' }}
onChange={ev => { const f = ev.target.files[0]; if (f) importFromApp(f); ev.target.value = '' }} />
@@ -769,6 +810,45 @@ function EquipmentCard({ S, update }) {
// display names are free text and need not be unique. copyText also reaches the clipboard on a
// plain-http LAN address, where the Clipboard API is missing and password sign-in (#118) is the
// usual way in; where no copy works at all the id is still on screen to read out.
+/* After "Reset everything": the photos and videos go too. Signed in, the empty state is pushed
+ first and, once the server holds it, the server is asked to drop every file that state no
+ longer refers to (POST /api/media/sweep) — asked before the push landed, it would still see the
+ old state and keep everything, which is the safe side. Then this device keeps only the files a
+ stash refers to: another account's changes kept here are not this reset's to delete. */
+async function clearMediaAfterReset(signedIn) {
+ const st = useStore.getState()
+ if (signedIn && typeof st.pushState === 'function') {
+ await st.pushState()
+ const now = useStore.getState()
+ if (now.sync?.status === 'ok' && now.config?.media) await api('/api/media/sweep', { method: 'POST', body: '{}' }).catch(() => {})
+ }
+ const keep = typeof st.stashedMediaHashes === 'function' ? await st.stashedMediaHashes() : new Set()
+ await mediaStore.retainOnly(keep)
+}
+
+/* Settings → Data → "Photos & videos": how much of the server's space they take and what is still
+ waiting to go up; a tap sends what is waiting now, offers again what the server refused, and
+ lets a device that showed a file as missing ask for it again. On a device without a server that
+ stores media, it says they are kept here only. */
+function MediaRow() {
+ const S = useStore(s => s.S)
+ const user = useStore(s => s.user)
+ const config = useStore(s => s.config)
+ const status = useSyncExternalStore(subscribeMediaStatus, getMediaStatus)
+ const remote = !!(user && config?.media)
+ useEffect(() => { if (remote) syncMedia() }, [remote])
+ const pending = remote ? pendingRefCount(S) : 0
+ const u = status.usage
+ const usage = remote && u && u.quotaBytes > 0
+ ? t('{0} of {1} MB used on your server', Math.round((u.bytes || 0) / MB * 10) / 10, Math.round(u.quotaBytes / MB))
+ : null
+ const sub = remote
+ ? [usage, pending ? t('{0} waiting to upload', pending) : null].filter(Boolean).join(' · ') || undefined
+ : t('Kept on this device only — Export with photos & videos keeps a copy.')
+ return <Row icon="image" iconTint="var(--teal)" title={t('Photos & videos')} subtitle={sub}
+ onClick={remote ? () => syncMedia({ force: true, retryRejected: true }) : undefined} />
+}
+
function AccountIdRow({ id }) {
const toast = useUI(s => s.toast)
if (!id) return null
diff --git a/frontend/src/views/Settings.media.test.jsx b/frontend/src/views/Settings.media.test.jsx
new file mode 100644
index 000000000..be44368cc
--- /dev/null
+++ b/frontend/src/views/Settings.media.test.jsx
@@ -0,0 +1,188 @@
+// @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'
+import { createMediaStore, memoryBackend, _setMediaStore } from '../lib/media-store.js'
+import { readZip, zipStore } from '../lib/zip.js'
+import { sha256Hex } from '../lib/sha256.js'
+import { jpeg } from '../lib/media-samples.test-util.js'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+/* Settings → Data with photos and videos: the JSON export says it leaves them out, the zip export
+ carries them, Import takes either, and "Reset everything" takes the files too — on the server
+ once the empty state is there, and on this device except what a stash still refers to. */
+const mocks = vi.hoisted(() => {
+ const state = { S: null, user: null, config: null, sync: { status: 'ok' }, stashed: new Set() }
+ state.replaceState = vi.fn()
+ state.pushState = vi.fn(async () => {})
+ state.confirmSheet = vi.fn()
+ state.api = vi.fn(() => Promise.resolve({ ok: true }))
+ state.toast = vi.fn()
+ // Stable across renders: KeptChangesRows re-asks whenever the function changes, and sets a new
+ // list each time.
+ state.kept = []
+ state.keptChanges = async () => state.kept
+ state.snapshot = () => ({
+ S: state.S, user: state.user, config: state.config, sync: state.sync, coachLocal: null,
+ update: vi.fn(), replaceState: state.replaceState, setUser: vi.fn(), pullState: vi.fn(), pushState: state.pushState,
+ signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
+ syncNow: vi.fn(), unsyncedChanges: () => ({ owed: false, count: 0 }), keptChanges: state.keptChanges,
+ stashedMediaHashes: async () => state.stashed
+ })
+ 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' }, workouts: [] }, hasData: () => false }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: (...a) => mocks.toast(...a), 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: (...a) => mocks.api(...a), 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', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), shareExportBlob: vi.fn(), syncReminder: vi.fn() }))
+vi.mock('../lib/coach-api.js', () => ({ forgetCoach: vi.fn(() => Promise.resolve()) }))
+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(), askAddDeviceData: vi.fn(),
+}))
+
+globalThis.__APP_VERSION__ ??= 'test'
+
+const PHOTO = jpeg()
+let HASH, media, host, root
+const settle = async () => { for (let i = 0; i < 8; i++) await act(async () => { await new Promise(r => setTimeout(r, 0)) }) }
+// For what goes through a dynamic import and a few awaits of file reads: a busy test run can take
+// longer than a fixed number of ticks.
+const until = async (cond, ms = 4000) => {
+ const end = Date.now() + ms
+ while (!(await cond()) && Date.now() < end) await act(async () => { await new Promise(r => setTimeout(r, 10)) })
+}
+const row = text => [...host.querySelectorAll('.lrow')].find(r => r.textContent.includes(text))
+const stateWithPhoto = () => ({
+ unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none', gifSize: 'full', workouts: [], routines: [], exWeights: {},
+ customEx: [{ id: 'c1', n: 'Sandbag carry', bp: 'back', custom: true, media: { kind: 'image', hash: HASH, mime: 'image/jpeg', size: PHOTO.length, width: 640, height: 480, at: 1 } }]
+})
+
+beforeEach(async () => {
+ HASH = await sha256Hex(PHOTO)
+ media = createMediaStore(memoryBackend())
+ _setMediaStore(media)
+ mocks.S = stateWithPhoto()
+ mocks.user = null
+ mocks.config = null
+ mocks.sync = { status: 'ok' }
+ mocks.stashed = new Set()
+ for (const f of [mocks.replaceState, mocks.pushState, mocks.confirmSheet, mocks.api, mocks.toast]) f.mockClear()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ _setMediaStore(null)
+})
+const mount = async () => { act(() => root.render(<Settings />)); await settle() }
+
+describe('Settings — photos and videos', () => {
+ it('the JSON export says it leaves them out, the zip row and the Photos & videos row appear', async () => {
+ await mount()
+ expect(row('Export backup (JSON)').textContent).toContain('Without photos and videos')
+ expect(row('Export with photos & videos (.zip)')).toBeTruthy()
+ expect(row('Photos & videos').textContent).toContain('Kept on this device only')
+ expect(host.querySelector('input[type="file"][accept=".json,.zip,application/json,application/zip"]')).toBeTruthy()
+ })
+
+ it('without any, none of that shows', async () => {
+ mocks.S = { ...stateWithPhoto(), customEx: [] }
+ await mount()
+ expect(row('Export backup (JSON)').textContent).not.toContain('Without photos')
+ expect(row('Export with photos & videos')).toBeUndefined()
+ expect(row('Photos & videos')).toBeUndefined()
+ })
+
+ it('the zip export carries the state and the photo under its hash', async () => {
+ await media.put(HASH, new Blob([PHOTO]), { mime: 'image/jpeg', pending: false })
+ let blob = null
+ const created = vi.spyOn(URL, 'createObjectURL').mockImplementation(b => { blob = b; return 'blob:zip' })
+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ await mount()
+ act(() => { row('Export with photos & videos (.zip)').click() })
+ await until(() => created.mock.calls.length > 0)
+ expect(created).toHaveBeenCalled()
+ const names = (await readZip(blob)).map(e => e.name)
+ expect(names).toEqual(['opengym-backup.json', `media/${HASH}.jpg`, 'README.txt'])
+ expect(mocks.toast).toHaveBeenCalledWith('Backup exported')
+ vi.restoreAllMocks()
+ })
+
+ it('importing a zip keeps its photo as pending, once confirmed', async () => {
+ const S = stateWithPhoto()
+ const zip = await zipStore([{ name: 'opengym-backup.json', blob: new Blob([JSON.stringify(S)]) }, { name: `media/${HASH}.jpg`, blob: new Blob([PHOTO]) }])
+ await mount()
+ const input = host.querySelector('input[type="file"][accept^=".json"]')
+ Object.defineProperty(input, 'files', { value: [new File([zip], 'backup.zip')], configurable: true })
+ act(() => { input.dispatchEvent(new Event('change', { bubbles: true })) })
+ await until(() => mocks.confirmSheet.mock.calls.length > 0)
+ expect(mocks.confirmSheet).toHaveBeenCalledTimes(1)
+ expect(await media.has(HASH)).toBe(false) // nothing before the confirm
+ await act(async () => { await mocks.confirmSheet.mock.calls[0][0].onConfirm() })
+ expect(await media.get(HASH)).toMatchObject({ mime: 'image/jpeg', pending: true })
+ expect(mocks.replaceState).toHaveBeenCalledTimes(1)
+ expect(mocks.replaceState.mock.calls[0][0].customEx[0].media.hash).toBe(HASH)
+ expect(mocks.replaceState.mock.calls[0][1]).toBe(true)
+ })
+
+ it('Reset, signed in: pushes, asks the server to sweep, and keeps only what a stash refers to', async () => {
+ mocks.user = { id: 'u1', name: 'Ana' }
+ mocks.config = { media: { imageMB: 2 } }
+ const other = 'c'.repeat(64)
+ await media.put(HASH, new Blob([PHOTO]), { mime: 'image/jpeg', pending: false })
+ await media.put(other, new Blob(['x']), { mime: 'image/png', pending: true })
+ mocks.stashed = new Set([other])
+ await mount()
+ act(() => { row('Reset everything').click() })
+ act(() => { mocks.confirmSheet.mock.calls[0][0].onConfirm() })
+ await until(async () => !(await media.has(HASH)))
+ expect(mocks.pushState).toHaveBeenCalled()
+ expect(mocks.api.mock.calls.map(c => c[0])).toContain('/api/media/sweep')
+ expect(await media.has(HASH)).toBe(false)
+ expect(await media.has(other)).toBe(true)
+ })
+
+ it('Reset: no sweep before the empty state is on the server, nor for a guest', async () => {
+ mocks.user = { id: 'u1', name: 'Ana' }
+ mocks.config = { media: { imageMB: 2 } }
+ mocks.sync = { status: 'offline' }
+ await mount()
+ act(() => { row('Reset everything').click() })
+ act(() => { mocks.confirmSheet.mock.calls[0][0].onConfirm() })
+ await until(() => mocks.pushState.mock.calls.length > 0)
+ await settle()
+ expect(mocks.api.mock.calls.map(c => c[0])).not.toContain('/api/media/sweep')
+ act(() => root.unmount())
+ root = createRoot(host)
+ mocks.user = null
+ mocks.sync = { status: 'ok' }
+ mocks.confirmSheet.mockClear(); mocks.api.mockClear()
+ await media.put(HASH, new Blob([PHOTO]), { mime: 'image/jpeg', pending: true })
+ await mount()
+ act(() => { row('Reset everything').click() })
+ act(() => { mocks.confirmSheet.mock.calls[0][0].onConfirm() })
+ await until(async () => !(await media.has(HASH)))
+ expect(mocks.api).not.toHaveBeenCalled()
+ expect(await media.has(HASH)).toBe(false)
+ })
+})