Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ios/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
5A0C00000000000000000003 /* LongSyncDataIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A0C00000000000000000004 /* LongSyncDataIntent.swift */; };
5A0C00000000000000000005 /* LongSyncDataIntentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A0C00000000000000000006 /* LongSyncDataIntentTests.swift */; };
60DE9D949573401269D6DF2E /* HealthRoutes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46A2B400A52A2CA90242C195 /* HealthRoutes.swift */; };
1CA4F649E4E115C8B259B823 /* HealthAuthBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = F04D841A4616CA41FCBCD482 /* HealthAuthBridge.swift */; };
630172CC9317145AD5F8F3B7 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C721EA0C8D31A3834E66203 /* Pods_RunnerTests.framework */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; };
Expand Down Expand Up @@ -117,6 +118,7 @@
331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
46A2B400A52A2CA90242C195 /* HealthRoutes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HealthRoutes.swift; sourceTree = "<group>"; };
F04D841A4616CA41FCBCD482 /* HealthAuthBridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HealthAuthBridge.swift; sourceTree = "<group>"; };
4A03AF838C04AE2BCB84D0B1 /* Signing.defaults.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Signing.defaults.xcconfig; path = Config/Signing.defaults.xcconfig; sourceTree = "<group>"; };
5348973B2FDC19C80033A4D9 /* OpenStrapWidgetExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = OpenStrapWidgetExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
5348973C2FDC19C80033A4D9 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };
Expand Down Expand Up @@ -343,6 +345,7 @@
5A0C00000000000000000002 /* ShortcutSyncBridge.swift */,
5A0C00000000000000000004 /* LongSyncDataIntent.swift */,
46A2B400A52A2CA90242C195 /* HealthRoutes.swift */,
F04D841A4616CA41FCBCD482 /* HealthAuthBridge.swift */,
A8C1E3F507294B6D81A0C2E4 /* HealthKitSleepWriter.swift */,
);
path = Runner;
Expand Down Expand Up @@ -775,6 +778,7 @@
5A0C00000000000000000001 /* ShortcutSyncBridge.swift in Sources */,
5A0C00000000000000000003 /* LongSyncDataIntent.swift in Sources */,
60DE9D949573401269D6DF2E /* HealthRoutes.swift in Sources */,
1CA4F649E4E115C8B259B823 /* HealthAuthBridge.swift in Sources */,
B9D2F406183A5C7E92B1D3F5 /* HealthKitSleepWriter.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down
4 changes: 4 additions & 0 deletions ios/Runner/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ import CoreMotion
if let registrar = registry.registrar(forPlugin: "HealthKitSleepWriter") {
HealthKitSleepWriter.register(messenger: registrar.messenger())
}
// Per-type WRITE authorization status → Dart. See HealthAuthBridge.swift.
if let registrar = registry.registrar(forPlugin: "HealthAuthBridge") {
HealthAuthBridge.register(messenger: registrar.messenger())
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}
if let registrar = registry.registrar(forPlugin: "ShortcutSyncBridge") {
ShortcutSyncBridge.shared.attach(messenger: registrar.messenger())
}
Expand Down
87 changes: 87 additions & 0 deletions ios/Runner/HealthAuthBridge.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import Flutter
import HealthKit

// Per-type WRITE authorization status → Dart. The `health` plugin cannot read
// write auth on iOS (HealthKit hides it from the plugin by design), but
// HKHealthStore.authorizationStatus(for:) DOES answer for the share side —
// only READ denial is withheld, so an app can tell "granted"/"denied"/
// "not yet asked" apart for writes, which is exactly what a settings screen
// needs. Without this, a revoked grant only surfaced as a silently skipped
// export.
//
// `authorizationStatus` is synchronous and never prompts, so this is safe to
// call on app resume and on every settings-screen open.

enum HealthAuthBridge {
private static let channelName = "openstrap/health_auth"
private static let store = HKHealthStore()

static func register(messenger: FlutterBinaryMessenger) {
let channel = FlutterMethodChannel(name: channelName, binaryMessenger: messenger)
channel.setMethodCallHandler { call, result in
switch call.method {
case "writeStatus":
guard HKHealthStore.isHealthDataAvailable() else {
result([]) // iPad and the simulator. Not an error, just no store.
return
}
let args = call.arguments as? [String: Any] ?? [:]
let keys = args["types"] as? [String] ?? []
var out: [[String: Any]] = []
for key in keys {
guard let type = objectType(for: key) else { continue }
out.append([
"type": key,
"status": statusString(store.authorizationStatus(for: type)),
])
}
result(out)
default:
result(FlutterMethodNotImplemented)
}
}
}

/// The HealthKit object type behind one Dart-side key, or nil for a key this
/// build does not ask for. Sleep collapses to the single `sleepAnalysis`
/// category type that all stage types share.
private static func objectType(for key: String) -> HKObjectType? {
switch key {
case "sleep":
return HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
case "resting_hr":
return HKObjectType.quantityType(forIdentifier: .restingHeartRate)
case "hrv":
return HKObjectType.quantityType(forIdentifier: .heartRateVariabilitySDNN)
case "resp_rate":
return HKObjectType.quantityType(forIdentifier: .respiratoryRate)
case "heart_rate":
return HKObjectType.quantityType(forIdentifier: .heartRate)
case "active_energy":
return HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)
case "basal_energy":
return HKObjectType.quantityType(forIdentifier: .basalEnergyBurned)
case "steps":
return HKObjectType.quantityType(forIdentifier: .stepCount)
case "workout":
return HKObjectType.workoutType()
case "weight":
return HKObjectType.quantityType(forIdentifier: .bodyMass)
default:
return nil
}
}

private static func statusString(_ status: HKAuthorizationStatus) -> String {
switch status {
case .sharingAuthorized:
return "authorized"
case .sharingDenied:
return "denied"
case .notDetermined:
return "notDetermined"
@unknown default:
return "unknown"
}
}
}
5 changes: 5 additions & 0 deletions ios/Runner/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -265,5 +265,10 @@
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>x-apple-health</string>
<string>app-settings</string>
</array>
</dict>
</plist>
8 changes: 8 additions & 0 deletions lib/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ class _OpenStrapAppState extends State<OpenStrapApp> with WidgetsBindingObserver
unawaited(app.maybeStopBreathingFromLiveActivity());
app.refreshAppStatus(); // re-check OTA + admin banner on every foreground
app.runCadenceChecks(); // evening wind-down / weekly recap nudges (best-effort)
// Write access to Apple Health / Health Connect can be revoked in OS
// Settings while we are backgrounded, and an ungranted HealthKit write
// silently no-ops — so re-read the per-type status here instead of
// discovering the revocation on a silently skipped export.
if (app.healthSyncEnabled) {
unawaited(app.checkHealth());
unawaited(app.refreshHealthPermissions());
}
// A Siri "start breathing" App Intent may have just foregrounded an
// already-running process (openAppWhenRun doesn't guarantee a fresh
// launch) — the constructor-time check alone would miss that case.
Expand Down
24 changes: 24 additions & 0 deletions lib/health/health_export.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import '../data/db.dart';
import '../data/series_codec.dart';
import 'health_heart_rate_batch.dart';
import 'health_nap_export.dart';
import 'health_permission_status.dart';
import 'health_sleep_session.dart';
import 'health_weight_export.dart';

Expand Down Expand Up @@ -479,6 +480,7 @@ class HealthExporter {
writer: MethodChannelHealthKitSleepSessionWriter(),
);
final HealthConnectHeartRateWriter _androidHeartRate;
final HealthAuthReader _authReader;
bool _configured = false;

/// Upper bound on one plugin `delete()`. HealthKit's delete runs a sample
Expand Down Expand Up @@ -548,11 +550,13 @@ class HealthExporter {

HealthExporter({
HealthConnectHeartRateWriter? androidHeartRate,
HealthAuthReader? authReader,
@visibleForTesting Duration deleteTimeout = const Duration(seconds: 30),
@visibleForTesting bool? isApple,
}) : _isAppleOverride = isApple,
_androidHeartRate =
androidHeartRate ?? MethodChannelHealthConnectHeartRateWriter(),
_authReader = authReader ?? MethodChannelHealthAuthReader(),
_deleteTimeout = deleteTimeout;

/// The process-wide exporter. `AppState` holds this one, and so does every
Expand Down Expand Up @@ -646,6 +650,26 @@ class HealthExporter {
/// Display name of the platform health store.
static String get storeName => isApple ? 'Apple Health' : 'Health Connect';

/// The authorization scope, in request order — what the settings screen
/// lists as permission rows.
List<HealthDataType> get requestedHealthTypes => _types;

/// Per-type WRITE authorization as the store reports it, keyed by
/// [HealthPermType.key]. Apple: read over the native `openstrap/health_auth`
/// channel, because HealthKit answers `authorizationStatus` for the share
/// side (only read denial is withheld) and the plugin cannot see write auth.
/// Android: all `unknown` — Health Connect's hasPermissions(WRITE) is
/// unreliable (see the gate comment above), so the UI sends the user to
/// Health Connect's own permission screen instead of showing a possibly
/// wrong list. Never throws; unreadable stays `unknown`.
Future<Map<String, HealthWriteAuth>> permissionStatuses() async {
final keys = [for (final t in healthPermTypesFor(_types)) t.key];
if (!_apple || keys.isEmpty) {
return {for (final k in keys) k: HealthWriteAuth.unknown};
}
return _authReader.read(keys);
}

/// HealthKit only stores SDNN; Health Connect stores RMSSD — write whichever
/// the platform supports (both are real, from cleaned RR).
HealthDataType get _hrvType => _apple
Expand Down
135 changes: 135 additions & 0 deletions lib/health/health_permission_status.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Per-type WRITE authorization status of the platform health store, and the
// pure mapping from HealthDataType to the display rows the settings screen
// lists. The status itself is read natively on Apple (HealthKit answers
// `authorizationStatus` for the SHARE side — only READ denial is withheld —
// while the `health` plugin cannot see write auth at all); see
// ios/Runner/HealthAuthBridge.swift.
//
// Honesty rule: anything unreadable maps to [HealthWriteAuth.unknown], never
// to a guessed granted/denied.

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:health/health.dart';

/// What the store says about our WRITE access for one data type.
enum HealthWriteAuth { unknown, notDetermined, denied, authorized }

/// Native status string → enum. Accepts both the raw HealthKit names and the
/// normalized names the channel sends; anything else is `unknown`.
HealthWriteAuth healthWriteAuthFromNative(String? raw) => switch (raw) {
'authorized' || 'sharingAuthorized' => HealthWriteAuth.authorized,
'denied' || 'sharingDenied' => HealthWriteAuth.denied,
'notDetermined' => HealthWriteAuth.notDetermined,
_ => HealthWriteAuth.unknown,
};

/// One display row of the permission list. Sleep collapses to a single row:
/// HealthKit has one `sleepAnalysis` object type behind all the stage types.
enum HealthPermType {
sleep('sleep'),
restingHr('resting_hr'),
hrv('hrv'),
respRate('resp_rate'),
heartRate('heart_rate'),
activeEnergy('active_energy'),
basalEnergy('basal_energy'),
steps('steps'),
workout('workout'),
weight('weight');

const HealthPermType(this.key);

/// Stable key sent over the native channel.
final String key;
}

HealthPermType? healthPermTypeOf(HealthDataType t) => switch (t) {
HealthDataType.SLEEP_DEEP ||
HealthDataType.SLEEP_REM ||
HealthDataType.SLEEP_LIGHT ||
HealthDataType.SLEEP_AWAKE ||
HealthDataType.SLEEP_SESSION ||
HealthDataType.SLEEP_IN_BED =>
HealthPermType.sleep,
HealthDataType.RESTING_HEART_RATE => HealthPermType.restingHr,
HealthDataType.HEART_RATE_VARIABILITY_SDNN ||
HealthDataType.HEART_RATE_VARIABILITY_RMSSD =>
HealthPermType.hrv,
HealthDataType.RESPIRATORY_RATE => HealthPermType.respRate,
HealthDataType.HEART_RATE => HealthPermType.heartRate,
HealthDataType.ACTIVE_ENERGY_BURNED => HealthPermType.activeEnergy,
HealthDataType.BASAL_ENERGY_BURNED => HealthPermType.basalEnergy,
HealthDataType.STEPS => HealthPermType.steps,
HealthDataType.WORKOUT => HealthPermType.workout,
HealthDataType.WEIGHT => HealthPermType.weight,
_ => null,
};

/// Unique display rows for [types], in first-seen order.
List<HealthPermType> healthPermTypesFor(Iterable<HealthDataType> types) {
final out = <HealthPermType>[];
for (final t in types) {
final p = healthPermTypeOf(t);
if (p != null && !out.contains(p)) out.add(p);
}
return out;
}

/// Counts over one permission read. Nothing is inferred beyond what the store
/// actually answered.
class HealthPermissionSummary {
HealthPermissionSummary(Map<String, HealthWriteAuth> statuses)
: total = statuses.length,
authorized = _count(statuses, HealthWriteAuth.authorized),
denied = _count(statuses, HealthWriteAuth.denied),
notDetermined = _count(statuses, HealthWriteAuth.notDetermined),
unknown = _count(statuses, HealthWriteAuth.unknown);

static int _count(Map<String, HealthWriteAuth> m, HealthWriteAuth a) =>
m.values.where((v) => v == a).length;

final int total, authorized, denied, notDetermined, unknown;

bool get anyDenied => denied > 0;

/// False for an empty read — "nothing denied" must not pass for "all granted".
bool get allAuthorized => total > 0 && authorized == total;
}

/// Reads per-type write status. Implemented by the native channel bridge;
/// injectable so tests can mock the platform reply.
abstract class HealthAuthReader {
Future<Map<String, HealthWriteAuth>> read(List<String> keys);
}

/// Reads per-type WRITE status over the native `openstrap/health_auth`
/// channel. Never throws: a missing channel, a plugin-less host or a platform
/// error leaves every key at [HealthWriteAuth.unknown].
class MethodChannelHealthAuthReader implements HealthAuthReader {
MethodChannelHealthAuthReader({MethodChannel? channel})
: _channel = channel ?? const MethodChannel('openstrap/health_auth');

final MethodChannel _channel;

@override
Future<Map<String, HealthWriteAuth>> read(List<String> keys) async {
final out = {for (final k in keys) k: HealthWriteAuth.unknown};
if (keys.isEmpty) return out;
try {
final raw = await _channel
.invokeMethod<List<Object?>>('writeStatus', {'types': keys});
if (raw == null) return out;
for (final e in raw) {
if (e is! Map) continue;
final k = e['type'];
if (k is! String || !out.containsKey(k)) continue;
final s = e['status'];
out[k] = healthWriteAuthFromNative(s is String ? s : null);
}
} catch (e) {
debugPrint('[health] writeStatus read: $e');
}
return out;
}
}
30 changes: 29 additions & 1 deletion lib/l10n/app_de.arb
Original file line number Diff line number Diff line change
Expand Up @@ -3982,5 +3982,33 @@
},
"helpLookingForSomething": "Suchst du etwas?",
"helpAllGuides": "Alle Anleitungen",
"helpTopicEmpty": "Für diesen Tab gibt es noch keine Anleitungen."
"helpTopicEmpty": "Für diesen Tab gibt es noch keine Anleitungen.",
"settingsGroupWrite": "Schreiben",
"settingsGroupPermissions": "Berechtigungen",
"settingsGroupManage": "Verwalten",
"settingsHealthSyncPermsOk": "Alle {count} Berechtigungen in {store} erteilt",
"settingsHealthSyncPermsDenied": "{denied} von {total} Berechtigungen in {store} verweigert — antippen zum Anpassen",
"settingsHealthRequestPermsTitle": "Berechtigungen anfragen",
"settingsHealthRequestPermsSub": "Fragt {store} nach den noch nicht entschiedenen Typen — HealthKit zeigt sein Blatt nur dafür; bestehende Auswahl änderst du unter Einstellungen → Health → Datenzugriff & Geräte",
"settingsHealthOpenSystemTitle": "Health-App öffnen",
"settingsHealthOpenSystemSub": "Bestehende Auswahl änderst du in den iOS-Einstellungen unter Health → Datenzugriff & Geräte → diese App",
"settingsHealthFootnote": "{store} meldet den Schreibstatus jedes Datentyps. Der Status wird bei jedem Öffnen der App neu gelesen; Änderungen in den Systemeinstellungen erscheinen dann dort.",
"settingsHealthManageStoreRowTitle": "In {store} verwalten",
"settingsHealthManageStoreRowSub": "Berechtigungen werden pro App in der {store}-App erteilt",
"healthPermAuthorized": "Erlaubt",
"healthPermDenied": "Verweigert",
"healthPermNotDetermined": "Nicht angefragt",
"healthPermUnknown": "Unbekannt",
"healthTypeSleep": "Schlaf",
"healthTypeRestingHr": "Ruhepuls",
"healthTypeHrv": "HRV",
"healthTypeRespRate": "Atemfrequenz",
"healthTypeHeartRate": "Herzfrequenz",
"healthTypeActiveEnergy": "Aktive Energie",
"healthTypeBasalEnergy": "Grundumsatz",
"healthTypeSteps": "Schritte",
"healthTypeWorkout": "Trainings",
"healthTypeWeight": "Gewicht",
"settingsHealthSyncPermsPartial": "{granted} von {total} Berechtigungen in {store} erteilt — einige noch nicht entschieden",
"settingsHealthSyncPermsUnknown": "Berechtigungsstatus konnte nicht aus {store} gelesen werden — {unknown} von {total} Typen unbekannt"
}
Loading