Repository navigation
feat(settings): Apple Health sub-screen with per-type write permissions #765
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BucciMobile
wants to merge
6
commits into
OpenStrap:main
Choose a base branch
from
BucciMobile:feat/health-permissions-cd3903
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,240
−23
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f2db7f5
feat(settings): Apple Health sub-screen with per-type write permissions
mistral-vibe 95d3fe9
fix(ui): stray quote in health_store.dart import broke compilation
mistral-vibe febbeef
test: register HealthStoreScreen as a route + ru/th placeholder metadata
mistral-vibe af83011
fix(review): address PR #765 review findings
mistral-vibe dd50e97
fix(review): distinguish unknown vs undecided, Health URL scheme, Hin…
mistral-vibe 3f16470
fix(l10n): keep {store} in ru/th openSystemSub
mistral-vibe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.