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.

Android: Play asset packs of the animations, generated on the release machine

Duarte Santos5674afc1618c
diff --git a/frontend/android/.gitignore b/frontend/android/.gitignore
index 48354a3df..25c0c48fa 100644
--- a/frontend/android/.gitignore
+++ b/frontend/android/.gitignore
@@ -99,3 +99,10 @@ app/src/main/assets/public
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+
+# The Play asset packs of the animations: generated on the release machine right before the Play
+# bundle is built (scripts/android/make-asset-packs.mjs), never committed (Gym visual licence).
+/anim_*/
+/asset-packs.settings.gradle
+/asset-packs.app.gradle
+/app/src/play/assets/anim-packs.json
diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle
index e0551beed..81b25ad5d 100644
--- a/frontend/android/app/build.gradle
+++ b/frontend/android/app/build.gradle
@@ -72,6 +72,9 @@ dependencies {
// Writing workouts and weigh-ins to Health Connect (#200, HealthConnectPlugin). Off until the
// user turns it on.
implementation "androidx.health.connect:connect-client:$healthConnectVersion"
+ // The sharper animations as Play asset packs (AnimationPacksPlugin in src/play): the Play
+ // build only. The sideloaded APK has no Play Store behind it and keeps its built-in ones.
+ playImplementation "com.google.android.play:asset-delivery:$assetDeliveryVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
@@ -81,6 +84,11 @@ dependencies {
apply from: 'capacitor.build.gradle'
+// The asset packs themselves, generated on the release machine only (settings.gradle).
+if (rootProject.file('asset-packs.app.gradle').exists()) {
+ apply from: rootProject.file('asset-packs.app.gradle')
+}
+
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/AnimationPacksPlugin.java b/frontend/android/app/src/sideload/java/ch/duartesantos/opengym/AnimationPacksPlugin.java
similarity index 100%
rename from frontend/android/app/src/main/java/ch/duartesantos/opengym/AnimationPacksPlugin.java
rename to frontend/android/app/src/sideload/java/ch/duartesantos/opengym/AnimationPacksPlugin.java
diff --git a/frontend/android/settings.gradle b/frontend/android/settings.gradle
index 3b4431d77..8aa7e5be2 100644
--- a/frontend/android/settings.gradle
+++ b/frontend/android/settings.gradle
@@ -2,4 +2,9 @@ include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
-apply from: 'capacitor.settings.gradle'
\ No newline at end of file
+apply from: 'capacitor.settings.gradle'
+// The Play asset packs of the animations, only while the release machine builds the Play bundle
+// (scripts/android/make-asset-packs.mjs writes this file and the modules; never committed).
+if (file('asset-packs.settings.gradle').exists()) {
+ apply from: 'asset-packs.settings.gradle'
+}
diff --git a/frontend/android/variables.gradle b/frontend/android/variables.gradle
index a9983adeb..214d07cdc 100644
--- a/frontend/android/variables.gradle
+++ b/frontend/android/variables.gradle
@@ -14,4 +14,5 @@ ext {
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
healthConnectVersion = '1.1.0'
+ assetDeliveryVersion = '2.2.2'
}
\ No newline at end of file
diff --git a/frontend/src/lib/android-asset-packs.test.js b/frontend/src/lib/android-asset-packs.test.js
new file mode 100644
index 000000000..9852b3568
--- /dev/null
+++ b/frontend/src/lib/android-asset-packs.test.js
@@ -0,0 +1,81 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { planPacks, splitParts, moduleName, packIndex, moduleGradle, write, clean, PART_MAX_BYTES } from '../../../scripts/android/make-asset-packs.mjs'
+import { buildPacks } from '../../../scripts/media/make-pack-manifests.mjs'
+import { EXDB } from './exercises-data.js'
+import { packDrawingId } from './anim-quality.js'
+
+/* The Google Play asset packs scripts/android/make-asset-packs.mjs puts into the Android project
+ on the release machine: the same drawings per pack as the iPhone's, Play-valid names, split under
+ Play's 1.5 GB per-pack limit. File sizes are made up here: nothing reads a media file. */
+const sizeOf = () => 100_000
+const srcFor = px => `/media/${px}`
+
+describe('Play asset packs', () => {
+ it('hold exactly the drawings of the iPhone packs, at <packId>/<drawing>.webp', () => {
+ const plan = planPacks({ qualities: [480], srcFor, sizeOf })
+ const ios = Object.fromEntries(buildPacks(EXDB, { qualities: [480] }).packs.map(p => [p.id, p.ids]))
+ expect(plan.map(p => p.id).sort()).toEqual(['anim-480-female', 'anim-480-male'])
+ for (const p of plan) {
+ const ids = p.parts.flatMap(x => x.files.map(f => f.id))
+ expect(ids).toEqual(ios[p.id])
+ expect(p.parts[0].files[0].src).toBe(`/media/480/${ids[0]}.webp`)
+ }
+ })
+
+ it('have Play-valid names: anim-480-male is the module anim_480_male', () => {
+ expect(moduleName('anim-480-male')).toBe('anim_480_male')
+ expect(moduleName('anim-1080-female', 2)).toBe('anim_1080_female_p2')
+ expect(moduleGradle('anim_480_male')).toMatch(/packName = "anim_480_male"[\s\S]*deliveryType = "on-demand"/)
+ })
+
+ it('split a pack over the limit into parts, each under it, nothing lost', () => {
+ const files = Array.from({ length: 10 }, (_, i) => ({ id: String(i), bytes: 400 }))
+ const parts = splitParts(files, 1000)
+ expect(parts.map(p => p.length)).toEqual([2, 2, 2, 2, 2])
+ expect(parts.flat()).toEqual(files)
+ const plan = planPacks({ qualities: [1080], srcFor, sizeOf: () => 400 * 1024, max: 1024 * 1024 * 1024 })
+ const male = plan.find(p => p.id === 'anim-1080-male')
+ expect(male.parts.length).toBeGreaterThan(1)
+ expect(male.parts.map(x => x.module)).toEqual(male.parts.map((_, i) => `anim_1080_male_p${i + 1}`))
+ for (const part of male.parts) expect(part.files.reduce((n, f) => n + f.bytes, 0)).toBeLessThanOrEqual(1024 * 1024 * 1024)
+ expect(PART_MAX_BYTES).toBeLessThan(1.5 * 1024 * 1024 * 1024)
+ })
+
+ it('refuse a pack with a drawing missing', () => {
+ expect(() => planPacks({ qualities: [480], srcFor, sizeOf: f => (f.endsWith('/0001.webp') ? null : 1) })).toThrow(/missing 480 px drawing 0001/)
+ })
+
+ it('a test set keeps the drawing the app probes a pack by', () => {
+ const plan = planPacks({ qualities: [240], srcFor, sizeOf, limit: 2 })
+ for (const p of plan) {
+ const probe = packDrawingId(EXDB.find(e => e.id === '0001'), p.figure)
+ expect(p.parts[0].files.map(f => f.id)).toContain(probe)
+ }
+ })
+
+ it('tell the app which Play packs make up each of its packs', () => {
+ const plan = planPacks({ qualities: [480], srcFor, sizeOf })
+ expect(packIndex(plan)['anim-480-male']).toMatchObject({ parts: ['anim_480_male'], files: plan[0].parts[0].files.length })
+ })
+
+ it('go into the project and out again, with nothing else touched', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'packs-'))
+ const src = path.join(dir, 'src')
+ fs.mkdirSync(src)
+ fs.writeFileSync(path.join(src, 'a.webp'), 'x')
+ fs.writeFileSync(path.join(dir, 'settings.gradle'), 'keep')
+ const plan = [{ id: 'anim-480-male', bytes: 1, parts: [{ module: 'anim_480_male', files: [{ id: 'a', src: path.join(src, 'a.webp'), bytes: 1 }] }] }]
+ write(plan, dir)
+ expect(fs.existsSync(path.join(dir, 'anim_480_male/src/main/assets/anim-480-male/a.webp'))).toBe(true)
+ expect(fs.readFileSync(path.join(dir, 'asset-packs.settings.gradle'), 'utf8')).toMatch(/include ':anim_480_male'/)
+ expect(fs.readFileSync(path.join(dir, 'asset-packs.app.gradle'), 'utf8')).toMatch(/assetPacks = \[":anim_480_male"\]/)
+ expect(JSON.parse(fs.readFileSync(path.join(dir, 'app/src/play/assets/anim-packs.json'), 'utf8'))['anim-480-male'].parts).toEqual(['anim_480_male'])
+ clean(dir)
+ expect(fs.readdirSync(dir).sort()).toEqual(['app', 'settings.gradle', 'src'])
+ expect(fs.existsSync(path.join(dir, 'app/src/play/assets/anim-packs.json'))).toBe(false)
+ fs.rmSync(dir, { recursive: true, force: true })
+ })
+})
diff --git a/scripts/android/make-asset-packs.mjs b/scripts/android/make-asset-packs.mjs
new file mode 100644
index 000000000..4cea581b5
--- /dev/null
+++ b/scripts/android/make-asset-packs.mjs
@@ -0,0 +1,167 @@
+#!/usr/bin/env node
+// The Google Play asset packs of the exercise animations (Play Asset Delivery, on demand), put
+// into the Android project on the release machine right before the Play bundle is built, and
+// taken out again after. They are never committed (frontend/android/.gitignore) and never built in
+// CI: the animations above 180 px may only ever reach people inside the store app (Gym visual
+// licence, Part B), and Google Play delivers these packs itself.
+//
+// node scripts/android/make-asset-packs.mjs [--px 360,480,720,1080] [--builtin 240]
+// [--src-root /mnt/backup-hdd/opengym-media/quality] [--src 480=/other/480] [--limit N]
+// node scripts/android/make-asset-packs.mjs --clean
+// ... --dry-run only says what it would make
+//
+// Per quality and figure the same files as the iPhone's packs (scripts/media/make-pack-manifests.mjs,
+// packDrawingId in frontend/src/lib/anim-quality.js): `anim-<px>-<figure>`, inside it
+// `<packId>/<drawing>.webp`. Only qualities sharper than the built-in files (--builtin, the
+// APK's 240) and whose folder exists are made. A Play pack name must be a Gradle module name, so
+// anim-480-male is the module anim_480_male; a pack over Play's 1.5 GB per-pack limit is split
+// into anim_480_male_p1, _p2, ... (the app fetches them together).
+//
+// Writes:
+// frontend/android/anim_<px>_<figure>[_pN]/ one asset-pack module each (files hard-linked)
+// frontend/android/asset-packs.settings.gradle include ':anim_...' for settings.gradle
+// frontend/android/asset-packs.app.gradle android.assetPacks for app/build.gradle
+// frontend/android/app/src/play/assets/anim-packs.json what the app's plugin offers:
+// { "anim-480-male": { "parts": ["anim_480_male"], "files": 5619, "bytes": 786000000 }, ... }
+// Without these files (any checkout, CI) the Play build simply has no packs and shows its
+// built-in animations.
+//
+// --limit N: only the first N drawings of each pack (plus the one the app probes), for a quick
+// emulator test with bundletool --local-testing. Never for a release.
+//
+// LICENCE: names and sizes only. This never opens, decodes or looks at a media file.
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { EXDB } from '../../frontend/src/lib/exercises-data.js'
+import { PACK_QUALITIES, FIGURES, packId, packDrawingId } from '../../frontend/src/lib/anim-quality.js'
+import { drawingsFor } from '../media/make-pack-manifests.mjs'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+export const ANDROID = path.join(ROOT, 'frontend/android')
+// Play's limit is 1.5 GB per asset pack; a margin below it for the pack's own overhead.
+export const PART_MAX_BYTES = 1400 * 1024 * 1024
+const PROBE_EX = '0001' // lib/anim-packs.js probeFor: the drawing the app checks a pack by
+
+/** anim-480-male → anim_480_male (a Gradle module and Play pack name). */
+export const moduleName = (id, part = 0) => id.replace(/-/g, '_') + (part ? `_p${part}` : '')
+
+/** Splits [{ id, bytes }] into parts of at most `max` bytes each, in order. */
+export function splitParts(files, max = PART_MAX_BYTES) {
+ const parts = [[]]
+ let size = 0
+ for (const f of files) {
+ if (size + f.bytes > max && parts.at(-1).length) { parts.push([]); size = 0 }
+ parts.at(-1).push(f)
+ size += f.bytes
+ }
+ return parts
+}
+
+/**
+ * The packs to make: [{ id, px, figure, parts: [{ module, files: [{ id, src, bytes }] }], bytes }].
+ * `sizeOf(path)` is the file size or null when it is missing (a missing file is an error: a
+ * pack must hold every drawing the app may ask it for).
+ */
+export function planPacks({ qualities, srcFor, sizeOf, catalogue = EXDB, limit = 0, max = PART_MAX_BYTES }) {
+ const plan = []
+ for (const px of qualities) {
+ for (const figure of FIGURES) {
+ let ids = drawingsFor(catalogue, figure)
+ if (limit > 0) {
+ const probe = packDrawingId(catalogue.find(e => e.id === PROBE_EX), figure)
+ ids = [...new Set([probe, ...ids.slice(0, limit)])].filter(Boolean)
+ }
+ const files = ids.map(id => {
+ const src = path.join(srcFor(px), `${id}.webp`)
+ const bytes = sizeOf(src)
+ if (bytes == null) throw new Error(`missing ${px} px drawing ${id} (${src})`)
+ return { id, src, bytes }
+ })
+ const id = packId(px, figure)
+ const groups = splitParts(files, max)
+ plan.push({
+ id, px, figure,
+ bytes: files.reduce((n, f) => n + f.bytes, 0),
+ parts: groups.map((g, i) => ({ module: moduleName(id, groups.length > 1 ? i + 1 : 0), files: g })),
+ })
+ }
+ }
+ return plan
+}
+
+export const moduleGradle = name => `// Generated by scripts/android/make-asset-packs.mjs: not committed.
+apply plugin: 'com.android.asset-pack'
+
+assetPack {
+ packName = "${name}"
+ dynamicDelivery {
+ deliveryType = "on-demand"
+ }
+}
+`
+
+/** What the app's plugin reads (assets/anim-packs.json). */
+export const packIndex = plan => Object.fromEntries(plan.map(p => [p.id, {
+ parts: p.parts.map(x => x.module),
+ files: p.parts.reduce((n, x) => n + x.files.length, 0),
+ bytes: p.bytes,
+}]))
+
+const GENERATED = ['asset-packs.settings.gradle', 'asset-packs.app.gradle', 'app/src/play/assets/anim-packs.json']
+
+export function clean(android = ANDROID) {
+ for (const d of fs.readdirSync(android)) {
+ if (/^anim_\d+_(male|female)(_p\d+)?$/.test(d)) fs.rmSync(path.join(android, d), { recursive: true, force: true })
+ }
+ for (const f of GENERATED) fs.rmSync(path.join(android, f), { force: true })
+}
+
+function place(src, dest) {
+ try { fs.linkSync(src, dest) } catch { fs.copyFileSync(src, dest) }
+}
+
+export function write(plan, android = ANDROID) {
+ clean(android)
+ for (const p of plan) {
+ for (const part of p.parts) {
+ const dir = path.join(android, part.module)
+ const assets = path.join(dir, 'src/main/assets', p.id)
+ fs.mkdirSync(assets, { recursive: true })
+ fs.writeFileSync(path.join(dir, 'build.gradle'), moduleGradle(part.module))
+ for (const f of part.files) place(f.src, path.join(assets, `${f.id}.webp`))
+ }
+ }
+ const modules = plan.flatMap(p => p.parts.map(x => x.module))
+ const head = '// Generated by scripts/android/make-asset-packs.mjs: not committed.\n'
+ fs.writeFileSync(path.join(android, 'asset-packs.settings.gradle'), head + modules.map(m => `include ':${m}'`).join('\n') + '\n')
+ fs.writeFileSync(path.join(android, 'asset-packs.app.gradle'), head + `android {\n assetPacks = [${modules.map(m => `":${m}"`).join(', ')}]\n}\n`)
+ const assets = path.join(android, 'app/src/play/assets')
+ fs.mkdirSync(assets, { recursive: true })
+ fs.writeFileSync(path.join(assets, 'anim-packs.json'), JSON.stringify(packIndex(plan), null, 2) + '\n')
+}
+
+function main(argv) {
+ const opt = name => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : null }
+ if (argv.includes('--clean')) { clean(); console.log('asset packs removed from the Android project'); return }
+ const builtin = Number(opt('--builtin') || 240)
+ const srcRoot = opt('--src-root') || '/mnt/backup-hdd/opengym-media/quality'
+ const overrides = Object.fromEntries(argv.flatMap((a, i) => (a === '--src' ? [argv[i + 1].split('=')] : [])).map(([px, dir]) => [Number(px), dir]))
+ const srcFor = px => overrides[px] || path.join(srcRoot, String(px))
+ const asked = opt('--px') ? opt('--px').split(',').map(Number) : PACK_QUALITIES
+ if (asked.some(px => !PACK_QUALITIES.includes(px))) { console.error(`--px: only ${PACK_QUALITIES.join(', ')}`); process.exit(2) }
+ const qualities = asked.filter(px => px > builtin && fs.existsSync(srcFor(px)))
+ const skipped = asked.filter(px => !qualities.includes(px))
+ if (skipped.length) console.log(`skipped (not sharper than ${builtin} px, or no folder): ${skipped.join(', ')}`)
+ if (!qualities.length) { console.error('no quality to make a pack of'); process.exit(1) }
+ const limit = Number(opt('--limit') || 0)
+ const sizeOf = f => { try { return fs.statSync(f).size } catch { return null } }
+ const plan = planPacks({ qualities, srcFor, sizeOf, limit })
+ if (!argv.includes('--dry-run')) write(plan)
+ for (const p of plan) {
+ console.log(`${p.id}: ${p.parts.reduce((n, x) => n + x.files.length, 0)} files, ${(p.bytes / 1024 / 1024).toFixed(1)} MB, ${p.parts.map(x => x.module).join(' + ')}`)
+ }
+ if (limit) console.log(`--limit ${limit}: a TEST set, not for a release`)
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) main(process.argv.slice(2))