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.

Watch link: snapshots kept under the application context limit, link changes after launch, clip queue and cache bounded

Duarte Santos1730a6450c03
diff --git a/frontend/ios/App/App/WatchBridgePlugin.swift b/frontend/ios/App/App/WatchBridgePlugin.swift
index b2287deaa..62797a158 100644
--- a/frontend/ios/App/App/WatchBridgePlugin.swift
+++ b/frontend/ios/App/App/WatchBridgePlugin.swift
@@ -30,6 +30,8 @@ import WatchConnectivity
* WatchBridge.addListener('watchEvent', e => ...)
* await WatchBridge.sendClips({ wid, clips: [{ exId, path }] }) // the workout's animations
* await WatchBridge.openOnWatch() // { ok }: a workout started here opens the watch app
+ * await WatchBridge.dropClips() // the workout is over: clips still on their way are cancelled
+ * WatchBridge.addListener('watchState', ...) // activated, paired, installed changed: ask status again
*
* Animations: only the running workout's, only as files sent with transferFile (the watch keeps
* them while that workout runs and deletes them after). Each is what this phone shows for that
@@ -49,6 +51,7 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
CAPPluginMethod(name: "ack", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "sendClips", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "openOnWatch", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "dropClips", returnType: CAPPluginReturnPromise),
]
private let queue = DispatchQueue(label: "ch.opengym.watch-events")
@@ -70,6 +73,7 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
let s = WCSession.default
call.resolve([
"supported": true,
+ "activated": s.activationState == .activated,
"paired": s.isPaired,
"installed": s.isWatchAppInstalled,
"reachable": s.isReachable,
@@ -139,6 +143,25 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
}
}
+ /// The workout is over: its clips still waiting to go to the watch are cancelled (they would
+ /// pile up in the queue while the watch is away, and the watch drops them on arrival anyway).
+ @objc func dropClips(_ call: CAPPluginCall) {
+ if WCSession.isSupported(), WCSession.default.activationState == .activated {
+ WCSession.default.outstandingFileTransfers.forEach { $0.cancel() }
+ }
+ clipQueue.async { self.clipsSent = [:] }
+ call.resolve()
+ }
+
+ /// The phone's GIF cache (Caches/watch-clips): the most recently used few dozen are kept.
+ static func pruneClipCache(keep: Int = 60) {
+ let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("watch-clips")
+ let keys: [URLResourceKey] = [.contentModificationDateKey]
+ guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: keys), files.count > keep else { return }
+ let dated = files.map { ($0, (try? $0.resourceValues(forKeys: Set(keys)).contentModificationDate) ?? .distantPast) }
+ for (url, _) in dated.sorted(by: { $0.1 > $1.1 }).dropFirst(keep) { try? FileManager.default.removeItem(at: url) }
+ }
+
/// The clips already on their way for each workout, by exercise.
private var clipsSent: [String: Set<String>] = [:]
private let clipQueue = DispatchQueue(label: "ch.opengym.watch-clips", qos: .utility)
@@ -149,9 +172,12 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
guard s.activationState == .activated, s.isPaired, s.isWatchAppInstalled else { call.resolve(["sent": 0]); return }
let clips = (call.getArray("clips") ?? []).compactMap { $0 as? [String: Any] }
call.resolve(["queued": clips.count])
+ // Another workout's clips still queued (the watch was away): cancelled, this one's go first.
+ for t in s.outstandingFileTransfers where (t.file.metadata?["wid"] as? String) != wid { t.cancel() }
clipQueue.async {
var sent = self.clipsSent[wid] ?? []
if self.clipsSent.count > 4 { self.clipsSent = self.clipsSent.filter { $0.key == wid } }
+ defer { WatchBridgePlugin.pruneClipCache() }
for clip in clips {
guard let exId = clip["exId"] as? String, !sent.contains(exId),
let gif = WatchBridgePlugin.gifFor(clip, named: exId) else { continue }
@@ -170,7 +196,7 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
if let pack = clip["packId"] as? String, let drawing = clip["drawing"] as? String {
let out = dir.appendingPathComponent("\(pack)-\(drawing).gif")
- if FileManager.default.fileExists(atPath: out.path) { return out }
+ if FileManager.default.fileExists(atPath: out.path) { touch(out); return out }
guard let data = AnimationPacksPlugin.packData(pack, drawing) else { return nil }
return ClipCodec.makeGif(data: data, to: out, maxPixels: 160) ? out : nil
}
@@ -188,7 +214,7 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let safe = name.replacingOccurrences(of: "/", with: "_")
let out = dir.appendingPathComponent(safe + ".gif")
- if FileManager.default.fileExists(atPath: out.path) { return out }
+ if FileManager.default.fileExists(atPath: out.path) { touch(out); return out }
if source.pathExtension.lowercased() != "mp4" { return gifFromImage(source, to: out) }
let asset = AVURLAsset(url: source)
let seconds = CMTimeGetSeconds(asset.duration)
@@ -218,6 +244,11 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
return out
}
+ /// Used now: kept longest by the cache's pruning.
+ private static func touch(_ url: URL) {
+ try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: url.path)
+ }
+
/// An animated WebP or GIF, frame by frame with its delays (WatchCore ClipCodec, the same code
/// CI tests on a synthetic clip).
private static func gifFromImage(_ source: URL, to out: URL) -> URL? {
@@ -241,7 +272,15 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
}
}
- public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {}
+ /// The page asked for the status before the session was up (right after launch): it is told now.
+ public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
+ DispatchQueue.main.async { self.notifyListeners("watchState", data: ["activated": activationState == .activated]) }
+ }
+
+ /// A watch paired or unpaired, the app installed on it or removed.
+ public func sessionWatchStateDidChange(_ session: WCSession) {
+ DispatchQueue.main.async { self.notifyListeners("watchState", data: ["paired": session.isPaired, "installed": session.isWatchAppInstalled]) }
+ }
public func sessionDidBecomeInactive(_ session: WCSession) {}
public func sessionDidDeactivate(_ session: WCSession) {
// A different watch was paired: start a session with that one.
diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.js
index b3fbb44c2..b1faee9d1 100644
--- a/frontend/src/lib/watch-sync.js
+++ b/frontend/src/lib/watch-sync.js
@@ -336,6 +336,37 @@ export function shouldOpenOnWatch (prev, next, { prefs = readWatchPrefs(), now =
return Number.isFinite(start) && start > 0 && Math.abs(now - start) <= OPEN_ON_WATCH_WINDOW_MS
}
+// The application context has a size limit (about 65 KB); a snapshot over it is refused, and then
+// the watch would never hear of the workout. Kept well under it, with room for the settings.
+export const SNAPSHOT_MAX_BYTES = 48 * 1024
+const bytesOf = v => new TextEncoder().encode(typeof v === 'string' ? v : JSON.stringify(v)).length
+
+/**
+ * The snapshot made small enough to send, dropping first what matters least: the "last time" lines
+ * of the routines the watch could start, then those routines but today's, then today's own "last
+ * time" lines and records, then the "last time" of the running workout, then what is ready
+ * altogether. The running workout's sets are never cut: without them the watch has nothing to do.
+ */
+export function fitSnapshot (snap, max = SNAPSHOT_MAX_BYTES) {
+ if (bytesOf(snap) <= max) return snap
+ const out = JSON.parse(JSON.stringify(snap))
+ const strip = (entries, ...keys) => { for (const e of entries || []) for (const k of keys) delete e[k] }
+ const steps = [
+ () => { for (const r of out.ready?.others || []) strip(r.entries, 'last', 'best') },
+ () => { if (out.ready) out.ready.others = (out.ready.others || []).slice(0, 3) },
+ () => { if (out.ready) out.ready.others = [] },
+ () => { if (out.ready?.today) strip(out.ready.today.entries, 'last', 'best') },
+ () => { if (out.active) strip(out.active.entries, 'last') },
+ () => { out.ready = null },
+ () => { if (out.active) strip(out.active.entries, 'best') },
+ ]
+ for (const step of steps) {
+ step()
+ if (bytesOf(out) <= max) return out
+ }
+ return out
+}
+
export async function startWatchSync ({ useStore, useUI }) {
const p = await watchPlugin()
if (!p) return () => {}
@@ -377,7 +408,7 @@ export async function startWatchSync ({ useStore, useUI }) {
? buildSnapshot(S, { timer: useUI.getState().timer, ready: readyFor(S) })
: { v: SNAPSHOT_VERSION, unit: S.unit === 'lb' ? 'lb' : 'kg', active: null, ready: null }
snap.settings = settingsForWatch(prefs, healthOn)
- const json = JSON.stringify(snap)
+ const json = JSON.stringify(fitSnapshot(snap))
if (json !== lastSent) {
const r = await p.WatchBridge.sendSnapshot({ json })
if (r && r.sent) lastSent = json
@@ -388,6 +419,10 @@ export async function startWatchSync ({ useStore, useUI }) {
if (clips.length && key !== lastClips) {
await p.WatchBridge.sendClips({ wid: S.active.id, clips })
lastClips = key
+ } else if (!S.active && lastClips) {
+ // The workout is over: animations still on their way to the watch are not wanted any more.
+ lastClips = null
+ await p.WatchBridge.dropClips?.()
}
} catch { /* no watch, or not now: the next change tries again */ }
}
@@ -403,11 +438,14 @@ export async function startWatchSync ({ useStore, useUI }) {
const offUI = useUI.subscribe((s, prev) => { if (s.timer !== prev.timer && restOf(s.timer) !== restOf(prev.timer)) schedule() })
const offPrefs = onWatchPrefs(() => schedule())
const sub = await p.WatchBridge.addListener('watchEvent', () => { drainWatchEvents() })
+ // The link itself changed (the session finished activating after launch, a watch was paired, the
+ // app was installed on it): asked again, and the snapshot sent when there is a watch now.
+ const subLink = await Promise.resolve(p.WatchBridge.addListener('watchState', () => { checkLink().then(() => schedule()) })).catch(() => null)
const onVisible = () => { if (document.visibilityState === 'visible') { drainWatchEvents(); checkLink().then(() => schedule()) } }
document.addEventListener('visibilitychange', onVisible)
schedule()
drainWatchEvents()
- return () => { offStore(); offUI(); offPrefs(); offHealth(); sub?.remove?.(); document.removeEventListener('visibilitychange', onVisible); clearTimeout(tm) }
+ return () => { offStore(); offUI(); offPrefs(); offHealth(); sub?.remove?.(); subLink?.remove?.(); document.removeEventListener('visibilitychange', onVisible); clearTimeout(tm) }
}
// Test seams.
diff --git a/frontend/src/lib/watch-sync.settypes.test.js b/frontend/src/lib/watch-sync.settypes.test.js
index 277cb9857..91368f6dd 100644
--- a/frontend/src/lib/watch-sync.settypes.test.js
+++ b/frontend/src/lib/watch-sync.settypes.test.js
@@ -89,3 +89,39 @@ describe('ticks of every kind', () => {
expect(patchSet.mock.calls[2][0].side).toBeUndefined()
})
})
+
+describe('a snapshot too big for the application context', () => {
+ const entry = (i, sets = 4) => ({ id: 'e' + i, name: 'Exercise ' + i, mode: 'reps', restSec: 90, last: 'x'.repeat(300), best: { w: 100, r: 5 },
+ sets: Array.from({ length: sets }, () => ({ w: 60, r: 8, sec: null, done: false, warmup: false })) })
+ const session = n => ({ routineIds: ['r'], name: 'Routine', entries: Array.from({ length: n }, (_, i) => entry(i)) })
+ const big = () => ({ v: 1, unit: 'kg', restSec: 90, settings: { health: true },
+ active: { id: 'w', name: 'Big', unit: 'kg', cur: 0, restSec: 90, entries: Array.from({ length: 12 }, (_, i) => entry(i)) },
+ ready: { today: session(12), others: Array.from({ length: 8 }, () => session(12)) } })
+ const size = v => new TextEncoder().encode(JSON.stringify(v)).length
+
+ it('is left alone when it fits', async () => {
+ const { fitSnapshot } = await import('./watch-sync.js')
+ const small = { v: 1, active: null, ready: null }
+ expect(fitSnapshot(small)).toBe(small)
+ })
+
+ it('loses what matters least first, never the running sets, and fits', async () => {
+ const { fitSnapshot, SNAPSHOT_MAX_BYTES } = await import('./watch-sync.js')
+ const snap = big()
+ expect(size(snap)).toBeGreaterThan(SNAPSHOT_MAX_BYTES)
+ const fit = fitSnapshot(snap)
+ expect(size(fit)).toBeLessThanOrEqual(SNAPSHOT_MAX_BYTES)
+ expect(fit.active.entries).toHaveLength(12)
+ expect(fit.active.entries.every(e => e.sets.length === 4)).toBe(true)
+ expect(fit.settings).toEqual({ health: true })
+ expect(snap.ready.others).toHaveLength(8) // the original is not touched
+ })
+
+ it('keeps today\'s routine when cutting the others is enough', async () => {
+ const { fitSnapshot } = await import('./watch-sync.js')
+ const snap = big()
+ const fit = fitSnapshot(snap, size({ ...snap, ready: { today: snap.ready.today, others: [] } }) + 10)
+ expect(fit.ready.today.entries).toHaveLength(12)
+ expect(fit.active.entries[0].last).toBeTruthy()
+ })
+})