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.

iOS: rest alert, app plugins registered, privacy manifest, simulator CI

Duarte Santos4782a2b41058
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml
new file mode 100644
index 000000000..2c019be92
--- /dev/null
+++ b/.github/workflows/ios.yml
@@ -0,0 +1,121 @@
+# Builds the iPhone app on a Mac and starts it in the simulator: nobody working on openGym has a
+# Mac to hand, so this is where a change to the iOS shell (ios/, a Capacitor plugin, the mobile
+# build) is first compiled. It uses the repo's own 180 px media like every other CI build; the
+# App Store build gets its animations on the release machine (docs/APP_STORES.md).
+name: iOS
+
+on:
+ pull_request:
+ paths:
+ - 'frontend/ios/**'
+ - 'frontend/package.json'
+ - 'frontend/package-lock.json'
+ - 'frontend/capacitor.config.json'
+ - '.github/workflows/ios.yml'
+ push:
+ branches: [main, stores]
+ paths:
+ - 'frontend/**'
+ - '.github/workflows/ios.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ios-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ simulator:
+ runs-on: macos-26
+ timeout-minutes: 60
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 22
+ cache: npm
+ cache-dependency-path: frontend/package-lock.json
+ - run: npm ci
+ working-directory: frontend
+ # The phone build, copied into ios/App/App/public; cap sync runs pod install.
+ - run: npm run build:mobile
+ working-directory: frontend
+ - name: Build for the simulator
+ working-directory: frontend/ios/App
+ run: |
+ set -o pipefail
+ xcodebuild -workspace App.xcworkspace -scheme App -configuration Debug \
+ -sdk iphonesimulator -derivedDataPath build/dd \
+ CODE_SIGNING_ALLOWED=NO build | tee build/xcodebuild.log | grep -E "error:|warning: .*(App/|Swift)|BUILD" || true
+ test -d build/dd/Build/Products/Debug-iphonesimulator/App.app
+ # Starts the app and keeps what it prints: Capacitor logs every bridge call and every
+ # console message of the page in a debug build. A plugin the page calls but the app never
+ # registered shows up as "not implemented on ios".
+ - name: Start it in the simulator
+ working-directory: frontend/ios/App
+ run: |
+ UDID=$(xcrun simctl list devices available -j | node -e '
+ const d = JSON.parse(require("fs").readFileSync(0)).devices
+ const all = Object.entries(d).filter(([k]) => k.includes("iOS")).flatMap(([, v]) => v)
+ const phone = all.filter(x => /^iPhone/.test(x.name)).pop()
+ process.stdout.write(phone.udid)')
+ xcrun simctl boot "$UDID"
+ xcrun simctl bootstatus "$UDID" -b
+ xcrun simctl install "$UDID" build/dd/Build/Products/Debug-iphonesimulator/App.app
+ xcrun simctl launch --console-pty "$UDID" ch.duartesantos.opengym > build/console.log 2>&1 &
+ sleep 45
+ xcrun simctl io "$UDID" screenshot build/first-screen.png || true
+ kill %1 || true
+ cat build/console.log | grep -v "^\s*$" | head -200
+ if grep -q "not implemented on ios" build/console.log; then echo "::error::a plugin the page uses is missing on iOS"; exit 1; fi
+ grep -q "RestAlert" build/console.log || { echo "::error::the page never reached the RestAlert plugin"; exit 1; }
+ - uses: actions/upload-artifact@v6
+ if: always()
+ with:
+ name: ios-simulator
+ path: |
+ frontend/ios/App/build/xcodebuild.log
+ frontend/ios/App/build/console.log
+ frontend/ios/App/build/first-screen.png
+ retention-days: 7
+
+ # The App Store build without its signature, for the release machine to put the full-quality
+ # animations in and sign (scripts/ios/finish-ipa.sh). Built for devices; its media are the
+ # repo's 180 px ones.
+ device-archive:
+ runs-on: macos-26
+ timeout-minutes: 60
+ if: github.event_name != 'pull_request'
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 22
+ cache: npm
+ cache-dependency-path: frontend/package-lock.json
+ - run: npm ci
+ working-directory: frontend
+ - run: npm run build:mobile
+ working-directory: frontend
+ - name: Archive, unsigned
+ working-directory: frontend/ios/App
+ run: |
+ set -o pipefail
+ xcodebuild -workspace App.xcworkspace -scheme App -configuration Release \
+ -destination 'generic/platform=iOS' -archivePath build/App.xcarchive \
+ CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY="" archive \
+ | tee build/archive.log | grep -E "error:|BUILD|ARCHIVE" || true
+ test -d build/App.xcarchive/Products/Applications/App.app
+ cd build/App.xcarchive/Products/Applications
+ # The web assets are put back on the release machine; leave the repo's out of the zip.
+ rm -rf App.app/public/exercise-media
+ mkdir -p ../../../Payload && cp -R App.app ../../../Payload/
+ cd ../../.. && zip -qry App-unsigned.ipa Payload
+ ls -la App-unsigned.ipa
+ - uses: actions/upload-artifact@v6
+ with:
+ name: ios-unsigned-ipa
+ path: frontend/ios/App/build/App-unsigned.ipa
+ retention-days: 14
diff --git a/frontend/ios/App/App.xcodeproj/project.pbxproj b/frontend/ios/App/App.xcodeproj/project.pbxproj
index 64eae48c8..b4a69849a 100644
--- a/frontend/ios/App/App.xcodeproj/project.pbxproj
+++ b/frontend/ios/App/App.xcodeproj/project.pbxproj
@@ -17,7 +17,10 @@
50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */; };
AA0100000000000000000002 /* PrintPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0100000000000000000001 /* PrintPlugin.swift */; };
- AA0100000000000000000004 /* PrintPlugin.m in Sources */ = {isa = PBXBuildFile; fileRef = AA0100000000000000000003 /* PrintPlugin.m */; };
+ AA0200000000000000000002 /* MainViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000001 /* MainViewController.swift */; };
+ AA0200000000000000000004 /* RestAlertPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000003 /* RestAlertPlugin.swift */; };
+ AA0200000000000000000006 /* RestTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000005 /* RestTone.swift */; };
+ AA0200000000000000000008 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000007 /* PrivacyInfo.xcprivacy */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -27,7 +30,6 @@
504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
AA0000000000000000000001 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
AA0100000000000000000001 /* PrintPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrintPlugin.swift; sourceTree = "<group>"; };
- AA0100000000000000000003 /* PrintPlugin.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PrintPlugin.m; sourceTree = "<group>"; };
504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
@@ -36,6 +38,10 @@
AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; };
AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = "<group>"; };
FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = "<group>"; };
+ AA0200000000000000000001 /* MainViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainViewController.swift; sourceTree = "<group>"; };
+ AA0200000000000000000003 /* RestAlertPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RestAlertPlugin.swift; sourceTree = "<group>"; };
+ AA0200000000000000000005 /* RestTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RestTone.swift; sourceTree = "<group>"; };
+ AA0200000000000000000007 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -83,7 +89,10 @@
504EC3071FED79650016851F /* AppDelegate.swift */,
AA0000000000000000000001 /* SceneDelegate.swift */,
AA0100000000000000000001 /* PrintPlugin.swift */,
- AA0100000000000000000003 /* PrintPlugin.m */,
+ AA0200000000000000000001 /* MainViewController.swift */,
+ AA0200000000000000000003 /* RestAlertPlugin.swift */,
+ AA0200000000000000000005 /* RestTone.swift */,
+ AA0200000000000000000007 /* PrivacyInfo.xcprivacy */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
504EC3101FED79650016851F /* LaunchScreen.storyboard */,
@@ -172,6 +181,7 @@
50379B232058CBB4000EE86E /* capacitor.config.json in Resources */,
504EC30D1FED79650016851F /* Main.storyboard in Resources */,
2FAD9763203C412B000D30F8 /* config.xml in Resources */,
+ AA0200000000000000000008 /* PrivacyInfo.xcprivacy in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -221,7 +231,9 @@
504EC3081FED79650016851F /* AppDelegate.swift in Sources */,
AA0000000000000000000002 /* SceneDelegate.swift in Sources */,
AA0100000000000000000002 /* PrintPlugin.swift in Sources */,
- AA0100000000000000000004 /* PrintPlugin.m in Sources */,
+ AA0200000000000000000002 /* MainViewController.swift in Sources */,
+ AA0200000000000000000004 /* RestAlertPlugin.swift in Sources */,
+ AA0200000000000000000006 /* RestTone.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -360,11 +372,11 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 1;
+ CURRENT_PROJECT_VERSION = 26;
INFOPLIST_FILE = App/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
- MARKETING_VERSION = 1.0;
+ MARKETING_VERSION = 1.4.1;
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = ch.duartesantos.opengym;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -380,11 +392,11 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 1;
+ CURRENT_PROJECT_VERSION = 26;
INFOPLIST_FILE = App/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
- MARKETING_VERSION = 1.0;
+ MARKETING_VERSION = 1.4.1;
PRODUCT_BUNDLE_IDENTIFIER = ch.duartesantos.opengym;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
diff --git a/frontend/ios/App/App/Base.lproj/Main.storyboard b/frontend/ios/App/App/Base.lproj/Main.storyboard
index b44df7be8..b09af0185 100644
--- a/frontend/ios/App/App/Base.lproj/Main.storyboard
+++ b/frontend/ios/App/App/Base.lproj/Main.storyboard
@@ -11,7 +11,7 @@
<!--Bridge View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
- <viewController id="BYZ-38-t0r" customClass="CAPBridgeViewController" customModule="Capacitor" sceneMemberID="viewController"/>
+ <viewController id="BYZ-38-t0r" customClass="MainViewController" customModule="App" customModuleProvider="target" sceneMemberID="viewController"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
diff --git a/frontend/ios/App/App/Info.plist b/frontend/ios/App/App/Info.plist
index 59a4aed57..d00e1c54e 100644
--- a/frontend/ios/App/App/Info.plist
+++ b/frontend/ios/App/App/Info.plist
@@ -5,7 +5,7 @@
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
- <string>openGym</string>
+ <string>openGym</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -45,7 +45,7 @@
</dict>
<key>UIRequiredDeviceCapabilities</key>
<array>
- <string>armv7</string>
+ <string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
@@ -62,6 +62,8 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>
+ <key>ITSAppUsesNonExemptEncryption</key>
+ <false/>
<key>NSCameraUsageDescription</key>
<string>Used to scan your gym membership QR code, and to take a photo or video of an exercise you add yourself.</string>
<key>NSMicrophoneUsageDescription</key>
diff --git a/frontend/ios/App/App/MainViewController.swift b/frontend/ios/App/App/MainViewController.swift
new file mode 100644
index 000000000..6969c56e4
--- /dev/null
+++ b/frontend/ios/App/App/MainViewController.swift
@@ -0,0 +1,14 @@
+import Capacitor
+import UIKit
+
+/**
+ * The app's own bridge view controller (Main.storyboard). Since Capacitor 6 the bridge only loads
+ * the plugins that come from npm packages (packageClassList in capacitor.config.json); plugins
+ * that live in the app itself are registered here, or the page finds none of them.
+ */
+class MainViewController: CAPBridgeViewController {
+ override open func capacitorDidLoad() {
+ bridge?.registerPluginInstance(PrintPlugin())
+ bridge?.registerPluginInstance(RestAlertPlugin())
+ }
+}
diff --git a/frontend/ios/App/App/PrintPlugin.m b/frontend/ios/App/App/PrintPlugin.m
deleted file mode 100644
index 0e69ea7c5..000000000
--- a/frontend/ios/App/App/PrintPlugin.m
+++ /dev/null
@@ -1,7 +0,0 @@
-#import <Foundation/Foundation.h>
-#import <Capacitor/Capacitor.h>
-
-// Bridges the Swift PrintPlugin into Capacitor's Objective-C plugin registry.
-CAP_PLUGIN(PrintPlugin, "Print",
- CAP_PLUGIN_METHOD(printHtml, CAPPluginReturnPromise);
-)
diff --git a/frontend/ios/App/App/PrintPlugin.swift b/frontend/ios/App/App/PrintPlugin.swift
index 5acd35330..3edbad8bf 100644
--- a/frontend/ios/App/App/PrintPlugin.swift
+++ b/frontend/ios/App/App/PrintPlugin.swift
@@ -14,7 +14,12 @@ import UIKit
* await Print.printHtml({ html: '<!doctype html>…', name: 'Weekly Training Plan' });
*/
@objc(PrintPlugin)
-public class PrintPlugin: CAPPlugin {
+public class PrintPlugin: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "PrintPlugin"
+ public let jsName = "Print"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "printHtml", returnType: CAPPluginReturnPromise),
+ ]
@objc func printHtml(_ call: CAPPluginCall) {
guard let html = call.getString("html"), !html.isEmpty else {
diff --git a/frontend/ios/App/App/PrivacyInfo.xcprivacy b/frontend/ios/App/App/PrivacyInfo.xcprivacy
new file mode 100644
index 000000000..a4172d1d5
--- /dev/null
+++ b/frontend/ios/App/App/PrivacyInfo.xcprivacy
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!-- openGym's privacy manifest. The app does not track anyone and collects nothing for its
+ developer: the training log stays on the phone, or goes to a server the user connects to
+ themselves. The Coach talks to an AI provider only with the user's own key, after asking.
+ The required-reason APIs are the ones the app's own code and its web view storage use. -->
+<plist version="1.0">
+<dict>
+ <key>NSPrivacyTracking</key>
+ <false/>
+ <key>NSPrivacyTrackingDomains</key>
+ <array/>
+ <key>NSPrivacyCollectedDataTypes</key>
+ <array/>
+ <key>NSPrivacyAccessedAPITypes</key>
+ <array>
+ <dict>
+ <key>NSPrivacyAccessedAPIType</key>
+ <string>NSPrivacyAccessedAPICategoryUserDefaults</string>
+ <key>NSPrivacyAccessedAPITypeReasons</key>
+ <array>
+ <string>CA92.1</string>
+ </array>
+ </dict>
+ <dict>
+ <key>NSPrivacyAccessedAPIType</key>
+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
+ <key>NSPrivacyAccessedAPITypeReasons</key>
+ <array>
+ <string>C617.1</string>
+ </array>
+ </dict>
+ <dict>
+ <key>NSPrivacyAccessedAPIType</key>
+ <string>NSPrivacyAccessedAPICategoryDiskSpace</string>
+ <key>NSPrivacyAccessedAPITypeReasons</key>
+ <array>
+ <string>E174.1</string>
+ </array>
+ </dict>
+ </array>
+</dict>
+</plist>
diff --git a/frontend/ios/App/App/RestAlertPlugin.swift b/frontend/ios/App/App/RestAlertPlugin.swift
new file mode 100644
index 000000000..e6868894c
--- /dev/null
+++ b/frontend/ios/App/App/RestAlertPlugin.swift
@@ -0,0 +1,159 @@
+import AVFoundation
+import AudioToolbox
+import Capacitor
+import Foundation
+import UIKit
+import UserNotifications
+
+/**
+ * The rest-over alert on the iPhone (lib/rest-alert.js, the same calls as RestAlertPlugin.java).
+ *
+ * iOS stops the page's countdown as soon as the app leaves the screen, so the end of a rest is a
+ * local notification scheduled for the moment it ends, with the end tone Settings → Sound picked
+ * (RestTone.swift). With the app in front the page rings the end itself, so the notification is
+ * only pending while the app is in the background: it is taken back when the app comes to the
+ * front and put back for the same moment when the app leaves it. A paused rest has no end, so
+ * hold() calls the notification off; resuming schedules it again.
+ *
+ * tone() plays the end tone with the app in front through the audio session, which turns music
+ * down for it and back up after (a page's Web Audio cannot). buzz() is the phone's one vibration:
+ * iOS has no patterns.
+ */
+@objc(RestAlertPlugin)
+public class RestAlertPlugin: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "RestAlertPlugin"
+ public let jsName = "RestAlert"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "schedule", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "cancel", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "hold", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "tone", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "buzz", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "setAccent", returnType: CAPPluginReturnPromise),
+ ]
+
+ static let requestId = "opengym.rest"
+
+ /** The rest waiting to be rung, kept so it can go back in when the app leaves the screen. */
+ private struct Pending {
+ let at: Date
+ let title: String
+ let sound: Bool
+ let tone: String
+ }
+ private var pending: Pending?
+ private var player: AVAudioPlayer?
+
+ override public func load() {
+ let nc = NotificationCenter.default
+ nc.addObserver(self, selector: #selector(cameToFront), name: UIApplication.didBecomeActiveNotification, object: nil)
+ nc.addObserver(self, selector: #selector(leftFront), name: UIApplication.didEnterBackgroundNotification, object: nil)
+ // Written ahead, off the main thread: the first rest then finds its sound file there.
+ DispatchQueue.global(qos: .utility).async { RestTone.kinds.forEach { _ = RestTone.soundFile($0) } }
+ }
+
+ deinit {
+ NotificationCenter.default.removeObserver(self)
+ }
+
+ @objc func schedule(_ call: CAPPluginCall) {
+ guard let atMs = call.getDouble("at") else {
+ call.reject("at is required")
+ return
+ }
+ let at = Date(timeIntervalSince1970: atMs / 1000)
+ guard at > Date() else {
+ call.reject("at must be in the future")
+ return
+ }
+ pending = Pending(
+ at: at,
+ title: call.getString("title") ?? "Rest’s over. Next set!",
+ sound: call.getBool("sound") ?? true,
+ tone: RestTone.normalised(call.getString("tone") ?? ((call.getBool("classic") ?? false) ? "classic" : "chime"))
+ )
+ DispatchQueue.main.async {
+ if UIApplication.shared.applicationState != .active { self.post() }
+ call.resolve()
+ }
+ }
+
+ @objc func cancel(_ call: CAPPluginCall) {
+ pending = nil
+ withdraw()
+ call.resolve()
+ }
+
+ @objc func hold(_ call: CAPPluginCall) {
+ pending = nil
+ withdraw()
+ call.resolve()
+ }
+
+ @objc func setAccent(_ call: CAPPluginCall) {
+ call.resolve()
+ }
+
+ @objc func buzz(_ call: CAPPluginCall) {
+ AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
+ call.resolve()
+ }
+
+ @objc func tone(_ call: CAPPluginCall) {
+ let kind = RestTone.normalised(call.getString("kind"))
+ DispatchQueue.global(qos: .userInitiated).async {
+ guard let url = RestTone.soundFile(kind) else {
+ call.reject("no sound file")
+ return
+ }
+ DispatchQueue.main.async {
+ do {
+ let session = AVAudioSession.sharedInstance()
+ // Plays over the user's music, which ducks for it, and respects the ring/silent
+ // switch like any other sound the app makes.
+ try session.setCategory(.ambient, mode: .default, options: [.duckOthers])
+ try session.setActive(true)
+ let p = try AVAudioPlayer(contentsOf: url)
+ self.player = p
+ p.play()
+ DispatchQueue.main.asyncAfter(deadline: .now() + p.duration + 0.1) {
+ if self.player === p { self.player = nil }
+ try? session.setActive(false, options: [.notifyOthersOnDeactivation])
+ }
+ call.resolve()
+ } catch {
+ call.reject("could not play the tone")
+ }
+ }
+ }
+ }
+
+ @objc private func cameToFront() {
+ withdraw()
+ }
+
+ @objc private func leftFront() {
+ post()
+ }
+
+ private func post() {
+ guard let p = pending, p.at > Date() else { return }
+ let content = UNMutableNotificationContent()
+ content.title = p.title
+ if p.sound {
+ content.sound = RestTone.soundFile(p.tone) != nil
+ ? UNNotificationSound(named: UNNotificationSoundName(RestTone.soundName(p.tone)))
+ : .default
+ }
+ if #available(iOS 15.0, *) { content.interruptionLevel = .active }
+ let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(1, p.at.timeIntervalSinceNow), repeats: false)
+ let request = UNNotificationRequest(identifier: RestAlertPlugin.requestId, content: content, trigger: trigger)
+ UNUserNotificationCenter.current().add(request)
+ }
+
+ private func withdraw() {
+ let center = UNUserNotificationCenter.current()
+ center.removePendingNotificationRequests(withIdentifiers: [RestAlertPlugin.requestId])
+ center.removeDeliveredNotifications(withIdentifiers: [RestAlertPlugin.requestId])
+ }
+}
diff --git a/frontend/ios/App/App/RestTone.swift b/frontend/ios/App/App/RestTone.swift
new file mode 100644
index 000000000..419844a01
--- /dev/null
+++ b/frontend/ios/App/App/RestTone.swift
@@ -0,0 +1,140 @@
+import Foundation
+
+/**
+ * The end-of-rest sounds as 16-bit mono samples, number for number what Android renders
+ * (android/.../RestTone.java) and the page plays through Web Audio (lib/sound.js chime(),
+ * lib/rest-sounds.js REST_SOUNDS). iOS plays a notification's sound from a file, so the sounds are
+ * written once as WAV files to Library/Sounds, where UNNotificationSound looks for them.
+ */
+enum RestTone {
+ static let rate = 22050
+ /** Silence after the tone, as on Android: Bluetooth earbuds still hold the last note. */
+ static let tailSec = 0.6
+ static let kinds = ["chime", "classic", "bell", "beep", "whistle", "soft"]
+
+ private static let bright: [Double] = [1, 0.6, 0.35, 0.2]
+ private static let bellTimbre: [Double] = [1, 0.25, 0.5, 0.1, 0.3]
+ private static let sine: [Double] = [1]
+
+ // {freq, dur, when} or {freq, dur, when, glideTo}
+ private static let chime: [[Double]] = [[1319, 0.16, 0], [988, 0.16, 0.22], [1319, 0.5, 0.44]]
+ private static let bellNotes: [[Double]] = [[1319, 0.9, 0], [1047, 1.3, 0.4]]
+ private static let beepNotes: [[Double]] = [[1760, 0.08, 0], [1760, 0.08, 0.13], [1760, 0.08, 0.4], [1760, 0.08, 0.53]]
+ private static let whistleNotes: [[Double]] = [[1300, 0.16, 0, 2100], [1500, 0.42, 0.22, 2500]]
+ private static let softNotes: [[Double]] = [[659, 0.4, 0], [784, 0.4, 0.2], [988, 0.8, 0.4]]
+
+ /** A name it does not know plays the chime, as everywhere else. */
+ static func normalised(_ kind: String?) -> String {
+ guard let k = kind, kinds.contains(k) else { return "chime" }
+ return k
+ }
+
+ static func render(_ kind: String) -> [Int16] {
+ switch normalised(kind) {
+ case "classic": return withTail(renderBeeps())
+ case "bell": return withTail(renderNotes(bellNotes, peak: 0.55, hold: 0, harmonics: bellTimbre))
+ case "beep": return withTail(renderNotes(beepNotes, peak: 0.8, hold: 0.8, harmonics: bright))
+ case "whistle": return withTail(renderNotes(whistleNotes, peak: 0.7, hold: 0.55, harmonics: sine))
+ case "soft": return withTail(renderNotes(softNotes, peak: 0.3, hold: 0, harmonics: sine))
+ default: return withTail(renderNotes(chime, peak: 0.9, hold: 0.6, harmonics: bright))
+ }
+ }
+
+ static func renderNotes(_ notes: [[Double]], peak: Double, hold: Double, harmonics: [Double]) -> [Int16] {
+ let end = notes.map { $0[2] + $0[1] }.max() ?? 0
+ var mix = [Double](repeating: 0, count: Int((end * Double(rate)).rounded(.up)))
+ let norm = wavePeak(harmonics)
+ for n in notes {
+ let freq = n[0], dur = n[1], to = n.count > 3 ? n[3] : n[0]
+ let start = Int((n[2] * Double(rate)).rounded())
+ let len = Int(dur * Double(rate))
+ var s = 0
+ while s < len && start + s < mix.count {
+ let t = Double(s) / Double(rate)
+ let cycles = freq * t + (to - freq) * t * t / (2 * dur)
+ var wave = 0.0
+ for (k, h) in harmonics.enumerated() { wave += h * sin(2 * Double.pi * cycles * Double(k + 1)) }
+ mix[start + s] += wave / norm * gain(t, dur, peak, hold)
+ s += 1
+ }
+ }
+ return mix.map { Int16(max(-32767, min(32767, ($0 * 32767).rounded()))) }
+ }
+
+ static func gain(_ t: Double, _ dur: Double, _ peak: Double, _ hold: Double) -> Double {
+ let floor = 0.001, attack = 0.02, holdEnd = max(attack, dur * hold)
+ if t < 0 { return 0 }
+ if t < attack { return floor * pow(peak / floor, t / attack) }
+ if t < holdEnd { return peak }
+ if t < dur { return peak * pow(floor / peak, (t - holdEnd) / (dur - holdEnd)) }
+ return 0
+ }
+
+ private static func wavePeak(_ harmonics: [Double]) -> Double {
+ var top = 0.0
+ for i in 0..<4096 {
+ let x = 2 * Double.pi * Double(i) / 4096
+ var v = 0.0
+ for (k, h) in harmonics.enumerated() { v += h * sin(Double(k + 1) * x) }
+ top = max(top, abs(v))
+ }
+ return top
+ }
+
+ /** The classic beeps (880, 880, 1320), flat at 0.85 of full scale as on Android. */
+ static func renderBeeps() -> [Int16] {
+ let freq: [Double] = [880, 880, 1320], dur = [0.15, 0.15, 0.40], gap = [0.10, 0.10, 0]
+ var out: [Int16] = []
+ let fade = max(1, rate / 200)
+ for i in 0..<freq.count {
+ let n = Int(Double(rate) * dur[i])
+ for s in 0..<n {
+ var env = 1.0
+ if s < fade { env = Double(s) / Double(fade) } else if s > n - fade { env = Double(n - s) / Double(fade) }
+ let wave = sin(2 * Double.pi * freq[i] * Double(s) / Double(rate))
+ out.append(Int16(max(-32767, min(32767, wave * env * 0.85 * 32767))))
+ }
+ out.append(contentsOf: [Int16](repeating: 0, count: Int(Double(rate) * gap[i])))
+ }
+ return out
+ }
+
+ static func withTail(_ tone: [Int16]) -> [Int16] {
+ tone + [Int16](repeating: 0, count: Int(tailSec * Double(rate)))
+ }
+
+ static func wav(_ samples: [Int16]) -> Data {
+ var d = Data()
+ func u32(_ v: UInt32) { var x = v.littleEndian; d.append(Data(bytes: &x, count: 4)) }
+ func u16(_ v: UInt16) { var x = v.littleEndian; d.append(Data(bytes: &x, count: 2)) }
+ let bytes = UInt32(samples.count * 2)
+ d.append("RIFF".data(using: .ascii)!); u32(36 + bytes); d.append("WAVE".data(using: .ascii)!)
+ d.append("fmt ".data(using: .ascii)!); u32(16); u16(1); u16(1); u32(UInt32(rate)); u32(UInt32(rate * 2)); u16(2); u16(16)
+ d.append("data".data(using: .ascii)!); u32(bytes)
+ for s in samples { var x = s.littleEndian; d.append(Data(bytes: &x, count: 2)) }
+ return d
+ }
+
+ /**
+ * "rest-chime-v1.wav" etc., written to Library/Sounds the first time it is asked for. The
+ * version goes up with any change to the sounds above, so a phone never keeps an old file.
+ */
+ static func soundName(_ kind: String) -> String {
+ "rest-\(normalised(kind))-v1.wav"
+ }
+
+ static func soundFile(_ kind: String) -> URL? {
+ let k = normalised(kind)
+ guard let lib = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first else { return nil }
+ let dir = lib.appendingPathComponent("Sounds", isDirectory: true)
+ let url = dir.appendingPathComponent(soundName(k))
+ if FileManager.default.fileExists(atPath: url.path) { return url }
+ do {
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ try wav(render(k)).write(to: url, options: .atomic)
+ return url
+ } catch {
+ return nil
+ }
+ }
+}
diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js
index 347c570c0..5615056c2 100644
--- a/frontend/src/lib/mobile.js
+++ b/frontend/src/lib/mobile.js
@@ -33,6 +33,19 @@ export async function isAndroid() {
}
}
+// 'android' or 'ios' inside the phone app, null anywhere else: for what both native shells do,
+// each its own way (the rest alert: RestAlertPlugin.java and RestAlertPlugin.swift).
+export async function nativePlatform() {
+ if (!MOBILE) return null
+ try {
+ const { Capacitor } = await import('@capacitor/core')
+ const p = Capacitor.getPlatform()
+ return p === 'android' || p === 'ios' ? p : null
+ } catch (e) {
+ return null
+ }
+}
+
const FILE = 'opengym-state.json'
export async function nativeLoad() {
diff --git a/frontend/src/lib/rest-alert.js b/frontend/src/lib/rest-alert.js
index 3bee27d4a..95a9eacf3 100644
--- a/frontend/src/lib/rest-alert.js
+++ b/frontend/src/lib/rest-alert.js
@@ -7,11 +7,15 @@
// a shrinking bar. The lock screen shows it only when notifications are allowed and the
// system is set to show them there.
//
+// iOS stops the page the moment the app leaves the screen. RestAlertPlugin.swift answers the same
+// calls with a local notification for the end of the rest, in the tone Settings → Sound picked;
+// there is no countdown card and no buttons there, so hold() just calls the notification off.
+//
// The web build keeps Web Push (useUI). This file no-ops there; MOBILE is a build-time flag.
import { t } from './i18n-core.js'
import { argb } from './format.js'
import { accentPair } from './accent.js'
-import { MOBILE, isAndroid } from './mobile.js'
+import { MOBILE, nativePlatform } from './mobile.js'
import { REST_SOUNDS } from './rest-sounds.js'
export const REST_ALERT_ID = 42
@@ -81,17 +85,16 @@ const enqueue = fn => {
// The native plugin, registered once: registerPlugin() warns on every call after the first. It
// travels inside an object because a Capacitor plugin proxy answers `then` with a native call that
// never settles, so a promise resolved with the bare proxy hangs for good (the Coach hang, #42).
-// Anything but the Android app gets null and registers nothing: iOS has no RestAlert, and every
-// call to it there, addListener included, rejects.
+// Anything but the phone app gets null and registers nothing.
let pluginP = null
const restPlugin = () => pluginP || (pluginP = (async () => {
- if (!(await isAndroid())) return null
+ if (!(await nativePlatform())) return null
const { registerPlugin } = await import('@capacitor/core')
return { RestAlert: registerPlugin('RestAlert') }
})().catch(() => null))
-// Resolves true only when an Android alarm was scheduled. Callers use false as
-// "fall back to the server push" — web, iOS, and a failed schedule.
+// Resolves true only when the phone scheduled the end itself. Callers use false as
+// "fall back to the server push": the web, and a failed schedule.
export function armRestAlert(at, opts = {}) {
if (!MOBILE) return Promise.resolve(false)
const mine = ++token
@@ -105,7 +108,7 @@ export function armRestAlert(at, opts = {}) {
let kind = 'failed'
try { kind = await deliver(alert) } catch { kind = 'failed' }
if (mine !== token) return false
- return kind === 'android'
+ return kind === 'native'
})
}
@@ -133,8 +136,8 @@ export function holdRestAlert(leftSec, totalSec) {
let onNativeRest = null
export function bindNativeRest(cb) { onNativeRest = cb }
-// Caught, and only on Android: in the iOS app this listener used to reject at startup with
-// nobody to catch it.
+// Caught: in the iOS app before it had the plugin this listener rejected at startup with nobody
+// to catch it. The iPhone's notification has no buttons, so it never fires there.
if (MOBILE) {
restPlugin()
.then(p => p && p.RestAlert.addListener('rest', ev => { if (onNativeRest) onNativeRest(ev) }))
@@ -142,8 +145,9 @@ if (MOBILE) {
}
// A buzz that silent mode lets through (#375): the native side vibrates as an alarm. Resolves true
-// once it did, false anywhere it cannot (the web, iOS, a failed call) for the caller to buzz the
-// ordinary way instead. Never resolves with the plugin itself — see restPlugin.
+// once it did, false anywhere it cannot (the web, a failed call) for the caller to buzz the
+// ordinary way instead. iOS has no patterns: the phone buzzes once. Never resolves with the plugin
+// itself — see restPlugin.
export function buzzAsAlarm(pattern) {
if (!MOBILE) return Promise.resolve(false)
const p = Array.isArray(pattern) ? pattern.filter(n => Number.isFinite(n) && n >= 0).map(Math.round) : (Number.isFinite(pattern) && pattern > 0 ? [Math.round(pattern)] : [])
@@ -154,7 +158,7 @@ export function buzzAsAlarm(pattern) {
}
// The end tone through the native side, which ducks music for it (a page cannot). Resolves true
-// once it was handed over, false anywhere it cannot (the web, iOS, a failed call) for the caller
+// once it was handed over, false anywhere it cannot (the web, a failed call) for the caller
// to play the page's own chime instead. Never resolves with the plugin itself — see restPlugin.
export function toneNative(kind) {
if (!MOBILE) return Promise.resolve(false)
@@ -185,7 +189,7 @@ export function askNotifPermissionOnce() {
if (askP) return askP
askP = (async () => {
try {
- if (!(await isAndroid())) return false
+ if (!(await nativePlatform())) return false
const { LocalNotifications } = await import('@capacitor/local-notifications')
const perm = await LocalNotifications.checkPermissions()
if (perm.display === 'granted') return true
@@ -242,7 +246,7 @@ async function deliver(alert) {
accent: alert.accent,
ink: alert.ink,
})
- return 'android'
+ return 'native'
}
async function cancelDelivered() {
diff --git a/frontend/src/lib/rest-alert.native.test.js b/frontend/src/lib/rest-alert.native.test.js
index 05c585341..d5a758693 100644
--- a/frontend/src/lib/rest-alert.native.test.js
+++ b/frontend/src/lib/rest-alert.native.test.js
@@ -1,5 +1,6 @@
-// The Capacitor side of the rest alert (#296). The iOS app has no RestAlert plugin, and the
-// listener this file adds at startup used to reject there with nothing to catch it. On Android
+// The Capacitor side of the rest alert (#296). Both phone apps have a RestAlert plugin
+// (RestAlertPlugin.java, RestAlertPlugin.swift); anywhere else nothing may be registered, and the
+// listener this file adds at startup must not reject with nothing to catch it. On Android
// the plugin is a Capacitor proxy that answers `then` with a native call that never settles, so
// it must never become the value of a promise (the Coach hang, #42): here that would hang every
// rest alert call.
@@ -14,14 +15,14 @@ const h = vi.hoisted(() => {
})
// Shaped like the proxy registerPlugin() returns: every property is a native method, `then`
-// included, and that one never calls back. Off Android every method rejects, as Capacitor's do
+// included, and that one never calls back. Off the phone every method rejects, as Capacitor's do
// for a plugin the platform does not have.
const pluginProxy = () => new Proxy({}, {
get: (_, prop) => {
if (prop === 'then') return () => new Promise(() => {})
return (...args) => {
h.calls.push(String(prop))
- if (h.platform !== 'android') return Promise.reject(new Error(`"RestAlert.${String(prop)}()" is not implemented on ${h.platform}`))
+ if (h.platform !== 'android' && h.platform !== 'ios') return Promise.reject(new Error(`"RestAlert.${String(prop)}()" is not implemented on ${h.platform}`))
return Promise.resolve(prop === 'addListener' ? { remove: async () => {} } : undefined)
}
},
@@ -59,9 +60,23 @@ afterAll(() => {
})
describe('the rest alert in the iOS app', () => {
- it('registers nothing, rejects nothing and leaves the end to the server push', async () => {
+ it('schedules the end on the phone, like Android, and rejects nothing', async () => {
h.platform = 'ios'
const alert = await import('./rest-alert.js')
+ await expect(alert.armRestAlert(Date.now() + 90_000, { totalSec: 90 })).resolves.toBe(true)
+ alert.holdRestAlert(60, 90)
+ alert.disarmRestAlert()
+ await settle()
+ expect(h.registerPlugin).toHaveBeenCalledTimes(1)
+ expect(h.calls).toEqual(expect.arrayContaining(['schedule', 'hold', 'cancel']))
+ expect(unhandled).toEqual([])
+ })
+})
+
+describe('the rest alert in a browser shell', () => {
+ it('registers nothing, rejects nothing and leaves the end to the server push', async () => {
+ h.platform = 'web'
+ const alert = await import('./rest-alert.js')
await expect(alert.armRestAlert(Date.now() + 90_000, { totalSec: 90 })).resolves.toBe(false)
alert.holdRestAlert(60, 90)
alert.setRestAccent('red')
@@ -166,8 +181,8 @@ describe('the alarm buzz in the Android app', () => {
expect(calls.buzz).toHaveLength(1)
})
- it('answers false in the iOS app without touching any plugin', async () => {
- h.platform = 'ios'
+ it('answers false in a browser shell without touching any plugin', async () => {
+ h.platform = 'web'
const alert = await import('./rest-alert.js')
await expect(alert.buzzAsAlarm([200, 100, 200])).resolves.toBe(false)
expect(h.registerPlugin).not.toHaveBeenCalled()