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.

Animation packs: read them through Background Assets, not by path

Duarte Santosc222284b7391
diff --git a/frontend/ios/App/AnimationPacksDownloader/Info.plist b/frontend/ios/App/AnimationPacksDownloader/Info.plist
index 01d2ff89b..25fa1c17e 100644
--- a/frontend/ios/App/AnimationPacksDownloader/Info.plist
+++ b/frontend/ios/App/AnimationPacksDownloader/Info.plist
@@ -22,10 +22,6 @@
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>BAAppGroupID</key>
<string>group.ch.opengym.app</string>
- <key>BAHasManagedAssetPacks</key>
- <true/>
- <key>BAUsesAppleHosting</key>
- <true/>
<key>EXAppExtensionAttributes</key>
<dict>
<key>EXExtensionPointIdentifier</key>
diff --git a/frontend/ios/App/App/AnimationPacksPlugin.swift b/frontend/ios/App/App/AnimationPacksPlugin.swift
index 3499be3b1..fddffdca5 100644
--- a/frontend/ios/App/App/AnimationPacksPlugin.swift
+++ b/frontend/ios/App/App/AnimationPacksPlugin.swift
@@ -2,6 +2,7 @@ import Foundation
import Capacitor
import Network
import System
+import WebKit
#if canImport(BackgroundAssets)
import BackgroundAssets
#endif
@@ -15,6 +16,14 @@ import BackgroundAssets
* The page side is frontend/src/lib/anim-packs.js. On an older iOS every call answers
* "unavailable" and the app shows its built-in animations.
*
+ * Reading a pack's files: Background Assets keeps all downloaded packs as one shared namespace
+ * that is only meant to be read through AssetPackManager (contents(at:), descriptor(for:)); a
+ * URL from url(for:) is valid for this process only and is not a folder with the pack's files in
+ * it (build 30 showed a "downloaded" pack of 0.1 MB and no new animations). So the page never
+ * gets a path: it asks for opengym-pack://<packId>/<drawing>.webp, which AnimationPackSchemeHandler
+ * answers with the file's bytes from contents(at:searchingInAssetPackWithID:), memory-mapped, on a
+ * background queue. Nothing is copied and nothing leaves the app.
+ *
* The app needs, in Info.plist, BAAppGroupID, BAHasManagedAssetPacks and BAUsesAppleHosting, and
* the downloader extension (AnimationPacksDownloader), which the system runs to fetch packs.
*/
@@ -28,13 +37,15 @@ public class AnimationPacksPlugin: CAPPlugin, CAPBridgedPlugin {
CAPPluginMethod(name: "download", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "remove", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "localPath", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "info", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "diagnose", returnType: CAPPluginReturnPromise),
]
/// Only the ids the app knows: a pack id from the page goes nowhere else.
- private static let packPattern = try! NSRegularExpression(pattern: "^anim-(240|360|480|720|1080)-(male|female)$")
+ static let packPattern = try! NSRegularExpression(pattern: "^anim-(240|360|480|720|1080)-(male|female)$")
private static let probePattern = try! NSRegularExpression(pattern: "^[0-9]{4,5}$")
- private static func matches(_ re: NSRegularExpression, _ s: String) -> Bool {
+ static func matches(_ re: NSRegularExpression, _ s: String) -> Bool {
re.firstMatch(in: s, range: NSRange(s.startIndex..., in: s)) != nil
}
@@ -55,7 +66,7 @@ public class AnimationPacksPlugin: CAPPlugin, CAPBridgedPlugin {
/// extension. Background Assets stops the app outright (a "programmer error") when the group
/// or the extension is missing, as in an unsigned simulator build, so without them the packs
/// are simply not offered and nothing touches AssetPackManager.
- private static let supported: Bool = {
+ static let supported: Bool = {
guard #available(iOS 26.0, *) else { return false }
let info = Bundle.main.infoDictionary ?? [:]
guard info["BAUsesAppleHosting"] as? Bool == true, let group = info["BAAppGroupID"] as? String else { return false }
@@ -65,26 +76,103 @@ public class AnimationPacksPlugin: CAPPlugin, CAPBridgedPlugin {
}()
private var supported: Bool { AnimationPacksPlugin.supported }
+ /// A TestFlight (or development) build: the page shows the packs' details row there.
+ private static let testFlight: Bool = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
+
@objc func available(_ call: CAPPluginCall) {
- call.resolve(["available": supported])
+ call.resolve(["available": supported, "testflight": AnimationPacksPlugin.testFlight])
}
+ /// The URL the page reads a pack's files from (AnimationPackSchemeHandler).
+ static func base(_ id: String) -> String { "\(AnimationPackSchemeHandler.scheme)://\(id)" }
+
+ /// 'ready' when the pack is on this device and its probe file can be read, with its size on
+ /// disk (worked out once per pack version, then kept: it walks every file).
@objc func status(_ call: CAPPluginCall) {
guard let (id, probe) = packArgs(call, probe: true) else { return }
- guard supported, let folder = localFolder(id, probe) else {
- call.resolve(["state": "none"])
+ guard supported else { call.resolve(["state": "none"]); return }
+ #if canImport(BackgroundAssets)
+ if #available(iOS 26.0, *) {
+ Task {
+ let manager = AssetPackManager.shared
+ guard await manager.assetPackIsAvailableLocally(withID: id),
+ AnimationPacksPlugin.readable(id, probe) else {
+ call.resolve(["state": "none"])
+ return
+ }
+ call.resolve(["state": "ready", "bytes": Int(await AnimationPacksPlugin.localBytes(id)), "base": AnimationPacksPlugin.base(id)])
+ }
return
}
- call.resolve(["state": "ready", "bytes": AnimationPacksPlugin.size(of: folder)])
+ #endif
+ call.resolve(["state": "none"])
}
+ /// Kept for older pages: the base to read the pack's files from, never a file path.
@objc func localPath(_ call: CAPPluginCall) {
guard let (id, probe) = packArgs(call, probe: true) else { return }
- guard supported, let folder = localFolder(id, probe) else {
+ guard supported, AnimationPacksPlugin.readable(id, probe) else {
call.reject("not downloaded", "unavailable")
return
}
- call.resolve(["path": folder.path])
+ call.resolve(["path": AnimationPacksPlugin.base(id), "base": AnimationPacksPlugin.base(id)])
+ }
+
+ /// What a pack costs to download, before it is: { downloadSize } in bytes, from Apple.
+ @objc func info(_ call: CAPPluginCall) {
+ guard let (id, _) = packArgs(call, probe: false) else { return }
+ guard supported else { call.resolve([:]); return }
+ #if canImport(BackgroundAssets)
+ if #available(iOS 26.0, *) {
+ Task {
+ if let pack = try? await AssetPackManager.shared.assetPack(withID: id) {
+ call.resolve(["downloadSize": pack.downloadSize, "version": pack.version])
+ } else {
+ call.resolve([:])
+ }
+ }
+ return
+ }
+ #endif
+ call.resolve([:])
+ }
+
+ /// For the details row (TestFlight): everything this side knows about one pack, as text.
+ @objc func diagnose(_ call: CAPPluginCall) {
+ guard let (id, probe) = packArgs(call, probe: true) else { return }
+ var out: [String: Any] = ["supported": supported, "base": AnimationPacksPlugin.base(id), "probe": "\(id)/\(probe).webp"]
+ guard supported else { call.resolve(out); return }
+ #if canImport(BackgroundAssets)
+ if #available(iOS 26.0, *) {
+ Task {
+ let manager = AssetPackManager.shared
+ out["local"] = await manager.assetPackIsAvailableLocally(withID: id)
+ out["status"] = AnimationPacksPlugin.describe(await manager.localStatus(ofAssetPackWithID: id))
+ if let v = try? await manager.localVersion(ofAssetPackWithID: id) { out["version"] = v }
+ do {
+ let data = try manager.contents(at: FilePath("\(id)/\(probe).webp"), searchingInAssetPackWithID: id, options: .mappedIfSafe)
+ out["probeBytes"] = data.count
+ } catch {
+ out["probeError"] = String(describing: error)
+ }
+ if let url = try? manager.url(for: FilePath("\(id)/\(probe).webp")) {
+ out["probeUrl"] = url.path
+ out["probeUrlExists"] = FileManager.default.fileExists(atPath: url.path)
+ let folder = url.deletingLastPathComponent()
+ out["folderFiles"] = (try? FileManager.default.contentsOfDirectory(atPath: folder.path).count) ?? -1
+ }
+ do {
+ out["localSize"] = Int(try await manager.localSize(ofAssetPackWithID: id, calculationMethod: .allocated))
+ } catch {
+ out["localSizeError"] = String(describing: error)
+ }
+ if let pack = try? await manager.assetPack(withID: id) { out["downloadSize"] = pack.downloadSize }
+ call.resolve(out)
+ }
+ return
+ }
+ #endif
+ call.resolve(out)
}
@objc func download(_ call: CAPPluginCall) {
@@ -143,30 +231,48 @@ public class AnimationPacksPlugin: CAPPlugin, CAPBridgedPlugin {
call.resolve()
}
- /// The folder a downloaded pack's files are in, checked through one file it holds: Background
- /// Assets reads all downloaded packs as one tree and answers for a path, not for a pack, with
- /// a well-formed URL whether or not anything is there. Every pack keeps its files under its own
- /// id, so the folder is that pack's alone.
- private func localFolder(_ id: String, _ probe: String) -> URL? {
+ /// Whether the pack's probe file can be read through Background Assets: the test that the
+ /// pack is really there for the scheme handler, not only listed as downloaded.
+ static func readable(_ id: String, _ probe: String) -> Bool {
#if canImport(BackgroundAssets)
if #available(iOS 26.0, *) {
- guard let file = try? AssetPackManager.shared.url(for: FilePath("\(id)/\(probe).webp")),
- FileManager.default.fileExists(atPath: file.path) else { return nil }
- return file.deletingLastPathComponent()
+ guard let fd = try? AssetPackManager.shared.descriptor(for: FilePath("\(id)/\(probe).webp"), searchingInAssetPackWithID: id) else { return false }
+ try? fd.close()
+ return true
}
#endif
- return nil
+ return false
}
- private static func size(of folder: URL) -> Int {
- let keys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey]
- guard let files = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: keys) else { return 0 }
- var total = 0
- for case let f as URL in files {
- let v = try? f.resourceValues(forKeys: Set(keys))
- total += v?.totalFileAllocatedSize ?? v?.fileAllocatedSize ?? 0
- }
- return total
+ /// The pack's size on disk, from Background Assets, kept per pack and version (the count walks
+ /// every one of its thousands of files).
+ @available(iOS 26.0, *)
+ private static func localBytes(_ id: String) async -> Int64 {
+ #if canImport(BackgroundAssets)
+ let manager = AssetPackManager.shared
+ let version = (try? await manager.localVersion(ofAssetPackWithID: id)) ?? -1
+ let key = "animPackBytes.\(id).\(version)"
+ let kept = UserDefaults.standard.object(forKey: key) as? Int64
+ if let kept = kept, kept > 0 { return kept }
+ let bytes = (try? await manager.localSize(ofAssetPackWithID: id, calculationMethod: .allocated)) ?? 0
+ if bytes > 0 { UserDefaults.standard.set(bytes, forKey: key) }
+ return bytes
+ #else
+ return 0
+ #endif
+ }
+
+ @available(iOS 26.0, *)
+ private static func describe(_ s: AssetPack.Status) -> String {
+ var parts: [String] = []
+ if s.contains(.downloadAvailable) { parts.append("downloadAvailable") }
+ if s.contains(.downloading) { parts.append("downloading") }
+ if s.contains(.downloaded) { parts.append("downloaded") }
+ if s.contains(.upToDate) { parts.append("upToDate") }
+ if s.contains(.outOfDate) { parts.append("outOfDate") }
+ if s.contains(.updateAvailable) { parts.append("updateAvailable") }
+ if s.contains(.obsolete) { parts.append("obsolete") }
+ return parts.isEmpty ? "none" : parts.joined(separator: ",")
}
/// Whether the phone is on a network that costs nothing extra (Wi-Fi or a cable), now.
@@ -195,3 +301,63 @@ private final class Once: @unchecked Sendable {
return true
}
}
+
+/**
+ * Serves opengym-pack://<packId>/<drawing>.webp to the web view from the downloaded asset pack,
+ * read through AssetPackManager (memory-mapped) off the main thread. Only the app's pack ids and
+ * plain drawing names; anything else is a 404. Registered on the web view's configuration by
+ * MainViewController.
+ */
+final class AnimationPackSchemeHandler: NSObject, WKURLSchemeHandler {
+ static let scheme = "opengym-pack"
+ private static let filePattern = try! NSRegularExpression(pattern: "^[A-Za-z0-9_-]{1,64}\\.webp$")
+ private let queue = DispatchQueue(label: "ch.opengym.app.anim-pack-files", qos: .userInitiated, attributes: .concurrent)
+ private var stopped = Set<ObjectIdentifier>()
+ private let lock = NSLock()
+
+ func webView(_ webView: WKWebView, start task: WKURLSchemeTask) {
+ guard let url = task.request.url, let id = url.host,
+ AnimationPacksPlugin.matches(AnimationPacksPlugin.packPattern, id) else { return fail(task, 404) }
+ let file = url.lastPathComponent
+ guard url.pathComponents.count == 2, AnimationPacksPlugin.matches(AnimationPackSchemeHandler.filePattern, file) else { return fail(task, 404) }
+ let key = ObjectIdentifier(task)
+ queue.async {
+ var data: Data?
+ #if canImport(BackgroundAssets)
+ if #available(iOS 26.0, *) {
+ data = try? AssetPackManager.shared.contents(at: FilePath("\(id)/\(file)"), searchingInAssetPackWithID: id, options: .mappedIfSafe)
+ }
+ #endif
+ DispatchQueue.main.async {
+ guard self.take(key) else { return }
+ guard let data = data else { return self.fail(task, 404) }
+ let headers = [
+ "Content-Type": "image/webp",
+ "Content-Length": String(data.count),
+ "Cache-Control": "max-age=31536000, immutable",
+ "Access-Control-Allow-Origin": "*",
+ ]
+ let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: headers)!
+ task.didReceive(response)
+ task.didReceive(data)
+ task.didFinish()
+ }
+ }
+ }
+
+ func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {
+ lock.lock(); stopped.insert(ObjectIdentifier(task)); lock.unlock()
+ }
+
+ /// False once WebKit stopped the task: answering it then would throw.
+ private func take(_ key: ObjectIdentifier) -> Bool {
+ lock.lock(); defer { lock.unlock() }
+ return stopped.remove(key) == nil
+ }
+
+ private func fail(_ task: WKURLSchemeTask, _ code: Int) {
+ guard let url = task.request.url else { return }
+ task.didReceive(HTTPURLResponse(url: url, statusCode: code, httpVersion: "HTTP/1.1", headerFields: ["Access-Control-Allow-Origin": "*"])!)
+ task.didFinish()
+ }
+}
diff --git a/frontend/ios/App/App/MainViewController.swift b/frontend/ios/App/App/MainViewController.swift
index 46cf0e14b..51e1bf342 100644
--- a/frontend/ios/App/App/MainViewController.swift
+++ b/frontend/ios/App/App/MainViewController.swift
@@ -1,6 +1,7 @@
import Capacitor
import UIKit
import UserNotifications
+import WebKit
/**
* The app's own bridge view controller (Main.storyboard). Since Capacitor 6 the bridge only loads
@@ -8,6 +9,15 @@ import UserNotifications
* that live in the app itself are registered here, or the page finds none of them.
*/
class MainViewController: CAPBridgeViewController {
+ /// The downloaded animation packs, read through Background Assets (AnimationPacksPlugin.swift).
+ private let packFiles = AnimationPackSchemeHandler()
+
+ override open func webViewConfiguration(for instanceConfiguration: InstanceConfiguration) -> WKWebViewConfiguration {
+ let config = super.webViewConfiguration(for: instanceConfiguration)
+ config.setURLSchemeHandler(packFiles, forURLScheme: AnimationPackSchemeHandler.scheme)
+ return config
+ }
+
override open func capacitorDidLoad() {
bridge?.registerPluginInstance(PrintPlugin())
bridge?.registerPluginInstance(RestAlertPlugin())
diff --git a/frontend/src/components/Animations.jsx b/frontend/src/components/Animations.jsx
index 6ba764c8f..a5fb31211 100644
--- a/frontend/src/components/Animations.jsx
+++ b/frontend/src/components/Animations.jsx
@@ -1,14 +1,14 @@
// Settings → Workout → Animation quality, and the hooks that put the chosen quality on screen
// (store apps only; the web and a self-hosted server show nothing new and keep their 180 px
// files). The rules are lib/anim-quality.js, the packs and the per-device choice lib/anim-packs.js.
-import { useEffect, useSyncExternalStore } from 'react'
+import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { useStore } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
import { MOBILE } from '../lib/mobile.js'
import { gifSrc, figureOf } from '../lib/exercises.js'
import { fmtMB } from '../lib/media-limits.js'
import { BUILTIN_PX, packQualities, packId, wantedQuality, clipSources } from '../lib/anim-quality.js'
-import { subscribe, getState, installedBases, deviceInfo, refresh, ensureWanted, writePrefs, download, remove } from '../lib/anim-packs.js'
+import { subscribe, getState, installedBases, deviceInfo, refresh, ensureWanted, writePrefs, download, remove, downloadBytes, diagnose, ALL_PACKS } from '../lib/anim-packs.js'
import { Section, Row, Switch, Button } from './ui.jsx'
import { useUI } from '../store/useUI.js'
@@ -52,15 +52,42 @@ export function AnimationQualityRow() {
onClick={() => useUI.getState().openSheet(close => <AnimationQualitySheet close={close} />)} />
}
-// One pack's line under its quality: downloaded and how big, on its way, waiting for Wi-Fi.
-function packLine(p) {
- if (!p || p.state === 'none' || !p.state) return t('Not downloaded')
- if (p.state === 'ready') return t('Downloaded · {0}', t('{0} MB', fmtMB(Math.max(0.1, (p.bytes || 0) / MB))))
+// One pack's line under its quality: downloaded and how big on this device, on its way, waiting
+// for Wi-Fi, or what it would take to download ("~750 MB").
+const sizeText = bytes => t('{0} MB', fmtMB(Math.max(0.1, bytes / MB)))
+function packLine(p, id) {
+ if (!p || p.state === 'none' || !p.state) {
+ const dl = downloadBytes(id)
+ return dl ? t('Not downloaded') + ' · ~' + sizeText(dl) : t('Not downloaded')
+ }
+ if (p.state === 'ready') {
+ const dl = downloadBytes(id)
+ return t('Downloaded · {0}', p.bytes > 0 ? sizeText(p.bytes) : dl ? '~' + sizeText(dl) : '…')
+ }
if (p.state === 'downloading') return t('Downloading… {0}%', Math.round((p.progress || 0) * 100))
if (p.state === 'needs-wifi') return t('Waiting for Wi-Fi')
return t('Download failed. Tap to try again.')
}
+// TestFlight builds (or the title tapped five times): what the native side knows about each pack
+// and whether its sample drawing loads, for a screenshot when a download does not show. Not
+// translated on purpose: it is for the person fixing it.
+function PackDetails({ figure }) {
+ const [rows, setRows] = useState(null)
+ const run = async () => {
+ setRows([])
+ const ids = ALL_PACKS.filter(id => id.endsWith('-' + figure))
+ const out = []
+ for (const id of ids) { out.push(await diagnose(id)); setRows([...out]) }
+ }
+ return <Section title="Details">
+ <Row icon="info" title="Check the packs" subtitle="State, where they are read from, a sample drawing" accessory="chevron" onClick={run} />
+ {rows && <pre className="small dim" style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all', userSelect: 'text', padding: '8px 12px', margin: 0 }}>
+ {rows.length ? rows.map(r => JSON.stringify(r, null, 1)).join('\n\n') : '…'}
+ </pre>}
+ </Section>
+}
+
export function AnimationQualitySheet({ close }) {
const packs = useAnimPacks()
const figure = useStore(s => figureOf(s.S))
@@ -69,8 +96,11 @@ export function AnimationQualitySheet({ close }) {
const retry = id => () => download(id)
const qualities = packs.available ? packQualities() : []
const ready = Object.entries(packs.packs).filter(([, p]) => p.state === 'ready')
+ const taps = useRef(0)
+ const [details, setDetails] = useState(false)
+ const tapTitle = () => { taps.current += 1; if (taps.current >= 5) setDetails(true) }
return <>
- <h3>{t('Animation quality')}</h3>
+ <h3 onClick={tapTitle}>{t('Animation quality')}</h3>
<Section footer={packs.available
? t('Sharper animations download once per figure. Until they’re here you see the built-in ones, so nothing ever goes blank.')
: t('Sharper animations aren’t available on this device yet. The built-in ones work everywhere.')}>
@@ -81,7 +111,7 @@ export function AnimationQualitySheet({ close }) {
const id = packId(px, figure)
const p = packs.packs[id]
const failed = p?.state === 'failed' || p?.state === 'needs-wifi'
- return <Row key={px} title={t('{0} px', px)} subtitle={packLine(p)} accessory={choice === px ? 'check' : 'none'}
+ return <Row key={px} title={t('{0} px', px)} subtitle={packLine(p, id)} accessory={choice === px ? 'check' : 'none'}
onClick={failed && choice === px ? retry(id) : () => pick(px)} />
})}
</Section>
@@ -94,11 +124,12 @@ export function AnimationQualitySheet({ close }) {
{ready.map(([id, p]) => {
const [, px, fig] = /^anim-(\d+)-(male|female)$/.exec(id) || []
return <Row key={id} title={t('{0} px', px) + ' · ' + (fig === 'female' ? t('Female') : t('Male'))}
- subtitle={t('{0} MB', fmtMB(Math.max(0.1, (p.bytes || 0) / MB)))}>
+ subtitle={p.bytes > 0 ? sizeText(p.bytes) : '…'}>
<Button size="sm" variant="danger" onClick={() => remove(id)}>{t('Delete')}</Button>
</Row>
})}
</Section>}
+ {packs.available && (packs.testflight || details) && <PackDetails figure={figure} />}
<Button variant="ghost" className="dim" onClick={close}>{t('Done')}</Button>
</>
}
diff --git a/frontend/src/components/Animations.test.jsx b/frontend/src/components/Animations.test.jsx
index a1659b502..17e3905f5 100644
--- a/frontend/src/components/Animations.test.jsx
+++ b/frontend/src/components/Animations.test.jsx
@@ -141,3 +141,20 @@ describe('what the animation shows', () => {
expect(img().getAttribute('src')).toBe('exercise-media/clip/2476.webp')
})
})
+
+describe('sizes and details', () => {
+ it('says what a pack takes to download before it is downloaded', async () => {
+ await packs.refresh()
+ await mount(<AnimationQualitySheet close={() => {}} />)
+ const row = rowByTitle('480 px')
+ expect(row.textContent).toMatch(/Not downloaded · ~742 MB/)
+ })
+ it('shows the packs’ details after five taps on the title', async () => {
+ await packs.refresh()
+ await mount(<AnimationQualitySheet close={() => {}} />)
+ expect(host.textContent).not.toContain('Check the packs')
+ const h3 = host.querySelector('h3')
+ for (let i = 0; i < 5; i++) await act(async () => { h3.click() })
+ expect(host.textContent).toContain('Check the packs')
+ })
+})
diff --git a/frontend/src/lib/anim-packs.js b/frontend/src/lib/anim-packs.js
index 08bff0a11..375521534 100644
--- a/frontend/src/lib/anim-packs.js
+++ b/frontend/src/lib/anim-packs.js
@@ -2,16 +2,21 @@
// and the person's choice of quality. The rules are lib/anim-quality.js; this is the state around
// them and the bridge to the native AnimationPacks plugin:
//
-// available() → { available } iOS 26+ with Apple-hosted packs
-// status({ packId, probe }) → { state: 'ready'|'none', bytes?, downloadSize? }
+// available() → { available, testflight } iOS 26+ with Apple-hosted packs
+// status({ packId, probe }) → { state: 'ready'|'none', bytes?, base? }
+// info({ packId }) → { downloadSize? } what the download costs, from Apple
+// diagnose({ packId, probe }) → what the native side knows, for the details row
// download({ packId, wifiOnly, probe }) → resolves once installed; 'progress' events
// { packId, fraction }; rejects with a code:
// 'needs-wifi', 'unavailable', 'cancelled', 'failed'
// remove({ packId })
-// localPath({ packId, probe }) → { path } the folder the pack's <id>.webp sit in
+// localPath({ packId, probe }) → { base } (older native sides: { path })
//
-// `probe` is one drawing the pack holds, for a native side that can only find a pack's folder
-// through one of its files. iOS: ios/App/App/AnimationPacksPlugin.swift. Android answers
+// A pack's files are read from `base` + '/<drawing>.webp'. On iOS that is opengym-pack://<packId>,
+// which the app answers from Background Assets itself: a downloaded pack is not a folder a page
+// could be pointed at (build 30: "downloaded, 0.1 MB", no new animations). `probe` is one drawing
+// the pack holds, the native side's test that the pack can really be read.
+// iOS: ios/App/App/AnimationPacksPlugin.swift. Android answers
// "unavailable" until Play Asset Delivery comes (and the sideloaded APK never has packs).
//
// The choice is this device's, not the profile's: kept in localStorage, never in S, so it never
@@ -24,6 +29,9 @@ import { PACK_QUALITIES, FIGURES, packId, packDrawingId, readChoice, wantedPack,
export const PREFS_KEY = 'gym_anim_v1'
export const ALL_PACKS = PACK_QUALITIES.flatMap(px => FIGURES.map(f => packId(px, f)))
const PROBE_EX = '0001'
+const MB = 1024 * 1024
+// What the packs uploaded so far take to download, until Apple's own figure (info) is in.
+export const KNOWN_DOWNLOAD_BYTES = { 'anim-480-male': 749.5 * MB, 'anim-480-female': 742.0 * MB }
export const probeFor = id => packDrawingId(EXIDX[PROBE_EX], id.endsWith('-female') ? 'female' : 'male')
/* ---------------------------------------------------------------- the choice, per device */
@@ -48,8 +56,8 @@ export const deviceInfo = () => {
}
/* ---------------------------------------------------------------- state */
-// packs: { [packId]: { state: 'none'|'ready'|'downloading'|'failed'|'needs-wifi', progress, bytes, base } }
-let state = { available: false, checked: false, packs: {}, prefs: readPrefs() }
+// packs: { [packId]: { state: 'none'|'ready'|'downloading'|'failed'|'needs-wifi', progress, bytes, base, downloadSize } }
+let state = { available: false, testflight: false, checked: false, packs: {}, prefs: readPrefs() }
const listeners = new Set()
const emit = () => { for (const fn of listeners) fn() }
export const subscribe = fn => { listeners.add(fn); return () => listeners.delete(fn) }
@@ -74,20 +82,39 @@ async function readPack(p, id) {
try {
const st = await p.Packs.status({ packId: id, probe: probeFor(id) })
if (st?.state !== 'ready') { setPack(id, { state: state.packs[id]?.state === 'downloading' ? 'downloading' : 'none', bytes: 0, base: null }); return }
- const { path } = await p.Packs.localPath({ packId: id, probe: probeFor(id) })
- setPack(id, { state: 'ready', bytes: Number(st.bytes) || 0, base: path ? p.toUrl(path) : null, progress: 1 })
+ let base = typeof st.base === 'string' && st.base ? st.base : null
+ if (!base) {
+ const r = await p.Packs.localPath({ packId: id, probe: probeFor(id) })
+ base = r?.base || (r?.path ? (r.path.startsWith('/') ? p.toUrl(r.path) : r.path) : null)
+ }
+ setPack(id, { state: 'ready', bytes: Number(st.bytes) || 0, base, progress: 1 })
} catch { setPack(id, { state: 'none', base: null }) }
}
+// Apple's download size for a pack, when it says (it needs the network once).
+async function readInfo(p, id) {
+ try {
+ const r = await p.Packs.info({ packId: id })
+ const n = Number(r?.downloadSize)
+ if (n > 0) setPack(id, { downloadSize: n })
+ } catch { /* the built-in figure, or none */ }
+}
+
+/** What downloading a pack takes, in bytes: Apple's figure, else the known one, else null. */
+export const downloadBytes = (id, s = state) => s.packs[id]?.downloadSize || KNOWN_DOWNLOAD_BYTES[id] || null
+
/** Asks the native side what it has. Once at start, and after every download or removal. */
export async function refresh() {
const p = await packsPlugin()
if (!p) { state = { ...state, checked: true, available: false }; emit(); return state }
- let available = false
- try { available = !!(await p.Packs.available())?.available } catch { available = false }
- state = { ...state, checked: true, available }
+ let available = false, testflight = false
+ try { const r = await p.Packs.available(); available = !!r?.available; testflight = !!r?.testflight } catch { available = false }
+ state = { ...state, checked: true, available, testflight }
emit()
- if (available) await Promise.all(ALL_PACKS.map(id => readPack(p, id)))
+ if (available) {
+ await Promise.all(ALL_PACKS.map(id => readPack(p, id)))
+ ALL_PACKS.forEach(id => { readInfo(p, id) })
+ }
return state
}
@@ -143,7 +170,33 @@ export function ensureWanted(figure, device = deviceInfo()) {
return download(id)
}
+/**
+ * For the details row (TestFlight builds): what the native side says about one pack, and whether
+ * its probe drawing really loads as an image from where the page reads it.
+ */
+export async function diagnose(id, loadImage = defaultLoadImage) {
+ const p = await packsPlugin()
+ const out = { packId: id, state: state.packs[id]?.state || 'none', base: state.packs[id]?.base || null }
+ if (!p) return { ...out, native: null, image: 'no plugin' }
+ try { out.native = await p.Packs.diagnose({ packId: id, probe: probeFor(id) }) } catch (e) { out.native = { error: String(e?.message || e) } }
+ const base = out.base || out.native?.base
+ out.image = base ? await loadImage(base.replace(/\/$/, '') + '/' + probeFor(id) + '.webp') : 'no base'
+ return out
+}
+
+function defaultLoadImage(src) {
+ return new Promise(resolve => {
+ try {
+ const img = new Image()
+ const t = setTimeout(() => resolve('timeout'), 8000)
+ img.onload = () => { clearTimeout(t); resolve(`ok ${img.naturalWidth}×${img.naturalHeight}`) }
+ img.onerror = () => { clearTimeout(t); resolve('error') }
+ img.src = src
+ } catch (e) { resolve('error ' + String(e?.message || e)) }
+ })
+}
+
export function _resetAnimPacks(next = {}) {
pluginP = null; progressHooked = false; downloads.clear()
- state = { available: false, checked: false, packs: {}, prefs: readPrefs(), ...next }
+ state = { available: false, testflight: false, checked: false, packs: {}, prefs: readPrefs(), ...next }
}
diff --git a/frontend/src/lib/anim-packs.test.js b/frontend/src/lib/anim-packs.test.js
index c83094c66..03fd8fbc0 100644
--- a/frontend/src/lib/anim-packs.test.js
+++ b/frontend/src/lib/anim-packs.test.js
@@ -4,12 +4,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
/* The animation packs on this device (lib/anim-packs.js): the per-device choice, the bridge to
the native AnimationPacks plugin and the download a choice or a figure starts. The plugin is a
stand-in shaped like Capacitor's: a Proxy whose `then` is a native call that never answers (#42). */
-const mocks = vi.hoisted(() => ({ MOBILE: true, available: true, ready: new Set(), calls: [], listeners: {}, downloadFails: null }))
+const mocks = vi.hoisted(() => ({ MOBILE: true, available: true, ready: new Set(), calls: [], listeners: {}, downloadFails: null, base: false, info: {}, testflight: false }))
vi.mock('./mobile.js', () => ({ get MOBILE() { return mocks.MOBILE } }))
vi.mock('@capacitor/core', () => {
const impl = {
- available: async () => ({ available: mocks.available }),
- status: async ({ packId }) => (mocks.ready.has(packId) ? { state: 'ready', bytes: 5 * 1024 * 1024 } : { state: 'none' }),
+ available: async () => ({ available: mocks.available, testflight: mocks.testflight }),
+ status: async ({ packId }) => (mocks.ready.has(packId) ? { state: 'ready', bytes: 5 * 1024 * 1024, ...(mocks.base ? { base: 'opengym-pack://' + packId } : {}) } : { state: 'none' }),
+ info: async ({ packId }) => mocks.info[packId] || {},
+ diagnose: async ({ packId, probe }) => ({ local: mocks.ready.has(packId), probe: packId + '/' + probe + '.webp', base: 'opengym-pack://' + packId }),
localPath: async ({ packId }) => ({ path: '/var/packs/' + packId }),
download: async ({ packId, wifiOnly, probe }) => {
mocks.calls.push(['download', packId, wifiOnly, probe])
@@ -34,7 +36,7 @@ import * as packs from './anim-packs.js'
const phone = { shortSide: 390 }
beforeEach(() => {
localStorage.clear()
- mocks.MOBILE = true; mocks.available = true; mocks.ready = new Set(); mocks.calls = []; mocks.listeners = {}; mocks.downloadFails = null
+ mocks.MOBILE = true; mocks.available = true; mocks.ready = new Set(); mocks.calls = []; mocks.listeners = {}; mocks.downloadFails = null; mocks.base = false; mocks.info = {}; mocks.testflight = false
packs._resetAnimPacks()
})
@@ -122,3 +124,38 @@ describe('downloads', () => {
expect(mocks.calls).toEqual([['remove', 'anim-1080-male']])
})
})
+
+// Build 30: a pack Background Assets had downloaded read as "0.1 MB" and showed nothing, because
+// the page was pointed at a file path. Now the native side names the base to read it from.
+describe('reading a pack from where the app serves it', () => {
+ it('takes the base the native side gives (opengym-pack://<packId>), never a converted path', async () => {
+ mocks.base = true
+ mocks.ready.add('anim-480-female')
+ await packs.refresh()
+ expect(packs.getState().packs['anim-480-female']).toMatchObject({ state: 'ready', base: 'opengym-pack://anim-480-female' })
+ expect(packs.installedBases()).toEqual({ 'anim-480-female': 'opengym-pack://anim-480-female' })
+ })
+ it('knows what a download costs: Apple’s figure first, else the known one for 480', async () => {
+ mocks.info = { 'anim-720-male': { downloadSize: 1234567890 } }
+ await packs.refresh()
+ await new Promise(r => setTimeout(r, 0))
+ expect(packs.downloadBytes('anim-720-male')).toBe(1234567890)
+ expect(packs.downloadBytes('anim-480-male')).toBeCloseTo(749.5 * 1024 * 1024)
+ expect(packs.downloadBytes('anim-240-female')).toBeNull()
+ })
+ it('says whether this is a TestFlight build, for the details row', async () => {
+ mocks.testflight = true
+ await packs.refresh()
+ expect(packs.getState().testflight).toBe(true)
+ })
+ it('diagnose: what the native side knows and whether the sample drawing loads', async () => {
+ mocks.base = true
+ mocks.ready.add('anim-480-male')
+ await packs.refresh()
+ const tried = []
+ const d = await packs.diagnose('anim-480-male', async src => { tried.push(src); return 'ok 480×480' })
+ expect(d.native).toMatchObject({ local: true, base: 'opengym-pack://anim-480-male' })
+ expect(tried).toEqual(['opengym-pack://anim-480-male/' + packs.probeFor('anim-480-male') + '.webp'])
+ expect(d.image).toBe('ok 480×480')
+ })
+})