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.

NudgeCheck: the native background check before a nudge

Duarte Santos8dc9e681d634
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml
index b9483449c..a63377cb0 100644
--- a/frontend/android/app/src/main/AndroidManifest.xml
+++ b/frontend/android/app/src/main/AndroidManifest.xml
@@ -78,6 +78,14 @@
android:value="Shows how long is left in the rest between sets." />
</service>
+ <!-- The background check before a nudge or a reminder (NudgeCheckJob): asks the paired
+ server whether the day was trained elsewhere. Run by JobScheduler only; persisted
+ jobs survive a reboot through RECEIVE_BOOT_COMPLETED (declared below). -->
+ <service
+ android:name=".NudgeCheckJob"
+ android:permission="android.permission.BIND_JOB_SERVICE"
+ android:exported="false" />
+
<!-- Gym check-in scanner (@capacitor-mlkit/barcode-scanning): pre-fetch the ML Kit
barcode model at install time so the first scan doesn't wait on a download. -->
<meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="barcode_ui" />
@@ -107,6 +115,9 @@
<!-- Delete my account on a paired phone: the phone's own face, fingerprint or screen lock
confirms it is the owner first (DeviceAuthPlugin). A normal permission, no prompt. -->
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
+ <!-- The background check before a nudge (NudgeCheckJob) is a persisted job: it is still
+ there after a restart. Local notifications declare the same for their own alarms. -->
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Gym check-in: scanning a membership QR/barcode with the camera. -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- Health Connect (#200): write-only, asked for only when the user turns it on in Settings.
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
index dbd348822..49dff985c 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
@@ -28,6 +28,7 @@ public class MainActivity extends BridgeActivity {
registerPlugin(BackupFolderPlugin.class);
registerPlugin(BarIconsPlugin.class);
registerPlugin(DeviceAuthPlugin.class);
+ registerPlugin(NudgeCheckPlugin.class);
super.onCreate(savedInstanceState);
passSystemBarsToPage();
}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheck.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheck.java
new file mode 100644
index 000000000..e2f16b271
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheck.java
@@ -0,0 +1,176 @@
+package ch.duartesantos.opengym;
+
+import android.app.AlarmManager;
+import android.app.PendingIntent;
+import android.app.job.JobInfo;
+import android.app.job.JobScheduler;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Build;
+import android.security.keystore.KeyGenParameterSpec;
+import android.security.keystore.KeyProperties;
+import android.util.Base64;
+import com.capacitorjs.plugins.localnotifications.NotificationStorage;
+import com.capacitorjs.plugins.localnotifications.TimedNotificationPublisher;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyStore;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.GCMParameterSpec;
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+/**
+ * The background check before a missed-day nudge or a workout-day reminder the app scheduled on
+ * the phone (frontend lib/nudge-check.js; NudgeCheckPlugin hands it over, NudgeCheckJob runs it).
+ * What it keeps: the paired server, the headers a request to it carries (the pairing token among
+ * them) and the days something is scheduled for. That goes into the app's private preferences
+ * encrypted with a key of the Android Keystore, so the token is no easier to read than in the
+ * pairing file it comes from.
+ */
+final class NudgeCheck {
+ static final int JOB_ID = 46_201;
+ private static final String PREFS = "opengym_nudge_check";
+ private static final String KEY_ALIAS = "opengym-nudge-check";
+ private static final long MINUTE = 60_000L;
+
+ private NudgeCheck() {}
+
+ // ---------------------------------------------------------------- what is kept
+
+ static boolean save(Context ctx, JSONObject config) {
+ try {
+ Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
+ c.init(Cipher.ENCRYPT_MODE, key());
+ byte[] sealed = c.doFinal(config.toString().getBytes(StandardCharsets.UTF_8));
+ prefs(ctx).edit()
+ .putString("iv", Base64.encodeToString(c.getIV(), Base64.NO_WRAP))
+ .putString("config", Base64.encodeToString(sealed, Base64.NO_WRAP))
+ .apply();
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ static JSONObject load(Context ctx) {
+ try {
+ SharedPreferences p = prefs(ctx);
+ String iv = p.getString("iv", null), sealed = p.getString("config", null);
+ if (iv == null || sealed == null) return null;
+ Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
+ c.init(Cipher.DECRYPT_MODE, key(), new GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)));
+ return new JSONObject(new String(c.doFinal(Base64.decode(sealed, Base64.NO_WRAP)), StandardCharsets.UTF_8));
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ static void clear(Context ctx) {
+ prefs(ctx).edit().clear().apply();
+ JobScheduler js = (JobScheduler) ctx.getSystemService(Context.JOB_SCHEDULER_SERVICE);
+ if (js != null) js.cancel(JOB_ID);
+ }
+
+ private static SharedPreferences prefs(Context ctx) {
+ return ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
+ }
+
+ private static SecretKey key() throws Exception {
+ KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
+ ks.load(null);
+ if (ks.containsAlias(KEY_ALIAS)) return ((KeyStore.SecretKeyEntry) ks.getEntry(KEY_ALIAS, null)).getSecretKey();
+ KeyGenerator gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
+ gen.init(new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .build());
+ return gen.generateKey();
+ }
+
+ // ---------------------------------------------------------------- the days
+
+ /** The days still ahead, soonest first. */
+ static List<JSONObject> upcoming(JSONObject config, long now) {
+ List<JSONObject> out = new ArrayList<>();
+ JSONArray entries = config.optJSONArray("entries");
+ if (entries == null) return out;
+ for (int i = 0; i < entries.length(); i++) {
+ JSONObject e = entries.optJSONObject(i);
+ if (e != null && e.optLong("at") > now) out.add(e);
+ }
+ Collections.sort(out, (a, b) -> Long.compare(a.optLong("at"), b.optLong("at")));
+ return out;
+ }
+
+ /**
+ * Runs the check in the half hour before the next day's first notification, with a network
+ * if there is one; at the end of that window it runs anyway (and, offline, changes nothing).
+ */
+ static void schedule(Context ctx, JSONObject config) {
+ JobScheduler js = (JobScheduler) ctx.getSystemService(Context.JOB_SCHEDULER_SERVICE);
+ if (js == null) return;
+ js.cancel(JOB_ID);
+ List<JSONObject> next = upcoming(config, System.currentTimeMillis());
+ if (next.isEmpty()) return;
+ long now = System.currentTimeMillis();
+ long at = next.get(0).optLong("at");
+ long from = Math.max(0, at - 30 * MINUTE - now);
+ long until = Math.max(from + MINUTE, at - 2 * MINUTE - now);
+ JobInfo job = new JobInfo.Builder(JOB_ID, new ComponentName(ctx, NudgeCheckJob.class))
+ .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
+ .setMinimumLatency(from)
+ .setOverrideDeadline(until)
+ .setPersisted(true)
+ .build();
+ js.schedule(job);
+ }
+
+ /**
+ * The rule lib/nudge-check.js idsToCancel spells out: a day trained or excused takes its
+ * reminder and its nudge, a day the server would not nudge takes the nudge, anything else
+ * (another day's answer included) takes nothing.
+ */
+ static List<Integer> idsToCancel(JSONObject entry, JSONObject answer) {
+ List<Integer> out = new ArrayList<>();
+ if (entry == null || answer == null) return out;
+ String date = entry.optString("date", "");
+ if (date.isEmpty() || !date.equals(answer.optString("date", null))) return out;
+ boolean done = answer.optBoolean("done", false) && answer.opt("done") instanceof Boolean;
+ boolean noNudge = answer.opt("nudge") instanceof Boolean && !answer.optBoolean("nudge", true);
+ if (done) addAll(out, entry.optJSONArray("reminder"));
+ if (done || noNudge) addAll(out, entry.optJSONArray("nudge"));
+ return out;
+ }
+
+ private static void addAll(List<Integer> out, JSONArray ids) {
+ if (ids == null) return;
+ for (int i = 0; i < ids.length(); i++) if (ids.opt(i) instanceof Number) out.add(ids.optInt(i));
+ }
+
+ /**
+ * Takes back notifications @capacitor/local-notifications scheduled: its alarm (the same
+ * PendingIntent it set, LocalNotificationManager.cancelTimerForNotification) and its stored
+ * record, which a reboot would otherwise schedule again.
+ */
+ static void cancelScheduled(Context ctx, List<Integer> ids) {
+ AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
+ NotificationStorage storage = new NotificationStorage(ctx);
+ for (int id : ids) {
+ int flags = PendingIntent.FLAG_NO_CREATE;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) flags |= PendingIntent.FLAG_MUTABLE;
+ PendingIntent pi = PendingIntent.getBroadcast(ctx, id, new Intent(ctx, TimedNotificationPublisher.class), flags);
+ if (pi != null) {
+ if (am != null) am.cancel(pi);
+ pi.cancel();
+ }
+ storage.deleteNotification(String.valueOf(id));
+ }
+ }
+}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheckJob.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheckJob.java
new file mode 100644
index 000000000..27536169b
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheckJob.java
@@ -0,0 +1,100 @@
+package ch.duartesantos.opengym;
+
+import android.app.job.JobParameters;
+import android.app.job.JobService;
+import android.content.Context;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+/**
+ * The background check itself (NudgeCheck): asks GET /api/nudge-check about each day whose
+ * notifications fire within the next twelve hours and takes back what a workout or a day note on
+ * another device made pointless. Offline, an error, an answer it cannot read: nothing changes.
+ * Then it asks for the next run.
+ */
+public class NudgeCheckJob extends JobService {
+ private volatile Thread worker;
+
+ @Override
+ public boolean onStartJob(JobParameters params) {
+ final Context ctx = getApplicationContext();
+ worker = new Thread(() -> {
+ try { check(ctx); } catch (Exception ignored) { /* nothing changes */ }
+ jobFinished(params, false);
+ }, "nudge-check");
+ worker.start();
+ return true;
+ }
+
+ @Override
+ public boolean onStopJob(JobParameters params) {
+ Thread t = worker;
+ if (t != null) t.interrupt();
+ return false; // the next run is asked for below, or by the next resync in the app
+ }
+
+ private static void check(Context ctx) throws Exception {
+ JSONObject config = NudgeCheck.load(ctx);
+ if (config == null) return;
+ String server = config.optString("server", "");
+ JSONObject headers = config.optJSONObject("headers");
+ long now = System.currentTimeMillis();
+ Set<String> settled = new HashSet<>();
+ if (!server.isEmpty()) {
+ for (JSONObject entry : NudgeCheck.upcoming(config, now)) {
+ if (entry.optLong("at") - now > 12 * 3_600_000L) break;
+ String date = entry.optString("date", "");
+ JSONObject answer = ask(server, date, headers);
+ List<Integer> ids = NudgeCheck.idsToCancel(entry, answer);
+ if (!ids.isEmpty()) NudgeCheck.cancelScheduled(ctx, ids);
+ if (answer != null && Boolean.TRUE.equals(answer.opt("done"))) settled.add(date);
+ }
+ }
+ // A day settled is not checked again; the rest is asked about again closer to its time.
+ JSONArray left = new JSONArray();
+ for (JSONObject e : NudgeCheck.upcoming(config, System.currentTimeMillis())) {
+ if (!settled.contains(e.optString("date", ""))) left.put(e);
+ }
+ config.put("entries", left);
+ NudgeCheck.save(ctx, config);
+ NudgeCheck.schedule(ctx, config);
+ }
+
+ /** The server's answer, or null for anything that is not a 200 with JSON. */
+ private static JSONObject ask(String server, String date, JSONObject headers) {
+ HttpURLConnection c = null;
+ try {
+ URL url = new URL(server + "/api/nudge-check?date=" + URLEncoder.encode(date, "UTF-8"));
+ c = (HttpURLConnection) url.openConnection();
+ c.setConnectTimeout(15_000);
+ c.setReadTimeout(15_000);
+ if (headers != null) {
+ for (Iterator<String> it = headers.keys(); it.hasNext(); ) {
+ String k = it.next();
+ c.setRequestProperty(k, headers.optString(k));
+ }
+ }
+ if (c.getResponseCode() != 200) return null;
+ try (InputStream in = c.getInputStream()) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buf = new byte[1024];
+ for (int n; (n = in.read(buf)) > 0 && out.size() < 4096; ) out.write(buf, 0, n);
+ return new JSONObject(out.toString(StandardCharsets.UTF_8.name()));
+ }
+ } catch (Exception e) {
+ return null;
+ } finally {
+ if (c != null) c.disconnect();
+ }
+ }
+}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheckPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheckPlugin.java
new file mode 100644
index 000000000..b1203b9fe
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/NudgeCheckPlugin.java
@@ -0,0 +1,50 @@
+package ch.duartesantos.opengym;
+
+import com.getcapacitor.JSArray;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+import org.json.JSONObject;
+
+/**
+ * Hands the background check its days (frontend lib/nudge-check.js), or takes it back. See
+ * NudgeCheck for what is kept and NudgeCheckJob for the check.
+ *
+ * Usage from JS:
+ * const NudgeCheck = registerPlugin('NudgeCheck');
+ * await NudgeCheck.arm({ server, headers, entries: [{ date, at, reminder: [ids], nudge: [ids] }] });
+ * await NudgeCheck.disarm();
+ */
+@CapacitorPlugin(name = "NudgeCheck")
+public class NudgeCheckPlugin extends Plugin {
+
+ @PluginMethod
+ public void arm(PluginCall call) {
+ String server = call.getString("server");
+ if (server == null || server.isEmpty()) {
+ call.reject("server is required");
+ return;
+ }
+ try {
+ JSObject headers = call.getObject("headers", new JSObject());
+ JSArray entries = call.getArray("entries", new JSArray());
+ JSONObject config = new JSONObject().put("server", server).put("headers", headers).put("entries", entries);
+ if (!NudgeCheck.save(getContext(), config)) {
+ call.reject("could not keep the check");
+ return;
+ }
+ NudgeCheck.schedule(getContext(), config);
+ call.resolve();
+ } catch (Exception e) {
+ call.reject("could not keep the check", e);
+ }
+ }
+
+ @PluginMethod
+ public void disarm(PluginCall call) {
+ NudgeCheck.clear(getContext());
+ call.resolve();
+ }
+}
diff --git a/frontend/ios/App/App.xcodeproj/project.pbxproj b/frontend/ios/App/App.xcodeproj/project.pbxproj
index bc36bd173..1c2cc51d4 100644
--- a/frontend/ios/App/App.xcodeproj/project.pbxproj
+++ b/frontend/ios/App/App.xcodeproj/project.pbxproj
@@ -22,6 +22,7 @@
AA0200000000000000000006 /* RestTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000005 /* RestTone.swift */; };
AA0200000000000000000008 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000007 /* PrivacyInfo.xcprivacy */; };
AA0300000000000000000002 /* DeviceAuthPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0300000000000000000001 /* DeviceAuthPlugin.swift */; };
+ AA0300000000000000000004 /* NudgeCheckPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0300000000000000000003 /* NudgeCheckPlugin.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -44,6 +45,7 @@
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>"; };
AA0300000000000000000001 /* DeviceAuthPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAuthPlugin.swift; sourceTree = "<group>"; };
+ AA0300000000000000000003 /* NudgeCheckPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NudgeCheckPlugin.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -95,6 +97,7 @@
AA0200000000000000000003 /* RestAlertPlugin.swift */,
AA0200000000000000000005 /* RestTone.swift */,
AA0300000000000000000001 /* DeviceAuthPlugin.swift */,
+ AA0300000000000000000003 /* NudgeCheckPlugin.swift */,
AA0200000000000000000007 /* PrivacyInfo.xcprivacy */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
@@ -238,6 +241,7 @@
AA0200000000000000000004 /* RestAlertPlugin.swift in Sources */,
AA0200000000000000000006 /* RestTone.swift in Sources */,
AA0300000000000000000002 /* DeviceAuthPlugin.swift in Sources */,
+ AA0300000000000000000004 /* NudgeCheckPlugin.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/frontend/ios/App/App/AppDelegate.swift b/frontend/ios/App/App/AppDelegate.swift
index a513a30f7..316032174 100644
--- a/frontend/ios/App/App/AppDelegate.swift
+++ b/frontend/ios/App/App/AppDelegate.swift
@@ -5,7 +5,9 @@ import Capacitor
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
- // Override point for customization after application launch.
+ // The background check before a nudge (NudgeCheckPlugin): iOS hands the task only to a
+ // handler registered before launching ends.
+ NudgeCheckPlugin.registerTask()
return true
}
diff --git a/frontend/ios/App/App/Info.plist b/frontend/ios/App/App/Info.plist
index 2189347e9..7d8526c2b 100644
--- a/frontend/ios/App/App/Info.plist
+++ b/frontend/ios/App/App/Info.plist
@@ -78,6 +78,14 @@
<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>
<string>Used to record the sound of a video you take of an exercise you add yourself.</string>
+ <key>BGTaskSchedulerPermittedIdentifiers</key>
+ <array>
+ <string>ch.opengym.app.nudge-check</string>
+ </array>
+ <key>UIBackgroundModes</key>
+ <array>
+ <string>fetch</string>
+ </array>
<key>NSFaceIDUsageDescription</key>
<string>Used to make sure it’s really you before your account is deleted.</string>
</dict>
diff --git a/frontend/ios/App/App/MainViewController.swift b/frontend/ios/App/App/MainViewController.swift
index 0f67eafa7..2c89f200f 100644
--- a/frontend/ios/App/App/MainViewController.swift
+++ b/frontend/ios/App/App/MainViewController.swift
@@ -11,5 +11,6 @@ class MainViewController: CAPBridgeViewController {
bridge?.registerPluginInstance(PrintPlugin())
bridge?.registerPluginInstance(RestAlertPlugin())
bridge?.registerPluginInstance(DeviceAuthPlugin())
+ bridge?.registerPluginInstance(NudgeCheckPlugin())
}
}
diff --git a/frontend/ios/App/App/NudgeCheckPlugin.swift b/frontend/ios/App/App/NudgeCheckPlugin.swift
new file mode 100644
index 000000000..93e429813
--- /dev/null
+++ b/frontend/ios/App/App/NudgeCheckPlugin.swift
@@ -0,0 +1,183 @@
+import Foundation
+import Capacitor
+import BackgroundTasks
+import Security
+import UserNotifications
+
+/**
+ * The background check before a missed-day nudge or a workout-day reminder the app scheduled on
+ * the phone (frontend lib/nudge-check.js). The page hands over the paired server, the headers a
+ * request to it carries and the days something is scheduled for; a BGAppRefreshTask then asks
+ * GET /api/nudge-check about the next of those days and takes back the notifications a workout or
+ * a day note on another device made pointless. Offline, an error, an answer it cannot read:
+ * nothing changes. iOS decides when the task actually runs, so this is a good chance of catching
+ * it, never a promise (docs/MOBILE.md).
+ *
+ * Usage from JS:
+ * const NudgeCheck = registerPlugin('NudgeCheck');
+ * await NudgeCheck.arm({ server, headers, entries: [{ date, at, reminder: [ids], nudge: [ids] }] });
+ * await NudgeCheck.disarm();
+ *
+ * The headers carry the pairing token, so the whole configuration lives in the Keychain (this
+ * device only, readable after the first unlock, which a background task needs), not in a file.
+ */
+@objc(NudgeCheckPlugin)
+public class NudgeCheckPlugin: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "NudgeCheckPlugin"
+ public let jsName = "NudgeCheck"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "arm", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "disarm", returnType: CAPPluginReturnPromise),
+ ]
+
+ /// Also in Info.plist (BGTaskSchedulerPermittedIdentifiers).
+ static let taskId = "ch.opengym.app.nudge-check"
+ private static let account = "nudge-check"
+
+ @objc func arm(_ call: CAPPluginCall) {
+ guard let server = call.getString("server"), !server.isEmpty else {
+ call.reject("server is required")
+ return
+ }
+ let config: [String: Any] = [
+ "server": server,
+ "headers": call.getObject("headers") ?? [:],
+ "entries": call.getArray("entries") ?? [],
+ ]
+ guard NudgeCheckPlugin.save(config) else {
+ call.reject("could not keep the check")
+ return
+ }
+ NudgeCheckPlugin.schedule(config)
+ call.resolve()
+ }
+
+ @objc func disarm(_ call: CAPPluginCall) {
+ NudgeCheckPlugin.clear()
+ BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: NudgeCheckPlugin.taskId)
+ call.resolve()
+ }
+
+ // MARK: the task
+
+ /// From AppDelegate, before launching ends: iOS only hands a task to a handler registered then.
+ static func registerTask() {
+ BGTaskScheduler.shared.register(forTaskWithIdentifier: taskId, using: nil) { task in
+ guard let refresh = task as? BGAppRefreshTask else { task.setTaskCompleted(success: false); return }
+ run(refresh)
+ }
+ }
+
+ /// The days still ahead, soonest first.
+ private static func upcoming(_ config: [String: Any], now: Date = Date()) -> [[String: Any]] {
+ let entries = config["entries"] as? [[String: Any]] ?? []
+ return entries
+ .filter { ($0["at"] as? Double ?? 0) / 1000 > now.timeIntervalSince1970 }
+ .sorted { ($0["at"] as? Double ?? 0) < ($1["at"] as? Double ?? 0) }
+ }
+
+ /// Asks for a run some time before the next day's first notification: an hour ahead, or a
+ /// quarter of an hour from now when that is already past. iOS picks the moment itself.
+ static func schedule(_ config: [String: Any]) {
+ BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: taskId)
+ guard let next = upcoming(config).first, let at = next["at"] as? Double else { return }
+ let fires = Date(timeIntervalSince1970: at / 1000)
+ let request = BGAppRefreshTaskRequest(identifier: taskId)
+ request.earliestBeginDate = max(fires.addingTimeInterval(-3600), Date().addingTimeInterval(15 * 60))
+ try? BGTaskScheduler.shared.submit(request)
+ }
+
+ private static func run(_ task: BGAppRefreshTask) {
+ guard var config = load(), let server = config["server"] as? String else {
+ task.setTaskCompleted(success: true)
+ return
+ }
+ // The days whose notifications fire within the next twelve hours: what a check now can still save.
+ let soon = upcoming(config).filter { (($0["at"] as? Double ?? 0) / 1000) - Date().timeIntervalSince1970 < 12 * 3600 }
+ let headers = config["headers"] as? [String: String] ?? [:]
+ let group = DispatchGroup()
+ var tasks: [URLSessionDataTask] = []
+ var settled: Set<String> = []
+ let lock = NSLock()
+ for entry in soon {
+ guard let date = entry["date"] as? String,
+ var parts = URLComponents(string: server + "/api/nudge-check") else { continue }
+ parts.queryItems = [URLQueryItem(name: "date", value: date)]
+ guard let url = parts.url else { continue }
+ var request = URLRequest(url: url, timeoutInterval: 20)
+ for (k, v) in headers { request.setValue(v, forHTTPHeaderField: k) }
+ group.enter()
+ let t = URLSession.shared.dataTask(with: request) { data, response, _ in
+ defer { group.leave() }
+ guard (response as? HTTPURLResponse)?.statusCode == 200, let data = data,
+ let answer = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
+ let ids = idsToCancel(entry, answer)
+ if !ids.isEmpty {
+ UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ids.map { String($0) })
+ }
+ if answer["done"] as? Bool == true { lock.lock(); settled.insert(date); lock.unlock() }
+ }
+ tasks.append(t)
+ t.resume()
+ }
+ task.expirationHandler = { tasks.forEach { $0.cancel() } }
+ group.notify(queue: .main) {
+ // A day settled is not checked again; the rest is asked about again closer to its time.
+ let left = upcoming(config).filter { !settled.contains($0["date"] as? String ?? "") }
+ config["entries"] = left
+ _ = save(config)
+ if let next = left.first, let at = next["at"] as? Double {
+ let fires = Date(timeIntervalSince1970: at / 1000)
+ BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: taskId)
+ let request = BGAppRefreshTaskRequest(identifier: taskId)
+ // Still well ahead of it: once more, half an hour before. Otherwise the usual hour.
+ let again = fires.timeIntervalSinceNow > 45 * 60 ? fires.addingTimeInterval(-30 * 60) : fires.addingTimeInterval(-3600)
+ request.earliestBeginDate = max(again, Date().addingTimeInterval(15 * 60))
+ try? BGTaskScheduler.shared.submit(request)
+ }
+ task.setTaskCompleted(success: true)
+ }
+ }
+
+ /// The rule lib/nudge-check.js idsToCancel spells out: a day trained or excused takes its
+ /// reminder and its nudge, a day the server would not nudge takes the nudge, anything else
+ /// (another day's answer included) takes nothing.
+ static func idsToCancel(_ entry: [String: Any], _ answer: [String: Any]) -> [Int] {
+ guard let date = entry["date"] as? String, answer["date"] as? String == date else { return [] }
+ let reminder = (entry["reminder"] as? [Any] ?? []).compactMap { ($0 as? NSNumber)?.intValue }
+ let nudge = (entry["nudge"] as? [Any] ?? []).compactMap { ($0 as? NSNumber)?.intValue }
+ if answer["done"] as? Bool == true { return reminder + nudge }
+ if answer["nudge"] as? Bool == false { return nudge }
+ return []
+ }
+
+ // MARK: Keychain
+
+ private static func query() -> [String: Any] {
+ return [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: Bundle.main.bundleIdentifier ?? "ch.opengym.app",
+ kSecAttrAccount as String: account]
+ }
+
+ static func save(_ config: [String: Any]) -> Bool {
+ guard let data = try? JSONSerialization.data(withJSONObject: config) else { return false }
+ SecItemDelete(query() as CFDictionary)
+ var add = query()
+ add[kSecValueData as String] = data
+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ return SecItemAdd(add as CFDictionary, nil) == errSecSuccess
+ }
+
+ static func load() -> [String: Any]? {
+ var q = query()
+ q[kSecReturnData as String] = true
+ q[kSecMatchLimit as String] = kSecMatchLimitOne
+ var out: AnyObject?
+ guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil }
+ return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
+ }
+
+ static func clear() {
+ SecItemDelete(query() as CFDictionary)
+ }
+}