diff --git a/android/app/build.gradle b/android/app/build.gradle index 1f912e63b..0ffb8cfdd 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -39,7 +39,7 @@ android { defaultConfig { // Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "de.wger.flutter" - minSdkVersion flutter.minSdkVersion + minSdkVersion 26 targetSdk = flutter.targetSdkVersion versionCode = flutter.versionCode versionName = flutter.versionName diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 4e50bad4a..2f8ef5362 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -9,11 +9,19 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/de/wger/flutter/MainActivity.kt b/android/app/src/main/kotlin/de/wger/flutter/MainActivity.kt index 421496c68..3e9f4cd14 100644 --- a/android/app/src/main/kotlin/de/wger/flutter/MainActivity.kt +++ b/android/app/src/main/kotlin/de/wger/flutter/MainActivity.kt @@ -1,6 +1,6 @@ package de.wger.flutter -import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.android.FlutterFragmentActivity -class MainActivity: FlutterActivity() { +class MainActivity: FlutterFragmentActivity() { } diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 9cec73d2b..aa101c62c 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -26,6 +26,8 @@ NSCameraUsageDescription Workout photos + NSHealthShareUsageDescription + wger uses your health data to automatically sync weight measurements from your smart scale UIApplicationSceneManifest UIApplicationSupportsMultipleScenes diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements index 903def2af..57cd45923 100644 --- a/ios/Runner/Runner.entitlements +++ b/ios/Runner/Runner.entitlements @@ -4,5 +4,11 @@ aps-environment development + com.apple.developer.healthkit + + com.apple.developer.healthkit.access + + health-records + diff --git a/lib/helpers/shared_preferences.dart b/lib/helpers/shared_preferences.dart index cdab8a537..9501a53ae 100644 --- a/lib/helpers/shared_preferences.dart +++ b/lib/helpers/shared_preferences.dart @@ -68,4 +68,30 @@ class PreferenceHelper { ); } } + + // Health sync + static const _healthSyncEnabledKey = 'healthSyncEnabled'; + static const _lastHealthSyncTimestampKey = 'lastHealthSyncTimestamp'; + + Future setHealthSyncEnabled(bool value) async { + await PreferenceHelper.asyncPref.setBool(_healthSyncEnabledKey, value); + } + + Future getHealthSyncEnabled() async { + final value = await PreferenceHelper.asyncPref.getBool(_healthSyncEnabledKey); + return value ?? false; + } + + Future setLastHealthSyncTimestamp(String value) async { + await PreferenceHelper.asyncPref.setString(_lastHealthSyncTimestampKey, value); + } + + Future getLastHealthSyncTimestamp() async { + return PreferenceHelper.asyncPref.getString(_lastHealthSyncTimestampKey); + } + + Future clearHealthSyncPreferences() async { + await PreferenceHelper.asyncPref.remove(_healthSyncEnabledKey); + await PreferenceHelper.asyncPref.remove(_lastHealthSyncTimestampKey); + } } diff --git a/lib/models/body_weight/weight_entry.dart b/lib/models/body_weight/weight_entry.dart index 8daada31c..46601af05 100644 --- a/lib/models/body_weight/weight_entry.dart +++ b/lib/models/body_weight/weight_entry.dart @@ -40,7 +40,7 @@ class WeightEntry { } } - WeightEntry copyWith({int? id, int? weight, DateTime? date}) => WeightEntry( + WeightEntry copyWith({int? id, num? weight, DateTime? date}) => WeightEntry( id: id, weight: weight ?? this.weight, date: date ?? this.date, diff --git a/lib/models/body_weight/weight_entry.g.dart b/lib/models/body_weight/weight_entry.g.dart index 286c98661..fbaaa9c68 100644 --- a/lib/models/body_weight/weight_entry.g.dart +++ b/lib/models/body_weight/weight_entry.g.dart @@ -15,8 +15,9 @@ WeightEntry _$WeightEntryFromJson(Map json) { ); } -Map _$WeightEntryToJson(WeightEntry instance) => { - 'id': instance.id, - 'weight': numToString(instance.weight), - 'date': dateToUtcIso8601(instance.date), -}; +Map _$WeightEntryToJson(WeightEntry instance) => + { + 'id': instance.id, + 'weight': numToString(instance.weight), + 'date': dateToUtcIso8601(instance.date), + }; diff --git a/lib/providers/body_weight.dart b/lib/providers/body_weight.dart index cc93f7c35..8af2f4b3c 100644 --- a/lib/providers/body_weight.dart +++ b/lib/providers/body_weight.dart @@ -58,7 +58,12 @@ class BodyWeightProvider with ChangeNotifier { WeightEntry? findByDate(DateTime date) { try { - return _entries.firstWhere((plan) => plan.date == date); + return _entries.firstWhere( + (entry) => + entry.date.year == date.year && + entry.date.month == date.month && + entry.date.day == date.day, + ); } on StateError { return null; } diff --git a/lib/providers/health_sync.dart b/lib/providers/health_sync.dart new file mode 100644 index 000000000..2bcfde48c --- /dev/null +++ b/lib/providers/health_sync.dart @@ -0,0 +1,224 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:io'; + +import 'package:health/health.dart'; +import 'package:logging/logging.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/helpers/shared_preferences.dart'; +import 'package:wger/models/body_weight/weight_entry.dart'; +import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/wger_base_riverpod.dart'; + +part 'health_sync.g.dart'; + +class HealthSyncState { + final bool isEnabled; + final bool isSyncing; + final int lastSyncCount; + + const HealthSyncState({ + this.isEnabled = false, + this.isSyncing = false, + this.lastSyncCount = 0, + }); + + HealthSyncState copyWith({ + bool? isEnabled, + bool? isSyncing, + int? lastSyncCount, + }) { + return HealthSyncState( + isEnabled: isEnabled ?? this.isEnabled, + isSyncing: isSyncing ?? this.isSyncing, + lastSyncCount: lastSyncCount ?? this.lastSyncCount, + ); + } +} + +/// Initial sync lookback period +const int healthSyncInitialDays = 30; + +@Riverpod(keepAlive: true) +class HealthSyncNotifier extends _$HealthSyncNotifier { + final _logger = Logger('HealthSyncNotifier'); + late final Health _health; + late final WgerBaseProvider _baseProvider; + + static const _weightEntryUrl = 'weightentry'; + + @override + HealthSyncState build() { + _health = Health(); + _baseProvider = ref.read(wgerBaseProvider); + + // Load persisted sync preference on startup + _loadPersistedState(); + + return const HealthSyncState(); + } + + Future _loadPersistedState() async { + final enabled = await PreferenceHelper.instance.getHealthSyncEnabled(); + if (enabled) { + state = state.copyWith(isEnabled: true); + } + } + + /// Check if the health platform is available on this device + Future isAvailable() async { + if (Platform.isAndroid) { + await _health.configure(); + final status = await _health.getHealthConnectSdkStatus(); + return status == HealthConnectSdkStatus.sdkAvailable; + } + // iOS always has HealthKit available + return Platform.isIOS; + } + + /// Enable health sync: request permissions, save preference, trigger initial sync + Future enableSync() async { + _logger.info('Enabling health sync'); + + await _health.configure(); + + final authorized = await _health.requestAuthorization( + [HealthDataType.WEIGHT], + permissions: [HealthDataAccess.READ], + ); + + if (!authorized) { + _logger.warning('Health permissions not granted'); + return 0; + } + + await PreferenceHelper.instance.setHealthSyncEnabled(true); + state = state.copyWith(isEnabled: true); + + return syncOnAppOpen(); + } + + /// Disable health sync: clear preferences + Future disableSync() async { + _logger.info('Disabling health sync'); + await PreferenceHelper.instance.clearHealthSyncPreferences(); + state = const HealthSyncState(); + } + + /// Main sync method: read weight data from health platform, post new entries to backend + Future syncOnAppOpen({List? existingEntries}) async { + final prefs = PreferenceHelper.instance; + final enabled = await prefs.getHealthSyncEnabled(); + if (!enabled) { + return 0; + } + + if (state.isSyncing) { + return 0; + } + state = state.copyWith(isEnabled: true, isSyncing: true); + + try { + await _health.configure(); + + // Determine the start time for the query + final lastSyncStr = await prefs.getLastHealthSyncTimestamp(); + final DateTime startTime; + if (lastSyncStr != null) { + startTime = DateTime.parse(lastSyncStr); + } else { + startTime = DateTime.now().subtract(const Duration(days: healthSyncInitialDays)); + } + final endTime = DateTime.now(); + + _logger.info('Syncing weight data from $startTime to $endTime'); + + // Read weight data from health platform + List dataPoints = await _health.getHealthDataFromTypes( + types: [HealthDataType.WEIGHT], + startTime: startTime, + endTime: endTime, + ); + dataPoints = _health.removeDuplicates(dataPoints); + + if (dataPoints.isEmpty) { + _logger.info('No new weight data from health platform'); + state = state.copyWith(isSyncing: false, lastSyncCount: 0); + return 0; + } + + _logger.info('Found ${dataPoints.length} weight data points'); + + int syncedCount = 0; + DateTime? latestSynced; + + for (final point in dataPoints) { + try { + final value = (point.value as NumericHealthValue).numericValue; + final weightKg = (value * 100).roundToDouble() / 100; // Round to 2 decimal places + final timestamp = point.dateFrom; + + // Fallback dedup: skip if an entry with the same timestamp exists locally + if (existingEntries != null) { + final duplicate = existingEntries.any( + (e) => + e.date.year == timestamp.year && + e.date.month == timestamp.month && + e.date.day == timestamp.day && + e.date.hour == timestamp.hour && + e.date.minute == timestamp.minute, + ); + if (duplicate) { + _logger.fine('Skipping duplicate entry for $timestamp'); + continue; + } + } + + // POST to backend with original timestamp + final entry = WeightEntry(weight: weightKg, date: timestamp); + await _baseProvider.post( + entry.toJson(), + _baseProvider.makeUrl(_weightEntryUrl), + ); + + syncedCount++; + if (latestSynced == null || timestamp.isAfter(latestSynced)) { + latestSynced = timestamp; + } + } catch (e) { + _logger.warning('Failed to sync weight entry: $e'); + // Best-effort: continue with next entry + } + } + + // Update last sync timestamp to the latest successfully synced reading + if (latestSynced != null) { + await prefs.setLastHealthSyncTimestamp(latestSynced.toIso8601String()); + } + + _logger.info('Synced $syncedCount weight entries'); + state = state.copyWith(isSyncing: false, lastSyncCount: syncedCount); + return syncedCount; + } catch (e) { + _logger.warning('Health sync failed: $e'); + state = state.copyWith(isSyncing: false, lastSyncCount: 0); + return 0; + } + } +} diff --git a/lib/providers/health_sync.g.dart b/lib/providers/health_sync.g.dart new file mode 100644 index 000000000..a10c6cec2 --- /dev/null +++ b/lib/providers/health_sync.g.dart @@ -0,0 +1,63 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'health_sync.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(HealthSyncNotifier) +final healthSyncProvider = HealthSyncNotifierProvider._(); + +final class HealthSyncNotifierProvider + extends $NotifierProvider { + HealthSyncNotifierProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'healthSyncProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$healthSyncNotifierHash(); + + @$internal + @override + HealthSyncNotifier create() => HealthSyncNotifier(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(HealthSyncState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$healthSyncNotifierHash() => + r'7a0929b0b1660729da0f0fc3a9a1a70af71cf894'; + +abstract class _$HealthSyncNotifier extends $Notifier { + HealthSyncState build(); + @$mustCallSuper + @override + void runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + HealthSyncState, + Object?, + Object? + >; + element.handleCreate(ref, build); + } +} diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index 10de168f7..8371cd98c 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -28,6 +28,7 @@ import 'package:wger/providers/auth.dart'; import 'package:wger/providers/body_weight.dart'; import 'package:wger/providers/exercises.dart'; import 'package:wger/providers/gallery.dart'; +import 'package:wger/providers/health_sync.dart'; import 'package:wger/providers/measurement.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/routines.dart'; @@ -147,6 +148,15 @@ class _HomeTabsScreenState extends ConsumerState } authProvider.dataInit = true; + + // Trigger health sync after weight entries are loaded (non-blocking) + final weightProviderForSync = context.read(); + final healthNotifier = ref.read(healthSyncProvider.notifier); + healthNotifier.syncOnAppOpen(existingEntries: weightProviderForSync.items).then((syncCount) { + if (syncCount > 0) { + weightProviderForSync.fetchAndSetEntries(); + } + }); } @override diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index 014b281d9..3469acd73 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -21,6 +21,7 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/screens/settings_plates_screen.dart'; import './settings/exercise_cache.dart'; +import './settings/health_sync.dart'; import './settings/ingredient_cache.dart'; import './settings/theme.dart'; @@ -42,6 +43,8 @@ class SettingsPage extends StatelessWidget { ), const SettingsExerciseCache(), const SettingsIngredientCache(), + ListTile(title: Text('Health', style: Theme.of(context).textTheme.headlineSmall)), + const HealthSyncSettingsTile(), ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)), const SettingsTheme(), ListTile( diff --git a/lib/widgets/core/settings/health_sync.dart b/lib/widgets/core/settings/health_sync.dart new file mode 100644 index 000000000..40fac6031 --- /dev/null +++ b/lib/widgets/core/settings/health_sync.dart @@ -0,0 +1,77 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/providers/health_sync.dart'; + +class HealthSyncSettingsTile extends ConsumerStatefulWidget { + const HealthSyncSettingsTile({super.key}); + + @override + ConsumerState createState() => _HealthSyncSettingsTileState(); +} + +class _HealthSyncSettingsTileState extends ConsumerState { + bool? _isAvailable; + + @override + void initState() { + super.initState(); + _checkAvailability(); + } + + Future _checkAvailability() async { + final notifier = ref.read(healthSyncProvider.notifier); + final available = await notifier.isAvailable(); + if (mounted) { + setState(() => _isAvailable = available); + } + } + + @override + Widget build(BuildContext context) { + // Hide entirely if platform check hasn't completed or is unavailable + if (_isAvailable == null || _isAvailable == false) { + return const SizedBox.shrink(); + } + + final syncState = ref.watch(healthSyncProvider); + + return SwitchListTile( + title: const Text('Health sync'), + subtitle: const Text('Import weight from Apple Health or Health Connect'), + value: syncState.isEnabled, + onChanged: syncState.isSyncing + ? null + : (enabled) async { + final notifier = ref.read(healthSyncProvider.notifier); + if (enabled) { + final count = await notifier.enableSync(); + if (context.mounted && count > 0) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Synced $count weight entries from Health')), + ); + } + } else { + await notifier.disableSync(); + } + }, + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index ab5661fdc..5a89f2a0e 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -153,6 +153,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.1.2" + carp_serializable: + dependency: transitive + description: + name: carp_serializable + sha256: f039f8ea22e9437aef13fe7e9743c3761c76d401288dcb702eadd273c3e4dcef + url: "https://pub.dev" + source: hosted + version: "2.0.1" change: dependency: transitive description: @@ -297,6 +305,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.3" + device_info_plus: + dependency: transitive + description: + name: device_info_plus + sha256: "4df8babf73058181227e18b08e6ea3520cf5fc5d796888d33b7cb0f33f984b7c" + url: "https://pub.dev" + source: hosted + version: "12.3.0" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f + url: "https://pub.dev" + source: hosted + version: "7.0.3" drift: dependency: "direct main" description: @@ -615,6 +639,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.2" + health: + dependency: "direct main" + description: + name: health + sha256: "2d9e119f3a1d281139f93149b41032b9f80b759960875bc784c5a25dd3c17524" + url: "https://pub.dev" + source: hosted + version: "13.3.1" hooks: dependency: transitive description: @@ -1649,6 +1681,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.15.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" + url: "https://pub.dev" + source: hosted + version: "2.1.0" xdg_directories: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 036307e83..c99b5c904 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -50,6 +50,7 @@ dependencies: font_awesome_flutter: ^11.0.0 freezed_annotation: ^3.0.0 get_it: ^8.3.0 + health: ^13.3.1 http: ^1.6.0 image_picker: ^1.2.1 intl: ^0.20.0 diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index f4869b4e6..003fb7dee 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -57,17 +58,21 @@ void main() { }); Widget createSettingsScreen({locale = 'en'}) { - return MultiProvider( - providers: [ - ChangeNotifierProvider(create: (context) => mockNutritionProvider), - ChangeNotifierProvider(create: (context) => mockExerciseProvider), - ChangeNotifierProvider(create: (context) => mockUserProvider), - ], - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: const SettingsPage(), + return ProviderScope( + child: MultiProvider( + providers: [ + ChangeNotifierProvider( + create: (context) => mockNutritionProvider, + ), + ChangeNotifierProvider(create: (context) => mockExerciseProvider), + ChangeNotifierProvider(create: (context) => mockUserProvider), + ], + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const SettingsPage(), + ), ), ); } diff --git a/test/weight/weight_model_test.dart b/test/weight/weight_model_test.dart index ebc283246..e6e6eb0d1 100644 --- a/test/weight/weight_model_test.dart +++ b/test/weight/weight_model_test.dart @@ -59,5 +59,19 @@ void main() { expect(weightModel.weight, 80); expect(weightModel.date, DateTime.utc(2020, 10, 01)); }); + + test('copyWith preserves decimal weight values', () { + final entry = WeightEntry(id: 1, weight: 80.5, date: DateTime.utc(2020, 10, 01)); + final copied = entry.copyWith(weight: 81.3); + + expect(copied.weight, 81.3); + }); + + test('copyWith with null weight keeps original value', () { + final entry = WeightEntry(id: 1, weight: 80.5, date: DateTime.utc(2020, 10, 01)); + final copied = entry.copyWith(); + + expect(copied.weight, 80.5); + }); }); } diff --git a/test/weight/weight_provider_test.dart b/test/weight/weight_provider_test.dart index 61ceffe80..e21d22094 100644 --- a/test/weight/weight_provider_test.dart +++ b/test/weight/weight_provider_test.dart @@ -88,6 +88,23 @@ void main() { expect(weightEntryNew.weight, 80); }); + test('findByDate matches by calendar date regardless of time', () { + final provider = BodyWeightProvider(mockBaseProvider); + provider.items = [ + WeightEntry(id: 1, weight: 80, date: DateTime(2021, 3, 15, 7, 15)), + WeightEntry(id: 2, weight: 81, date: DateTime(2021, 3, 16, 20, 0)), + ]; + + // Same calendar date, different time + final found = provider.findByDate(DateTime(2021, 3, 15, 22, 30)); + expect(found, isNotNull); + expect(found!.id, 1); + + // No entry for this date + final notFound = provider.findByDate(DateTime(2021, 3, 17)); + expect(notFound, isNull); + }); + test('Test deleting an existing weight entry', () async { // Arrange final uri = Uri(