diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index fb08f8518..6af13c217 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -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 */; }; @@ -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 = ""; }; 46A2B400A52A2CA90242C195 /* HealthRoutes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HealthRoutes.swift; sourceTree = ""; }; + F04D841A4616CA41FCBCD482 /* HealthAuthBridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HealthAuthBridge.swift; sourceTree = ""; }; 4A03AF838C04AE2BCB84D0B1 /* Signing.defaults.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Signing.defaults.xcconfig; path = Config/Signing.defaults.xcconfig; sourceTree = ""; }; 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; }; @@ -343,6 +345,7 @@ 5A0C00000000000000000002 /* ShortcutSyncBridge.swift */, 5A0C00000000000000000004 /* LongSyncDataIntent.swift */, 46A2B400A52A2CA90242C195 /* HealthRoutes.swift */, + F04D841A4616CA41FCBCD482 /* HealthAuthBridge.swift */, A8C1E3F507294B6D81A0C2E4 /* HealthKitSleepWriter.swift */, ); path = Runner; @@ -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; diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index 384db0ee9..93674dacf 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -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()) + } if let registrar = registry.registrar(forPlugin: "ShortcutSyncBridge") { ShortcutSyncBridge.shared.attach(messenger: registrar.messenger()) } diff --git a/ios/Runner/HealthAuthBridge.swift b/ios/Runner/HealthAuthBridge.swift new file mode 100644 index 000000000..90295c8b6 --- /dev/null +++ b/ios/Runner/HealthAuthBridge.swift @@ -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" + } + } +} diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index f2e756bf1..50c2f599a 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -265,5 +265,10 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + LSApplicationQueriesSchemes + + x-apple-health + app-settings + diff --git a/lib/app.dart b/lib/app.dart index 6ba33bf6b..1142acc30 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -152,6 +152,14 @@ class _OpenStrapAppState extends State 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. diff --git a/lib/health/health_export.dart b/lib/health/health_export.dart index f0df57144..1b808522e 100644 --- a/lib/health/health_export.dart +++ b/lib/health/health_export.dart @@ -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'; @@ -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 @@ -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 @@ -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 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> 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 diff --git a/lib/health/health_permission_status.dart b/lib/health/health_permission_status.dart new file mode 100644 index 000000000..1586e0680 --- /dev/null +++ b/lib/health/health_permission_status.dart @@ -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 healthPermTypesFor(Iterable types) { + final out = []; + 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 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 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> read(List 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> read(List keys) async { + final out = {for (final k in keys) k: HealthWriteAuth.unknown}; + if (keys.isEmpty) return out; + try { + final raw = await _channel + .invokeMethod>('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; + } +} diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 427565814..ec00d0d5c 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -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" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index a8f137e72..2ce1925f2 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -18065,5 +18065,61 @@ "helpTopicEmpty": "There are no guides for this tab yet.", "@helpTopicEmpty": { "description": "Empty state for a tab with no guides; All guides remains available." - } + }, + "settingsGroupWrite": "Write", + "@settingsGroupWrite": {"description": "Health-store sub-screen group title for the write switch"}, + "settingsGroupPermissions": "Permissions", + "@settingsGroupPermissions": {"description": "Health-store sub-screen group title for the per-type permission list"}, + "settingsGroupManage": "Manage", + "@settingsGroupManage": {"description": "Health-store sub-screen group title for the manage actions"}, + "settingsHealthSyncPermsOk": "All {count} permissions granted in {store}", + "@settingsHealthSyncPermsOk": {"description": "Health-store settings row subtitle when every requested permission is granted", "placeholders": {"count": {"type": "int"}, "store": {"type": "String"}}}, + "settingsHealthSyncPermsDenied": "{denied} of {total} permissions denied in {store} — tap to review", + "@settingsHealthSyncPermsDenied": {"description": "Health-store settings row subtitle when some permissions are denied", "placeholders": {"denied": {"type": "int"}, "total": {"type": "int"}, "store": {"type": "String"}}}, + "settingsHealthRequestPermsTitle": "Request permissions", + "@settingsHealthRequestPermsTitle": {"description": "Row that re-opens the platform grant sheet"}, + "settingsHealthRequestPermsSub": "Asks {store} for the types not yet decided — HealthKit only shows its sheet for those; to change an existing choice use Settings → Health → Data Access & Devices", + "@settingsHealthRequestPermsSub": {"description": "Subtitle of the row that re-opens the platform grant sheet", "placeholders": {"store": {"type": "String"}}}, + "settingsHealthOpenSystemTitle": "Open Health app", + "@settingsHealthOpenSystemTitle": {"description": "Row that opens the OS settings app"}, + "settingsHealthOpenSystemSub": "Existing choices change in iOS Settings under Health → Data Access & Devices → this app", + "@settingsHealthOpenSystemSub": {"description": "Subtitle of the row that opens the OS settings app", "placeholders": {"store": {"type": "String"}}}, + "settingsHealthFootnote": "{store} reports the write status of each data type. The status is re-read every time the app is opened; changes made in the system settings appear there.", + "@settingsHealthFootnote": {"description": "Footnote on the health-store screen explaining the status read and re-check", "placeholders": {"store": {"type": "String"}}}, + "settingsHealthManageStoreRowTitle": "Manage in {store}", + "@settingsHealthManageStoreRowTitle": {"description": "Row that opens the platform store's own permission screen (Android)", "placeholders": {"store": {"type": "String"}}}, + "settingsHealthManageStoreRowSub": "Permissions are granted per app in the {store} app", + "@settingsHealthManageStoreRowSub": {"description": "Subtitle of the row that opens the platform store's own permission screen", "placeholders": {"store": {"type": "String"}}}, + "healthPermAuthorized": "Allowed", + "@healthPermAuthorized": {"description": "Permission chip: write access granted"}, + "healthPermDenied": "Denied", + "@healthPermDenied": {"description": "Permission chip: write access denied"}, + "healthPermNotDetermined": "Not asked", + "@healthPermNotDetermined": {"description": "Permission chip: not asked yet"}, + "healthPermUnknown": "Unknown", + "@healthPermUnknown": {"description": "Permission chip: status could not be read"}, + "healthTypeSleep": "Sleep", + "@healthTypeSleep": {"description": "Permission row label: sleep"}, + "healthTypeRestingHr": "Resting heart rate", + "@healthTypeRestingHr": {"description": "Permission row label: resting heart rate"}, + "healthTypeHrv": "HRV", + "@healthTypeHrv": {"description": "Permission row label: heart rate variability"}, + "healthTypeRespRate": "Respiratory rate", + "@healthTypeRespRate": {"description": "Permission row label: respiratory rate"}, + "healthTypeHeartRate": "Heart rate", + "@healthTypeHeartRate": {"description": "Permission row label: heart rate"}, + "healthTypeActiveEnergy": "Active energy", + "@healthTypeActiveEnergy": {"description": "Permission row label: active energy"}, + "healthTypeBasalEnergy": "Basal energy", + "@healthTypeBasalEnergy": {"description": "Permission row label: basal energy"}, + "healthTypeSteps": "Steps", + "@healthTypeSteps": {"description": "Permission row label: steps"}, + "healthTypeWorkout": "Workouts", + "@healthTypeWorkout": {"description": "Permission row label: workouts"}, + "healthTypeWeight": "Weight", + "@healthTypeWeight": {"description": "Permission row label: weight"}, + "settingsHealthSyncPermsPartial": "{granted} of {total} permissions granted in {store} — some not decided yet", + "@settingsHealthSyncPermsPartial": {"description": "Health-store settings row subtitle when only some permissions are granted and none denied", "placeholders": {"granted": {"type": "int"}, "total": {"type": "int"}, "store": {"type": "String"}}}, + "settingsHealthSyncPermsUnknown": "Permission status could not be read from {store} — {unknown} of {total} types unknown", + "@settingsHealthSyncPermsUnknown": {"description": "Health-store settings row subtitle when the permission status could not be read at all", "placeholders": {"unknown": {"type": "int"}, "total": {"type": "int"}, "store": {"type": "String"}}} } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 9b4b141b9..d61e99260 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3982,5 +3982,33 @@ }, "helpLookingForSomething": "¿Buscas algo?", "helpAllGuides": "Todas las guías", - "helpTopicEmpty": "Todavía no hay guías para esta pestaña." + "helpTopicEmpty": "Todavía no hay guías para esta pestaña.", + "settingsGroupWrite": "Escribir", + "settingsGroupPermissions": "Permisos", + "settingsGroupManage": "Gestionar", + "settingsHealthSyncPermsOk": "Se han concedido los {count} permisos en {store}", + "settingsHealthSyncPermsDenied": "{denied} de {total} permisos denegados en {store}: toca para revisar", + "settingsHealthRequestPermsTitle": "Solicitar permisos", + "settingsHealthRequestPermsSub": "Pide a {store} los tipos aún no decididos: su hoja solo aparece para esos. Para cambiar una elección existente: Ajustes → Salud → Acceso a datos y dispositivos", + "settingsHealthOpenSystemTitle": "Abrir la app Salud", + "settingsHealthOpenSystemSub": "Las elecciones existentes se cambian en Ajustes de iOS → Salud → Acceso a datos y dispositivos → esta app", + "settingsHealthFootnote": "{store} informa del estado de escritura de cada tipo de dato. El estado se relee cada vez que se abre la app; los cambios hechos en los ajustes del sistema aparecen ahí.", + "settingsHealthManageStoreRowTitle": "Gestionar en {store}", + "settingsHealthManageStoreRowSub": "Los permisos se conceden por app en la app {store}", + "healthPermAuthorized": "Permitido", + "healthPermDenied": "Denegado", + "healthPermNotDetermined": "No solicitado", + "healthPermUnknown": "Desconocido", + "healthTypeSleep": "Sueño", + "healthTypeRestingHr": "Frecuencia cardíaca en reposo", + "healthTypeHrv": "HRV", + "healthTypeRespRate": "Frecuencia respiratoria", + "healthTypeHeartRate": "Frecuencia cardíaca", + "healthTypeActiveEnergy": "Energía activa", + "healthTypeBasalEnergy": "Energía basal", + "healthTypeSteps": "Pasos", + "healthTypeWorkout": "Entrenamientos", + "healthTypeWeight": "Peso", + "settingsHealthSyncPermsPartial": "{granted} de {total} permisos concedidos en {store}: algunos aún sin decidir", + "settingsHealthSyncPermsUnknown": "No se pudo leer el estado de los permisos desde {store}: {unknown} de {total} tipos son desconocidos" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 4d2a096d8..15c315090 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3982,5 +3982,33 @@ }, "helpLookingForSomething": "Vous cherchez quelque chose ?", "helpAllGuides": "Tous les guides", - "helpTopicEmpty": "Il n’y a pas encore de guides pour cet onglet." + "helpTopicEmpty": "Il n’y a pas encore de guides pour cet onglet.", + "settingsGroupWrite": "Écriture", + "settingsGroupPermissions": "Autorisations", + "settingsGroupManage": "Gérer", + "settingsHealthSyncPermsOk": "Les {count} autorisations sont accordées dans {store}", + "settingsHealthSyncPermsDenied": "{denied} autorisation(s) sur {total} refusée(s) dans {store} — touchez pour vérifier", + "settingsHealthRequestPermsTitle": "Demander les autorisations", + "settingsHealthRequestPermsSub": "Demande à {store} les types non encore décidés — sa feuille n'apparaît que pour ceux-là ; pour modifier un choix existant : Réglages → Santé → Accès aux données et appareils", + "settingsHealthOpenSystemTitle": "Ouvrir l'app Santé", + "settingsHealthOpenSystemSub": "Les choix existants se modifient dans Réglages iOS → Santé → Accès aux données et appareils → cette app", + "settingsHealthFootnote": "{store} indique l'état d'écriture de chaque type de données. L'état est relu à chaque ouverture de l'app ; les changements faits dans les réglages système y apparaissent.", + "settingsHealthManageStoreRowTitle": "Gérer dans {store}", + "settingsHealthManageStoreRowSub": "Les autorisations se donnent app par app dans l'app {store}", + "healthPermAuthorized": "Autorisé", + "healthPermDenied": "Refusé", + "healthPermNotDetermined": "Non demandé", + "healthPermUnknown": "Inconnu", + "healthTypeSleep": "Sommeil", + "healthTypeRestingHr": "Fréquence cardiaque au repos", + "healthTypeHrv": "HRV", + "healthTypeRespRate": "Fréquence respiratoire", + "healthTypeHeartRate": "Fréquence cardiaque", + "healthTypeActiveEnergy": "Énergie active", + "healthTypeBasalEnergy": "Énergie basale", + "healthTypeSteps": "Pas", + "healthTypeWorkout": "Séances", + "healthTypeWeight": "Poids", + "settingsHealthSyncPermsPartial": "{granted} autorisation(s) sur {total} accordée(s) dans {store} — certaines pas encore décidées", + "settingsHealthSyncPermsUnknown": "Impossible de lire l'état des autorisations depuis {store} — {unknown} type(s) sur {total} sont inconnus" } diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index d72ac832a..0c8794ee6 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -3982,5 +3982,33 @@ }, "helpLookingForSomething": "कुछ ढूँढ रहे हैं?", "helpAllGuides": "सभी गाइड", - "helpTopicEmpty": "इस टैब के लिए अभी कोई गाइड नहीं है।" + "helpTopicEmpty": "इस टैब के लिए अभी कोई गाइड नहीं है।", + "settingsGroupWrite": "लिखें", + "settingsGroupPermissions": "अनुमति", + "settingsGroupManage": "प्रबंधन", + "settingsHealthSyncPermsOk": "{store} में सबही {count} अनुमतियाँ दी गई हैं।", + "settingsHealthSyncPermsDenied": "{store} में {total} में से {denied} अनुमतियाँ अस्वीकृत हैं — समीक्षा के लिए छूएँ।", + "settingsHealthRequestPermsTitle": "अनुमतियाँ अनुरोध करें", + "settingsHealthRequestPermsSub": "{store} के लिए सिर्फ उन अनुमतियाँ का अनुरोध किया जाता है जो अभी तय नहीं हुई; मौजूदा विकल्ल बदललने के लिए: iOS सेटिंग्स → Health → Data Access & Devices → यह ऐप।", + "settingsHealthOpenSystemTitle": "Health ऐप खोलें", + "settingsHealthOpenSystemSub": "मौजूदा विकल्ल बदललने के लिए: iOS सेटिंग्स → Health → Data Access & Devices → यह ऐप।", + "settingsHealthFootnote": "{store} हर डेटा प्रकार की लेखन स्थिति बताता है। App खोलने पर स्थिति दोबारा पढ़ी जाती हैं। सेटिंग्स में किया गया बदलाव तब दिखता हैं।", + "settingsHealthManageStoreRowTitle": "{store} में प्रबंधित करें", + "settingsHealthManageStoreRowSub": "अनुमतियाँ {store} ऐप में प्रति-ऐप दी जाती हैं।", + "healthPermAuthorized": "अनुमति", + "healthPermDenied": "अस्वीकृत", + "healthPermNotDetermined": "नहीं पूछा गया", + "healthPermUnknown": "अज्ञात", + "healthTypeSleep": "नींद", + "healthTypeRestingHr": "आराम की हृदय गति", + "healthTypeHrv": "एचआरवी", + "healthTypeRespRate": "श्वसन दर", + "healthTypeHeartRate": "हृदय गति", + "healthTypeActiveEnergy": "सक्रिय ऊर्जा", + "healthTypeBasalEnergy": "मूल ऊर्जा", + "healthTypeSteps": "कदम", + "healthTypeWorkout": "वर्कआउट", + "healthTypeWeight": "वज़न", + "settingsHealthSyncPermsPartial": "{store} में {total} में से {granted} अनुमतियाँ दी गई हैं; कुछ शेष हैं।", + "settingsHealthSyncPermsUnknown": "{store} से अनुमति की स्थिति नहीं पढ़ी जा सकी — {total} में से {unknown} अज्ञात हैं।" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index d4028beae..a3ce4039d 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -9007,5 +9007,117 @@ }, "helpLookingForSomething": "Что-то ищете?", "helpAllGuides": "Все руководства", - "helpTopicEmpty": "Для этой вкладки пока нет руководств." + "helpTopicEmpty": "Для этой вкладки пока нет руководств.", + "settingsGroupWrite": "Запись", + "settingsGroupPermissions": "Разрешения", + "settingsGroupManage": "Управление", + "settingsHealthSyncPermsOk": "Все {count} разрешений предоставлены в {store}", + "@settingsHealthSyncPermsOk": { + "placeholders": { + "count": { + "type": "int" + }, + "store": { + "type": "String" + } + } + }, + "settingsHealthSyncPermsDenied": "Отклонено {denied} из {total} разрешений в {store} — нажмите, чтобы проверить", + "@settingsHealthSyncPermsDenied": { + "placeholders": { + "denied": { + "type": "int" + }, + "total": { + "type": "int" + }, + "store": { + "type": "String" + } + } + }, + "settingsHealthRequestPermsTitle": "Запросить разрешения", + "settingsHealthRequestPermsSub": "Запрашивает в {store} ещё не решённые типы — лист показывается только для них; изменить существующий выбор: «Настройки» → «Здоровье» → «Доступ к данным и устройствам»", + "@settingsHealthRequestPermsSub": { + "placeholders": { + "store": { + "type": "String" + } + } + }, + "settingsHealthOpenSystemTitle": "Открыть приложение «Здоровье»", + "settingsHealthOpenSystemSub": "Существующие выборы для {store} меняются в Настройки iOS → Здоровье → Доступ к данным и устройствам → это приложение", + "@settingsHealthOpenSystemSub": { + "placeholders": { + "store": { + "type": "String" + } + } + }, + "settingsHealthFootnote": "{store} сообщает статус записи каждого типа данных. Статус перечитывается при каждом открытии приложения; изменения в системных настройках видны там.", + "@settingsHealthFootnote": { + "placeholders": { + "store": { + "type": "String" + } + } + }, + "settingsHealthManageStoreRowTitle": "Управление в {store}", + "@settingsHealthManageStoreRowTitle": { + "placeholders": { + "store": { + "type": "String" + } + } + }, + "settingsHealthManageStoreRowSub": "Разрешения выдаются каждому приложению в приложении {store}", + "@settingsHealthManageStoreRowSub": { + "placeholders": { + "store": { + "type": "String" + } + } + }, + "healthPermAuthorized": "Разрешено", + "healthPermDenied": "Отклонено", + "healthPermNotDetermined": "Не запрошено", + "healthPermUnknown": "Неизвестно", + "healthTypeSleep": "Сон", + "healthTypeRestingHr": "Пульс в покое", + "healthTypeHrv": "ВСР", + "healthTypeRespRate": "Частота дыхания", + "healthTypeHeartRate": "Пульс", + "healthTypeActiveEnergy": "Активная энергия", + "healthTypeBasalEnergy": "Базальный обмен", + "healthTypeSteps": "Шаги", + "healthTypeWorkout": "Тренировки", + "healthTypeWeight": "Вес", + "settingsHealthSyncPermsPartial": "{granted} из {total} разрешений предоставлено в {store} — некоторые ещё не решены", + "@settingsHealthSyncPermsPartial": { + "placeholders": { + "granted": { + "type": "int" + }, + "total": { + "type": "int" + }, + "store": { + "type": "String" + } + } + }, + "settingsHealthSyncPermsUnknown": "Не удалось прочитать статус разрешений из {store} — {unknown} из {total} типов неизвестны", + "@settingsHealthSyncPermsUnknown": { + "placeholders": { + "unknown": { + "type": "int" + }, + "total": { + "type": "int" + }, + "store": { + "type": "String" + } + } + } } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 9a9cedfea..b524b9ce4 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -17215,5 +17215,126 @@ "profileHelpRow": "วิธีใช้", "helpLookingForSomething": "กำลังมองหาอะไรอยู่ไหม?", "helpAllGuides": "คู่มือทั้งหมด", - "helpTopicEmpty": "ยังไม่มีคู่มือสำหรับแท็บนี้" + "helpTopicEmpty": "ยังไม่มีคู่มือสำหรับแท็บนี้", + "settingsGroupWrite": "เขียน", + "settingsGroupPermissions": "สิทธิ์", + "settingsGroupManage": "จัดการ", + "settingsHealthSyncPermsOk": "ได้รับสิทธิ์ทั้งหมด {count} รายการใน {store} แล้ว", + "@settingsHealthSyncPermsOk": { + "description": "Health-store settings row subtitle when every requested permission is granted", + "placeholders": { + "count": { + "type": "int" + }, + "store": { + "type": "String" + } + } + }, + "settingsHealthSyncPermsDenied": "ปฏิเสธ {denied} จาก {total} สิทธิ์ใน {store} — แตะเพื่อตรวจสอบ", + "@settingsHealthSyncPermsDenied": { + "description": "Health-store settings row subtitle when some permissions are denied", + "placeholders": { + "denied": { + "type": "int" + }, + "total": { + "type": "int" + }, + "store": { + "type": "String" + } + } + }, + "settingsHealthRequestPermsTitle": "ขอสิทธิ์", + "settingsHealthRequestPermsSub": "ขอ {store} สำหรับประเภทที่ยังไม่ได้ตัดสินใจ — แผ่นจะเด้งเฉพาะที่ยังไม่ตัดสิน; สำหรับตัวเลือกที่มีอยู่แล้ว: การตั้งค่า → สุขภาพ → การเข้าถึงข้อมูลและอุปกรณ์", + "@settingsHealthRequestPermsSub": { + "description": "Subtitle of the row that re-opens the platform grant sheet", + "placeholders": { + "store": { + "type": "String" + } + } + }, + "settingsHealthOpenSystemTitle": "เปิดแอปสุขภาพ", + "settingsHealthOpenSystemSub": "เปลี่ยนตัวเลือกที่มีอยู่ของ {store} ได้ที่ การตั้งค่า iOS → สุขภาพ → การเข้าถึงข้อมูลและอุปกรณ์ → แอปนี้", + "@settingsHealthOpenSystemSub": { + "description": "Subtitle of the row that opens the OS settings app", + "placeholders": { + "store": { + "type": "String" + } + } + }, + "settingsHealthFootnote": "{store} แจ้งสถานะการเขียนของข้อมูลแต่ละประเภท สถานะจะถูกอ่านใหม่ทุกครั้งที่เปิดแอป การเปลี่ยนแปลงในการตั้งค่าระบบจะปรากฏที่นั่น", + "@settingsHealthFootnote": { + "description": "Footnote on the health-store screen explaining the status read and re-check", + "placeholders": { + "store": { + "type": "String" + } + } + }, + "settingsHealthManageStoreRowTitle": "จัดการใน {store}", + "@settingsHealthManageStoreRowTitle": { + "description": "Row that opens the platform store's own permission screen (Android)", + "placeholders": { + "store": { + "type": "String" + } + } + }, + "settingsHealthManageStoreRowSub": "สิทธิ์จะได้รับเป็นรายแอปในแอป {store}", + "@settingsHealthManageStoreRowSub": { + "description": "Subtitle of the row that opens the platform store's own permission screen", + "placeholders": { + "store": { + "type": "String" + } + } + }, + "healthPermAuthorized": "อนุญาต", + "healthPermDenied": "ปฏิเสธ", + "healthPermNotDetermined": "ยังไม่ได้ถาม", + "healthPermUnknown": "ไม่ทราบ", + "healthTypeSleep": "การนอนหลับ", + "healthTypeRestingHr": "อัตราการเต้นหัวใจขณะพัก", + "healthTypeHrv": "HRV", + "healthTypeRespRate": "อัตราการหายใจ", + "healthTypeHeartRate": "อัตราการเต้นของหัวใจ", + "healthTypeActiveEnergy": "พลังงานที่ใช้ไป", + "healthTypeBasalEnergy": "พลังงานพื้นฐาน", + "healthTypeSteps": "ก้าว", + "healthTypeWorkout": "การออกกำลังกาย", + "healthTypeWeight": "น้ำหนัก", + "settingsHealthSyncPermsPartial": "ได้รับ {granted} จาก {total} สิทธิ์ใน {store} — บางรายการยังไม่ได้ตัดสินใจ", + "@settingsHealthSyncPermsPartial": { + "description": "Health-store settings row subtitle when only some permissions are granted and none denied", + "placeholders": { + "granted": { + "type": "int" + }, + "total": { + "type": "int" + }, + "store": { + "type": "String" + } + } + }, + "settingsHealthSyncPermsUnknown": "อ่านสถานะสิทธิ์จาก {store} ไม่ได้ — {unknown} ใน {total} รายการไม่ทราบ", + "@settingsHealthSyncPermsUnknown": { + "description": "Health-store settings row subtitle when the permission status could not be read at all", + "placeholders": { + "unknown": { + "type": "int" + }, + "total": { + "type": "int" + }, + "store": { + "type": "String" + } + } + } } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index b7261524e..8ce8a8a0a 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3982,5 +3982,33 @@ }, "helpLookingForSomething": "在找什么吗?", "helpAllGuides": "所有指南", - "helpTopicEmpty": "此标签页暂无指南。" + "helpTopicEmpty": "此标签页暂无指南。", + "settingsGroupWrite": "写入", + "settingsGroupPermissions": "权限", + "settingsGroupManage": "管理", + "settingsHealthSyncPermsOk": "{store} 中的全部 {count} 项权限已授予", + "settingsHealthSyncPermsDenied": "{store} 中 {total} 项权限有 {denied} 项被拒 — 点击查看", + "settingsHealthRequestPermsTitle": "请求权限", + "settingsHealthRequestPermsSub": "向 {store} 申请尚未决定的类型 — HealthKit 的申请表只会为这些类型弹出;要更改已有选择,请前往系统设置 → 健康 → 数据访问权限与设备", + "settingsHealthOpenSystemTitle": "打开「健康」App", + "settingsHealthOpenSystemSub": "已有选择请在系统设置 → 健康 → 数据访问权限与设备 → 此 App 中更改", + "settingsHealthFootnote": "{store} 会报告每种数据类型的写入状态。每次打开 App 时都会重新读取该状态;在系统设置中做的更改会显示在那里。", + "settingsHealthManageStoreRowTitle": "在 {store} 中管理", + "settingsHealthManageStoreRowSub": "权限在 {store} 应用中按 App 逐一授予", + "healthPermAuthorized": "已允许", + "healthPermDenied": "已拒绝", + "healthPermNotDetermined": "未询问", + "healthPermUnknown": "未知", + "healthTypeSleep": "睡眠", + "healthTypeRestingHr": "静息心率", + "healthTypeHrv": "HRV", + "healthTypeRespRate": "呼吸频率", + "healthTypeHeartRate": "心率", + "healthTypeActiveEnergy": "活动能量", + "healthTypeBasalEnergy": "基础能量", + "healthTypeSteps": "步数", + "healthTypeWorkout": "锻炼", + "healthTypeWeight": "体重", + "settingsHealthSyncPermsPartial": "{store} 的 {total} 项权限已授予 {granted} 项 — 还有一些未决定", + "settingsHealthSyncPermsUnknown": "无法从 {store} 读取权限状态 — {total} 项中有 {unknown} 项未知" } diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index 09b21ffd6..2d322ce4c 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -118,6 +118,7 @@ import '../notify/notification_prefs.dart'; import '../gestures/gesture_settings.dart'; import '../health/auto_workout_import.dart'; import '../health/health_export.dart'; +import '../health/health_permission_status.dart'; import '../health/phone_pedometer.dart'; import '../import/noop_import.dart'; import '../import/whoop_import.dart'; @@ -828,6 +829,11 @@ class AppState extends ChangeNotifier { HealthExportSingleFlight(); HealthLinkState healthState = HealthLinkState.unknown; bool healthSyncEnabled = false; + /// Per-type WRITE authorization last read from the platform health store, + /// keyed by [HealthPermType.key]. RAM-only on purpose: the store's answer is + /// volatile (the user can flip it in OS Settings at any time), so it is + /// re-read on every foreground resume instead of persisted. + Map healthPermissions = {}; // Shared with `HealthExporter.exportWorkoutId`, which has to honour this // switch from callers that never see this class. static const String _kHealthSync = kHealthSyncPref; @@ -877,9 +883,25 @@ class AppState extends ChangeNotifier { notifyListeners(); } + /// The authorization scope in the order the settings screen lists it. + List get healthPermTypes => + healthPermTypesFor(_healthExport.requestedHealthTypes); + + /// Re-read per-type WRITE authorization WITHOUT prompting (resume-safe). + /// Never throws; an unreadable store leaves every key at `unknown`. + Future refreshHealthPermissions() async { + try { + healthPermissions = await _healthExport.permissionStatuses(); + } catch (e) { + _log('[health] permission status read: $e'); + } + notifyListeners(); + } + /// Prompt for write access (user gesture). On grant + enabled, kick a sync. Future requestHealth() async { healthState = await _healthExport.request(); + unawaited(refreshHealthPermissions()); notifyListeners(); if (healthState == HealthLinkState.ready && healthSyncEnabled) { unawaited(healthSyncNow()); @@ -903,7 +925,11 @@ class AppState extends ChangeNotifier { notifyListeners(); if (on) { await requestHealth(); - if (healthState == HealthLinkState.ready) unawaited(healthSyncNow()); + // A second tap may have switched it off again while the authorization + // request was in flight — recheck before kicking the first sync. + if (healthState == HealthLinkState.ready && healthSyncEnabled) { + unawaited(healthSyncNow()); + } } } diff --git a/lib/ui2/profile/health_store.dart b/lib/ui2/profile/health_store.dart new file mode 100644 index 000000000..ebfab98aa --- /dev/null +++ b/lib/ui2/profile/health_store.dart @@ -0,0 +1,249 @@ +// APPLE HEALTH / HEALTH CONNECT — the sub-screen behind the Data-group row in +// Settings. Top: the on/off switch for writing. Below it, only while on: the +// per-type WRITE authorization the store currently reports, plus the two ways +// to change it. +// +// WHY THIS SCREEN EXISTS: on iOS a write grant can be revoked in OS Settings +// at any moment, and an ungranted HealthKit write silently no-ops — the old +// row only noticed on a failed export. The status is read natively +// (`openstrap/health_auth`, because HealthKit answers authorizationStatus for +// the share side while the `health` plugin cannot see it) on every resume and +// every open of this screen, and anything unreadable shows as "Unknown", never +// as a guessed grant. + +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:provider/provider.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../../health/health_permission_status.dart'; +import '../../l10n/app_localizations.dart'; +import '../../state/app_state.dart'; +import '../ui2.dart'; +import 'profile.dart' show SetRow, settingsGroup; +import 'settings.dart' show healthSyncSub, toggleHealthSync; + +/// The route behind the "Apple Health" / "Health Connect" row in Settings → Data. +class HealthStoreScreen extends StatefulWidget { + const HealthStoreScreen({super.key}); + + @override + State createState() => _HealthStoreScreenState(); +} + +class _HealthStoreScreenState extends State + with WidgetsBindingObserver { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _refresh(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + // Back from the HealthKit grant sheet or OS Settings: re-read the status. + if (state == AppLifecycleState.resumed) _refresh(); + } + + void _refresh() { + final app = context.read(); + if (app.healthSyncEnabled) unawaited(app.refreshHealthPermissions()); + } + + @override + Widget build(BuildContext c) { + final app = c.watch(); + final l = AppLocalizations.of(c); + final p = P.of(c); + final store = app.healthStoreName; + return Scaffold( + backgroundColor: p.bg, + body: SafeArea( + child: Column(children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: S.x4), + child: NavBar(store), + ), + Expanded( + child: ListView( + padding: const EdgeInsets.fromLTRB(S.x4, 0, S.x4, S.x10), + children: [ + settingsGroup(c, l?.settingsGroupWrite ?? 'Write', [ + SetRow(LucideIcons.heartPulse, C.red, + l?.settingsWriteToHealthStoreRowTitle(store) ?? + 'Write to $store', + sub: healthSyncSub( + c, app.healthSyncEnabled, app.healthState, store), + trailing: Switch( + value: app.healthSyncEnabled, + onChanged: (_) => unawaited(toggleHealthSync(app))), + chevron: false, + onTap: () => unawaited(toggleHealthSync(app))), + ]), + if (app.healthSyncEnabled) ...[ + if (app.healthIsApple) + settingsGroup( + c, l?.settingsGroupPermissions ?? 'Permissions', [ + for (final t in app.healthPermTypes) + _permRow(c, l, t, app.healthPermissions[t.key]), + ]) + else + settingsGroup( + c, l?.settingsGroupPermissions ?? 'Permissions', [ + SetRow(LucideIcons.externalLink, C.blue, + l?.settingsHealthManageStoreRowTitle(store) ?? + 'Manage in $store', + sub: l?.settingsHealthManageStoreRowSub(store) ?? + 'Permissions are granted per app in the $store app', + onTap: () => app.openHealthConnect()), + ]), + if (app.healthIsApple) + settingsGroup(c, l?.settingsGroupManage ?? 'Manage', [ + // HealthKit only shows its grant sheet for types that + // are still NOT decided — an answered allow/deny is + // never re-prompted, so this row is a request, not + // "manage"; existing choices change in the system + // settings (path in the sub-line and the row below). + SetRow(LucideIcons.sliders, C.blue, + l?.settingsHealthRequestPermsTitle ?? + 'Request permissions', + sub: l?.settingsHealthRequestPermsSub(store) ?? + 'Asks $store for the types not yet decided — to change an existing choice use Settings → Health → Data Access & Devices', + onTap: () async { + await app.requestHealth(); + if (!c.mounted) return; + await app.refreshHealthPermissions(); + }), + SetRow(LucideIcons.settings, C.blue, + l?.settingsHealthOpenSystemTitle ?? 'Open Health app', + sub: l?.settingsHealthOpenSystemSub(store) ?? + 'Existing choices change in iOS Settings under Health → Data Access & Devices → this app', + onTap: () async { + // x-apple-health:// opens the Health app (declared in + // Info.plist's LSApplicationQueriesSchemes). Launch + // directly and fall back to this app's own Settings + // page only if the launch actually fails — + // canLaunchUrl alone is not reliable for it. + try { + await launchUrl(Uri.parse('x-apple-health://'), + mode: LaunchMode.externalApplication); + } catch (_) { + await launchUrl(Uri.parse('app-settings:'), + mode: LaunchMode.externalApplication); + } + }), + ]), + if (app.healthIsApple) + Padding( + padding: const EdgeInsets.fromLTRB(S.x4, S.x3, S.x4, 0), + child: Text( + l?.settingsHealthFootnote(store) ?? + '$store reports the write status of each data type. ' + 'Changes made in the system settings are picked up the next time the app is opened.', + style: F.over.copyWith(color: p.ink3)), + ), + ], + ], + ), + ), + ]), + ), + ); + } + + /// One data type: icon + localized name + a status chip. The chip is the + /// honest answer — denied is red, "not asked" and unreadable are distinct + /// and never shown as granted. + Widget _permRow( + BuildContext c, AppLocalizations? l, HealthPermType t, HealthWriteAuth? s) { + final a = s ?? HealthWriteAuth.unknown; + final (color, icon, label) = switch (a) { + HealthWriteAuth.authorized => ( + C.green, + LucideIcons.check, + l?.healthPermAuthorized ?? 'Allowed' + ), + HealthWriteAuth.denied => ( + C.red, + LucideIcons.x, + l?.healthPermDenied ?? 'Denied' + ), + HealthWriteAuth.notDetermined => ( + C.orange, + LucideIcons.circle, + l?.healthPermNotDetermined ?? 'Not asked' + ), + HealthWriteAuth.unknown => ( + C.orange, + LucideIcons.circleHelp, + l?.healthPermUnknown ?? 'Unknown' + ), + }; + final p = P.of(c); + return SetRow(_typeIcon(t), _typeColor(t), _typeLabel(l, t), + trailing: Container( + padding: + const EdgeInsets.symmetric(horizontal: S.x2, vertical: S.x1 / 2), + decoration: + BoxDecoration(color: p.wash(color), borderRadius: R.rSm), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Icon(icon, size: 12, color: p.on(color)), + const SizedBox(width: S.x1), + Text(label, + style: F.cap + .copyWith(color: p.on(color), fontWeight: FontWeight.w600)), + ]), + ), + chevron: false); + } + + static IconData _typeIcon(HealthPermType t) => switch (t) { + HealthPermType.sleep => LucideIcons.moonStar, + HealthPermType.restingHr => LucideIcons.heartPulse, + HealthPermType.hrv => LucideIcons.waves, + HealthPermType.respRate => LucideIcons.wind, + HealthPermType.heartRate => LucideIcons.gauge, + HealthPermType.activeEnergy => LucideIcons.flame, + HealthPermType.basalEnergy => LucideIcons.flame, + HealthPermType.steps => LucideIcons.footprints, + HealthPermType.workout => LucideIcons.medal, + HealthPermType.weight => LucideIcons.scale, + }; + + static Color _typeColor(HealthPermType t) => switch (t) { + HealthPermType.sleep => C.indigo, + HealthPermType.restingHr => C.red, + HealthPermType.hrv => C.blue, + HealthPermType.respRate => C.teal, + HealthPermType.heartRate => C.red, + HealthPermType.activeEnergy => C.orange, + HealthPermType.basalEnergy => C.yellow, + HealthPermType.steps => C.teal, + HealthPermType.workout => C.purple, + HealthPermType.weight => C.sky, + }; + + static String _typeLabel(AppLocalizations? l, HealthPermType t) => + switch (t) { + HealthPermType.sleep => l?.healthTypeSleep ?? 'Sleep', + HealthPermType.restingHr => l?.healthTypeRestingHr ?? 'Resting heart rate', + HealthPermType.hrv => l?.healthTypeHrv ?? 'HRV', + HealthPermType.respRate => l?.healthTypeRespRate ?? 'Respiratory rate', + HealthPermType.heartRate => l?.healthTypeHeartRate ?? 'Heart rate', + HealthPermType.activeEnergy => + l?.healthTypeActiveEnergy ?? 'Active energy', + HealthPermType.basalEnergy => l?.healthTypeBasalEnergy ?? 'Basal energy', + HealthPermType.steps => l?.healthTypeSteps ?? 'Steps', + HealthPermType.workout => l?.healthTypeWorkout ?? 'Workouts', + HealthPermType.weight => l?.healthTypeWeight ?? 'Weight', + }; +} diff --git a/lib/ui2/profile/settings.dart b/lib/ui2/profile/settings.dart index 13e3e5b32..199c69e84 100644 --- a/lib/ui2/profile/settings.dart +++ b/lib/ui2/profile/settings.dart @@ -23,8 +23,10 @@ import 'package:url_launcher/url_launcher.dart'; import '../../compute/profile.dart' show plausibleAgeYears, plausibleHeightCm, plausibleWeightKg; import '../../data/off_lookup.dart'; -import '../../health/health_export.dart' show HealthLinkState; +import '../../health/health_export.dart' show HealthExporter, HealthLinkState; import '../../health/health_import_state.dart'; +import '../../health/health_permission_status.dart' + show HealthPermissionSummary, HealthWriteAuth; import '../../health/health_profile_import.dart'; import '../../l10n/app_localizations.dart'; import '../../platform/tasker_bridge.dart'; @@ -43,6 +45,7 @@ import 'band_notifications.dart'; import 'data.dart'; import 'gallery.dart'; import 'gestures.dart'; +import 'health_store.dart'; import 'profile.dart'; import 'report_issue.dart'; import 'wearable_numbers.dart' show WearableDisplay, wearableSettingsGroup; @@ -259,7 +262,7 @@ class _MoreSettingsState extends State onToggleTelemetry: () => app.setTelemetryConsent(!app.telemetryConsent), onToggleBarcodeLookup: () => _toggleBarcode(c), onToggleHealthShare: () => _toggleHealthShare(c, app), - onToggleHealthSync: () => _toggleHealthSync(app), + healthPermissions: app.healthPermissions, onToggleUpdateChecks: () => app.setUpdateChecksEnabled(!app.updateChecksEnabled), onToggleZoneAlert: () => @@ -364,15 +367,16 @@ class _IconChoice extends StatelessWidget { /// Turn the Apple Health / Health Connect EXPORT on or off. /// /// `setHealthSync` already requests the OS permission and kicks a first sync; -/// this row is the only thing that was ever missing. Until it existed the app -/// shipped a write entitlement, a usage string and ten Android WRITE_* -/// permissions for a code path that could not run — see -/// docs/internal/UNREACHABLE.md P1. +/// the settings row used to be the only thing that was ever missing. Until it +/// existed the app shipped a write entitlement, a usage string and ten Android +/// WRITE_* permissions for a code path that could not run — see +/// docs/internal/UNREACHABLE.md P1. The switch itself now lives on the +/// [HealthStoreScreen]; this is the shared toggle behind it. /// /// Health Connect has two failure modes that are not refusals and must not be /// reported as one: it may not be installed, or it may be too old. Both are /// answered with the action that fixes them rather than an error. -Future _toggleHealthSync(AppState app) async { +Future toggleHealthSync(AppState app) async { if (app.healthSyncEnabled) { await app.setHealthSync(false); return; @@ -419,6 +423,42 @@ String healthSyncSub( }; } +/// The Data-group row's sub-line. Off-state as before; when the write is ON, +/// the per-type permission read decides — a grant revoked in OS Settings +/// shows here immediately (re-read on every foreground resume), instead of +/// only surfacing as a silently skipped export. +String healthStoreSub(BuildContext c, bool on, HealthLinkState state, + String store, Map perms) { + final l = AppLocalizations.of(c); + if (!on) { + return l?.settingsHealthSyncOff(store) ?? 'Off. Nothing is written to $store'; + } + final s = HealthPermissionSummary(perms); + if (s.anyDenied) { + return l?.settingsHealthSyncPermsDenied(s.denied, s.total, store) ?? + '${s.denied} of ${s.total} permissions denied in $store — tap to review'; + } + if (s.allAuthorized) { + return l?.settingsHealthSyncPermsOk(s.total, store) ?? + 'All ${s.total} permissions granted in $store'; + } + // Permission counts are only meaningful on Apple, where the status read is + // native. On Android the read is all-unknown by design, so fall through to + // the availability copy (notInstalled / needsUpdate / ready) instead of + // printing misleading counts. + if (HealthExporter.isApple && s.total > 0) { + // Unreadable is NOT "not decided": unknown means the store did not answer. + if (s.unknown > 0) { + return l?.settingsHealthSyncPermsUnknown(s.unknown, s.total, store) ?? + 'Permission status could not be read from $store — ${s.unknown} of ${s.total} types unknown'; + } + // Only notDetermined remains here — "not decided yet" is accurate for it. + return l?.settingsHealthSyncPermsPartial(s.authorized, s.total, store) ?? + '${s.authorized} of ${s.total} permissions granted in $store — some not decided yet'; + } + return healthSyncSub(c, on, state, store); +} + /// Grant or withdraw the whole-database health contribution. /// /// Asymmetric on purpose. Granting is confirmed first — it authorises a daily @@ -612,6 +652,10 @@ class MoreSettingsView extends StatelessWidget { final bool healthSync; final HealthLinkState healthState; final String healthStore; + /// Per-type WRITE authorization from the last read, keyed by + /// [HealthPermType.key] — only summarized on the row, listed on the + /// sub-screen. + final Map healthPermissions; /// The update-check row appears only on a build that can check. final bool showUpdateChecks, updateChecks; @@ -645,7 +689,6 @@ class MoreSettingsView extends StatelessWidget { onToggleBarcodeLookup, onToggleCycleTracking, onToggleHealthShare, - onToggleHealthSync, onToggleUpdateChecks, onToggleZoneAlert, onCycleZoneAlertZone, @@ -667,6 +710,7 @@ class MoreSettingsView extends StatelessWidget { this.healthSync = false, this.healthState = HealthLinkState.unknown, this.healthStore = 'Apple Health', + this.healthPermissions = const {}, this.telemetry = false, this.barcodeLookup = true, this.cycleTracking = false, @@ -697,7 +741,6 @@ class MoreSettingsView extends StatelessWidget { this.onToggleBarcodeLookup, this.onToggleCycleTracking, this.onToggleHealthShare, - this.onToggleHealthSync, this.onToggleUpdateChecks, this.onToggleZoneAlert, this.onCycleZoneAlertZone, @@ -847,12 +890,16 @@ class MoreSettingsView extends StatelessWidget { // was already written and simply had no way to be switched // on, so the write entitlement and usage strings described a // path that could not run. - SetRow(LucideIcons.heartPulse, C.red, - l?.settingsWriteToHealthStoreRowTitle(healthStore) ?? - 'Write to $healthStore', - sub: healthSyncSub(c, healthSync, healthState, healthStore), + // Named after the store itself, and it OPENS the + // sub-screen (on/off switch + per-type permission list) + // rather than toggling in place: a revoked Apple Health + // grant must be visible and fixable, not discovered on the + // next silently skipped write. + SetRow(LucideIcons.heartPulse, C.red, healthStore, + sub: healthStoreSub(c, healthSync, healthState, healthStore, + healthPermissions), value: healthSync ? on : off, - onTap: onToggleHealthSync), + onTap: () => goto(c, const HealthStoreScreen())), SetRow(LucideIcons.footprints, C.teal, l?.settingsStepsRowTitle ?? 'Steps', sub: l?.settingsStepsRowSub ?? diff --git a/test/health_permission_status_test.dart b/test/health_permission_status_test.dart new file mode 100644 index 000000000..b48b1c299 --- /dev/null +++ b/test/health_permission_status_test.dart @@ -0,0 +1,194 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:health/health.dart'; + +import 'package:openstrap_edge/health/health_permission_status.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('healthWriteAuthFromNative', () { + test('maps the HealthKit status names', () { + expect(healthWriteAuthFromNative('authorized'), HealthWriteAuth.authorized); + expect(healthWriteAuthFromNative('sharingAuthorized'), + HealthWriteAuth.authorized); + expect(healthWriteAuthFromNative('denied'), HealthWriteAuth.denied); + expect(healthWriteAuthFromNative('sharingDenied'), HealthWriteAuth.denied); + expect(healthWriteAuthFromNative('notDetermined'), + HealthWriteAuth.notDetermined); + }); + + test('never fabricates: missing or unknown input stays unknown', () { + expect(healthWriteAuthFromNative(null), HealthWriteAuth.unknown); + expect(healthWriteAuthFromNative(''), HealthWriteAuth.unknown); + expect(healthWriteAuthFromNative('granted'), HealthWriteAuth.unknown); + expect(healthWriteAuthFromNative('error'), HealthWriteAuth.unknown); + }); + }); + + group('healthPermTypeOf', () { + test('collapses every sleep type into one row', () { + for (final t in [ + HealthDataType.SLEEP_DEEP, + HealthDataType.SLEEP_REM, + HealthDataType.SLEEP_LIGHT, + HealthDataType.SLEEP_AWAKE, + HealthDataType.SLEEP_SESSION, + HealthDataType.SLEEP_IN_BED, + ]) { + expect(healthPermTypeOf(t), HealthPermType.sleep); + } + }); + + test('maps the whole export scope', () { + expect(healthPermTypeOf(HealthDataType.RESTING_HEART_RATE), + HealthPermType.restingHr); + expect(healthPermTypeOf(HealthDataType.HEART_RATE_VARIABILITY_SDNN), + HealthPermType.hrv); + expect(healthPermTypeOf(HealthDataType.HEART_RATE_VARIABILITY_RMSSD), + HealthPermType.hrv); + expect(healthPermTypeOf(HealthDataType.RESPIRATORY_RATE), + HealthPermType.respRate); + expect(healthPermTypeOf(HealthDataType.HEART_RATE), + HealthPermType.heartRate); + expect(healthPermTypeOf(HealthDataType.ACTIVE_ENERGY_BURNED), + HealthPermType.activeEnergy); + expect(healthPermTypeOf(HealthDataType.BASAL_ENERGY_BURNED), + HealthPermType.basalEnergy); + expect(healthPermTypeOf(HealthDataType.STEPS), HealthPermType.steps); + expect(healthPermTypeOf(HealthDataType.WORKOUT), HealthPermType.workout); + expect(healthPermTypeOf(HealthDataType.WEIGHT), HealthPermType.weight); + }); + + test('types outside the scope map to null', () { + expect(healthPermTypeOf(HealthDataType.BLOOD_GLUCOSE), isNull); + expect(healthPermTypeOf(HealthDataType.BLOOD_OXYGEN), isNull); + }); + }); + + group('healthPermTypesFor', () { + test('unique rows in first-seen order, sleep collapsed', () { + final rows = healthPermTypesFor([ + HealthDataType.SLEEP_DEEP, + HealthDataType.RESTING_HEART_RATE, + HealthDataType.SLEEP_REM, + HealthDataType.STEPS, + HealthDataType.SLEEP_IN_BED, + ]); + expect(rows, [ + HealthPermType.sleep, + HealthPermType.restingHr, + HealthPermType.steps, + ]); + }); + + test('empty scope yields no rows', () { + expect(healthPermTypesFor(const []), isEmpty); + }); + }); + + group('HealthPermissionSummary', () { + test('counts each state and flags denial', () { + final s = HealthPermissionSummary({ + 'a': HealthWriteAuth.authorized, + 'b': HealthWriteAuth.denied, + 'c': HealthWriteAuth.notDetermined, + 'd': HealthWriteAuth.unknown, + }); + expect(s.total, 4); + expect(s.authorized, 1); + expect(s.denied, 1); + expect(s.notDetermined, 1); + expect(s.unknown, 1); + expect(s.anyDenied, isTrue); + expect(s.allAuthorized, isFalse); + }); + + test('an empty read is not "all authorized"', () { + final s = HealthPermissionSummary(const {}); + expect(s.total, 0); + expect(s.allAuthorized, isFalse); + expect(s.anyDenied, isFalse); + }); + + test('all authorized only when every read row is authorized', () { + final s = HealthPermissionSummary({ + 'a': HealthWriteAuth.authorized, + 'b': HealthWriteAuth.authorized, + }); + expect(s.allAuthorized, isTrue); + expect(s.anyDenied, isFalse); + }); + + test('one unknown among grants is not "all authorized"', () { + final s = HealthPermissionSummary({ + 'a': HealthWriteAuth.authorized, + 'b': HealthWriteAuth.unknown, + }); + expect(s.allAuthorized, isFalse); + }); + }); + + group('MethodChannelHealthAuthReader', () { + const channel = MethodChannel('openstrap/health_auth'); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + }); + + test('parses the native reply; keys missing from it stay unknown', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'writeStatus'); + expect(call.arguments, { + 'types': ['sleep', 'steps', 'hrv'] + }); + return [ + {'type': 'sleep', 'status': 'sharingAuthorized'}, + {'type': 'steps', 'status': 'sharingDenied'}, + {'type': 'bogus', 'status': 'denied'}, + ]; + }); + final reader = MethodChannelHealthAuthReader(channel: channel); + final m = await reader.read(['sleep', 'steps', 'hrv']); + expect(m['sleep'], HealthWriteAuth.authorized); + expect(m['steps'], HealthWriteAuth.denied); + expect(m['hrv'], HealthWriteAuth.unknown); + expect(m.containsKey('bogus'), isFalse); + }); + + test('a throwing channel yields all-unknown and never throws', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + throw PlatformException(code: 'unavailable'); + }); + final reader = MethodChannelHealthAuthReader(channel: channel); + final m = await reader.read(['sleep', 'weight']); + expect(m, { + 'sleep': HealthWriteAuth.unknown, + 'weight': HealthWriteAuth.unknown, + }); + }); + + test('a null reply yields all-unknown', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async => null); + final reader = MethodChannelHealthAuthReader(channel: channel); + final m = await reader.read(['sleep']); + expect(m['sleep'], HealthWriteAuth.unknown); + }); + + test('an empty key list never calls the platform', () async { + var called = false; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + called = true; + return []; + }); + final reader = MethodChannelHealthAuthReader(channel: channel); + expect(await reader.read(const []), isEmpty); + expect(called, isFalse); + }); + }); +} diff --git a/test/ui2_tokens_test.dart b/test/ui2_tokens_test.dart index a720c7340..e0be57c82 100644 --- a/test/ui2_tokens_test.dart +++ b/test/ui2_tokens_test.dart @@ -210,6 +210,11 @@ const _notComponents = { 'NotificationSettings', 'NotificationSettingsView', 'EditProfile', 'EditProfileView', 'DataScreen', 'AlarmScreen', 'AlarmScreenView', 'ReportIssueScreen', + // The Apple Health / Health Connect sub-screen: a Scaffold route over + // AppState whose manage rows open the OS health-store grant sheet and the + // system settings on tap — a gallery case would fire a real HealthKit + // prompt from a screenshot sweep. + 'HealthStoreScreen', // Developer-only route: drives a live image transfer to the strap, so a // gallery case would start one. 'FirmwareFlashScreen',