Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Service updates
InlitX468b28cc1a00
diff --git a/lib/services/auto_backup.dart b/lib/services/auto_backup.dartindex 20278a6..312bf2e 100644--- a/lib/services/auto_backup.dart+++ b/lib/services/auto_backup.dart@@ -1,10 +1,12 @@import 'dart:async';import 'dart:convert';import 'dart:io';+import 'dart:math' as math;import 'package:archive/archive.dart';import 'package:flutter/foundation.dart';import 'package:flutter/services.dart';+import 'package:gymmane_merge/gymmane_merge.dart';import 'package:path_provider/path_provider.dart';import '../state/fit_state.dart';@@ -19,7 +21,7 @@ class AutoBackup extends ChangeNotifier {static const _channel = MethodChannel('gymmane/backup');static const _key = 'autoBackup';- static const prefix = 'gymmane-auto-';+ static const prefix = syncPrefix;static const keepOptions = [1, 3, 5, 10, 20];bool get supported => !kIsWeb && Platform.isAndroid;@@ -33,6 +35,11 @@ class AutoBackup extends ChangeNotifier {bool failed = false;bool running = false;int _seenSessions = -1;+ String device = '';+ final Map<String, int> _pulled = {};+ DateTime? pulledAt;+ int pulledCount = 0;+ bool pulling = false;Timer? _afterWorkout;bool get hasFolder => folderUri.isNotEmpty;@@ -42,7 +49,7 @@ class AutoBackup extends ChangeNotifier {if (!supported) return;_seenSessions = fit.sessions.length;fit.addListener(_onFit);- unawaited(_checkFolder());+ unawaited(_checkFolder().then((_) => pull()));Timer(const Duration(seconds: 8), onLeave);}@@ -60,7 +67,20 @@ class AutoBackup extends ChangeNotifier {lastAt = at == null ? null : DateTime.fromMillisecondsSinceEpoch(at);_lastCrc = (j['crc'] as num?)?.toInt() ?? 0;failed = j['failed'] as bool? ?? false;+ device = j['device'] as String? ?? '';+ ((j['pulled'] as Map?) ?? const {}).forEach((k, v) {+ if (k is String && v is num) _pulled[k] = v.toInt();+ });+ final pa = (j['pulledAt'] as num?)?.toInt();+ pulledAt = pa == null ? null : DateTime.fromMillisecondsSinceEpoch(pa);+ pulledCount = (j['pulledCount'] as num?)?.toInt() ?? 0;} catch (_) {}+ if (device.isEmpty) {+ final r = math.Random.secure();+ device = String.fromCharCodes([for (var i = 0; i < 6; i++) 97 + r.nextInt(26)]);+ if (device == 'server') device = 'serves';+ _save();+ }}void _save() {@@ -74,6 +94,10 @@ class AutoBackup extends ChangeNotifier {if (lastAt != null) 'at': lastAt!.millisecondsSinceEpoch,'crc': _lastCrc,if (failed) 'failed': true,+ 'device': device,+ 'pulled': _pulled,+ if (pulledAt != null) 'pulledAt': pulledAt!.millisecondsSinceEpoch,+ 'pulledCount': pulledCount,}));notifyListeners();}@@ -165,7 +189,7 @@ class AutoBackup extends ChangeNotifier {final zip = await buildBackupZip();if (!isValidBackupZip(zip)) return false;final now = DateTime.now();- final name = '$prefix${_stamp(now)}.zip';+ final name = syncName(device, now);final tmp = File('${(await getTemporaryDirectory()).path}/$name');await tmp.writeAsBytes(zip, flush: true);try {@@ -173,7 +197,7 @@ class AutoBackup extends ChangeNotifier {'uri': folderUri,'path': tmp.path,'name': name,- 'prefix': prefix,+ 'prefix': '$prefix$device-','keep': keep,}) ??false;@@ -188,8 +212,42 @@ class AutoBackup extends ChangeNotifier {return true;}- static String _two(int n) => n.toString().padLeft(2, '0');+ Future<int> pull() async {+ if (!supported || !hasFolder || pulling) return 0;+ pulling = true;+ notifyListeners();+ var merged = 0;+ try {+ final names = await _channel.invokeListMethod<String>('list', {'uri': folderUri, 'prefix': prefix}) ?? const [];+ final newest = newestByDevice(names, self: device);+ for (final f in newest.values) {+ final seen = _pulled[f.device] ?? 0;+ if (f.at.millisecondsSinceEpoch <= seen) continue;+ final tmp = File('${(await getTemporaryDirectory()).path}/pull-${f.name}');+ try {+ final ok = await _channel.invokeMethod<bool>('read', {'uri': folderUri, 'name': f.name, 'path': tmp.path}) ?? false;+ if (!ok) continue;+ final last = lastAt;+ final result = await mergeBackupZip(await tmp.readAsBytes(), incomingNewer: last == null || f.at.isAfter(last));+ if (result == null) continue;+ _pulled[f.device] = f.at.millisecondsSinceEpoch;+ if (result) merged++;+ } finally {+ try {+ await tmp.delete();+ } catch (_) {}+ }+ }+ } catch (e) {+ debugPrint('AutoBackup pull failed: $e');+ }+ pulling = false;+ if (merged > 0 || pulledAt == null) {+ pulledAt = DateTime.now();+ pulledCount = merged;+ }+ _save();+ return merged;+ }- static String _stamp(DateTime d) =>- '${d.year}-${_two(d.month)}-${_two(d.day)}-${_two(d.hour)}${_two(d.minute)}${_two(d.second)}';}diff --git a/lib/services/beeper.dart b/lib/services/beeper.dartindex 422ff9c..cc29c1e 100644--- a/lib/services/beeper.dart+++ b/lib/services/beeper.dart@@ -19,6 +19,8 @@ class Beeper {String? _tick;String? _go;String? _silence;+ Uint8List? _tickBytes;+ Uint8List? _goBytes;Timer? _release;bool _holding = false;bool _failed = false;@@ -67,7 +69,20 @@ class Beeper {Future<bool> _ready() async {if (_player != null) return true;- if (_failed || kIsWeb) return false;+ if (_failed) return false;+ if (kIsWeb) {+ try {+ _tickBytes = _tone(880, 0.09);+ _goBytes = _tone(1318.5, 0.32);+ final p = AudioPlayer();+ await p.setReleaseMode(ReleaseMode.stop);+ _player = p;+ return true;+ } catch (_) {+ _failed = true;+ return false;+ }+ }try {final dir = await getTemporaryDirectory();_tick = await _write(dir, 'gm_tick2.wav', _tone(880, 0.09));@@ -97,6 +112,15 @@ class Beeper {kind == _TickKind.go ? HapticFeedback.heavyImpact() : HapticFeedback.selectionClick();} catch (_) {}if (!sound || !await _ready()) return;+ if (kIsWeb) {+ final bytes = kind == _TickKind.go ? _goBytes : _tickBytes;+ if (bytes == null) return;+ try {+ await _player!.stop();+ await _player!.play(BytesSource(bytes, mimeType: 'audio/wav'), volume: 1);+ } catch (_) {}+ return;+ }await _route();final path = kind == _TickKind.go ? _go : _tick;if (path == null) return;diff --git a/lib/services/health_metrics.dart b/lib/services/health_metrics.dartindex 0b4d7be..cfb5cec 100644--- a/lib/services/health_metrics.dart+++ b/lib/services/health_metrics.dart@@ -1,177 +1,177 @@-import 'dart:io';--import 'package:flutter/services.dart';--enum HealthGroup { heart, vitals, sleep, activity }--enum HealthMetric {- restingHr(HealthGroup.heart),- heartRate(HealthGroup.heart),- hrv(HealthGroup.heart),- spo2(HealthGroup.vitals),- respiration(HealthGroup.vitals),- bloodPressure(HealthGroup.vitals),- temperature(HealthGroup.vitals),- sleep(HealthGroup.sleep),- distance(HealthGroup.activity),- floors(HealthGroup.activity),- elevation(HealthGroup.activity),- activeKcal(HealthGroup.activity);-- const HealthMetric(this.group);-- final HealthGroup group;-- bool get daily => switch (this) {- restingHr || heartRate || distance || floors || elevation || activeKcal => true,- _ => false,- };-- bool get summed => switch (this) {- sleep || distance || floors || elevation || activeKcal => true,- _ => false,- };-}--class HealthMetrics {- const HealthMetrics._();-- static const _channel = MethodChannel('gymmane/health');-- static Future<Set<HealthMetric>> granted() async {- if (!(Platform.isAndroid || Platform.isIOS)) return {};- try {- final keys = await _channel.invokeListMethod<String>('metricsGranted') ?? const [];- final byName = HealthMetric.values.asNameMap();- return {for (final k in keys) ?byName[k]};- } on PlatformException {- return {};- } on MissingPluginException {- return {};- }- }-- static Future<bool> request(Iterable<HealthMetric> metrics) async {- if (!(Platform.isAndroid || Platform.isIOS)) return false;- try {- return await _channel.invokeMethod<bool>('requestMetrics', {- 'metrics': [for (final m in metrics) m.name],- }) ??- false;- } on PlatformException {- return false;- } on MissingPluginException {- return false;- }- }-- static Future<Set<String>> grantedKeys() async {- if (!(Platform.isAndroid || Platform.isIOS)) return {};- try {- return {...?await _channel.invokeListMethod<String>('metricsGranted')};- } on PlatformException {- return {};- } on MissingPluginException {- return {};- }- }-- static Future<bool> requestKeys(List<String> keys) async {- if (!(Platform.isAndroid || Platform.isIOS)) return false;- try {- return await _channel.invokeMethod<bool>('requestMetrics', {'metrics': keys}) ?? false;- } on PlatformException {- return false;- } on MissingPluginException {- return false;- }- }-- static Future<bool> writeWorkout({- required String id,- required DateTime start,- required DateTime end,- required String type,- required String title,- String notes = '',- bool manual = false,- }) async {- if (!(Platform.isAndroid || Platform.isIOS)) return false;- try {- return await _channel.invokeMethod<bool>('writeWorkout', {- 'id': id,- 'start': start.millisecondsSinceEpoch,- 'end': end.millisecondsSinceEpoch,- 'type': type,- 'title': title,- 'notes': notes,- 'manual': manual,- }) ??- false;- } on PlatformException {- return false;- } on MissingPluginException {- return false;- }- }-- static Future<bool> deleteWorkout(String id) async {- if (!(Platform.isAndroid || Platform.isIOS)) return false;- try {- return await _channel.invokeMethod<bool>('deleteWorkout', {'id': id}) ?? false;- } on PlatformException {- return false;- } on MissingPluginException {- return false;- }- }-- static Future<List<List<double>>?> read(HealthMetric metric, DateTime from, DateTime to) =>- readKey(metric.name, from, to);-- static Future<List<List<double>>?> readKey(String key, DateTime from, DateTime to) async {- if (!(Platform.isAndroid || Platform.isIOS)) return null;- try {- final rows = await _channel.invokeListMethod<Object?>('readMetric', {- 'metric': key,- 'from': from.millisecondsSinceEpoch,- 'to': to.millisecondsSinceEpoch,- });- if (rows == null) return null;- return [- for (final r in rows)- if (r is List && r.length >= 2) [for (final v in r) (v as num).toDouble()],- ];- } on PlatformException {- return null;- } on MissingPluginException {- return null;- }- }-- static Map<String, List<double>> byDay(HealthMetric metric, List<List<double>> rows) {- final sums = <String, List<double>>{};- final counts = <String, int>{};- for (final r in rows) {- final t = DateTime.fromMillisecondsSinceEpoch(r[0].round());- final key = dayKey(t);- final values = r.sublist(1);- final acc = sums[key];- if (acc == null) {- sums[key] = [...values];- } else {- for (var i = 0; i < acc.length && i < values.length; i++) {- acc[i] += values[i];- }- }- counts[key] = (counts[key] ?? 0) + 1;- }- if (metric.daily || metric.summed) return sums;- return {- for (final e in sums.entries) e.key: [for (final v in e.value) v / counts[e.key]!],- };- }-- static String dayKey(DateTime d) =>- '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';-}++import 'package:flutter/services.dart';+import 'host.dart';++enum HealthGroup { heart, vitals, sleep, activity }++enum HealthMetric {+ restingHr(HealthGroup.heart),+ heartRate(HealthGroup.heart),+ hrv(HealthGroup.heart),+ spo2(HealthGroup.vitals),+ respiration(HealthGroup.vitals),+ bloodPressure(HealthGroup.vitals),+ temperature(HealthGroup.vitals),+ sleep(HealthGroup.sleep),+ distance(HealthGroup.activity),+ floors(HealthGroup.activity),+ elevation(HealthGroup.activity),+ activeKcal(HealthGroup.activity);++ const HealthMetric(this.group);++ final HealthGroup group;++ bool get daily => switch (this) {+ restingHr || heartRate || distance || floors || elevation || activeKcal => true,+ _ => false,+ };++ bool get summed => switch (this) {+ sleep || distance || floors || elevation || activeKcal => true,+ _ => false,+ };+}++class HealthMetrics {+ const HealthMetrics._();++ static const _channel = MethodChannel('gymmane/health');++ static Future<Set<HealthMetric>> granted() async {+ if (!onMobile) return {};+ try {+ final keys = await _channel.invokeListMethod<String>('metricsGranted') ?? const [];+ final byName = HealthMetric.values.asNameMap();+ return {for (final k in keys) ?byName[k]};+ } on PlatformException {+ return {};+ } on MissingPluginException {+ return {};+ }+ }++ static Future<bool> request(Iterable<HealthMetric> metrics) async {+ if (!onMobile) return false;+ try {+ return await _channel.invokeMethod<bool>('requestMetrics', {+ 'metrics': [for (final m in metrics) m.name],+ }) ??+ false;+ } on PlatformException {+ return false;+ } on MissingPluginException {+ return false;+ }+ }++ static Future<Set<String>> grantedKeys() async {+ if (!onMobile) return {};+ try {+ return {...?await _channel.invokeListMethod<String>('metricsGranted')};+ } on PlatformException {+ return {};+ } on MissingPluginException {+ return {};+ }+ }++ static Future<bool> requestKeys(List<String> keys) async {+ if (!onMobile) return false;+ try {+ return await _channel.invokeMethod<bool>('requestMetrics', {'metrics': keys}) ?? false;+ } on PlatformException {+ return false;+ } on MissingPluginException {+ return false;+ }+ }++ static Future<bool> writeWorkout({+ required String id,+ required DateTime start,+ required DateTime end,+ required String type,+ required String title,+ String notes = '',+ bool manual = false,+ }) async {+ if (!onMobile) return false;+ try {+ return await _channel.invokeMethod<bool>('writeWorkout', {+ 'id': id,+ 'start': start.millisecondsSinceEpoch,+ 'end': end.millisecondsSinceEpoch,+ 'type': type,+ 'title': title,+ 'notes': notes,+ 'manual': manual,+ }) ??+ false;+ } on PlatformException {+ return false;+ } on MissingPluginException {+ return false;+ }+ }++ static Future<bool> deleteWorkout(String id) async {+ if (!onMobile) return false;+ try {+ return await _channel.invokeMethod<bool>('deleteWorkout', {'id': id}) ?? false;+ } on PlatformException {+ return false;+ } on MissingPluginException {+ return false;+ }+ }++ static Future<List<List<double>>?> read(HealthMetric metric, DateTime from, DateTime to) =>+ readKey(metric.name, from, to);++ static Future<List<List<double>>?> readKey(String key, DateTime from, DateTime to) async {+ if (!onMobile) return null;+ try {+ final rows = await _channel.invokeListMethod<Object?>('readMetric', {+ 'metric': key,+ 'from': from.millisecondsSinceEpoch,+ 'to': to.millisecondsSinceEpoch,+ });+ if (rows == null) return null;+ return [+ for (final r in rows)+ if (r is List && r.length >= 2) [for (final v in r) (v as num).toDouble()],+ ];+ } on PlatformException {+ return null;+ } on MissingPluginException {+ return null;+ }+ }++ static Map<String, List<double>> byDay(HealthMetric metric, List<List<double>> rows) {+ final sums = <String, List<double>>{};+ final counts = <String, int>{};+ for (final r in rows) {+ final t = DateTime.fromMillisecondsSinceEpoch(r[0].round());+ final key = dayKey(t);+ final values = r.sublist(1);+ final acc = sums[key];+ if (acc == null) {+ sums[key] = [...values];+ } else {+ for (var i = 0; i < acc.length && i < values.length; i++) {+ acc[i] += values[i];+ }+ }+ counts[key] = (counts[key] ?? 0) + 1;+ }+ if (metric.daily || metric.summed) return sums;+ return {+ for (final e in sums.entries) e.key: [for (final v in e.value) v / counts[e.key]!],+ };+ }++ static String dayKey(DateTime d) =>+ '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';+}diff --git a/lib/services/health_steps.dart b/lib/services/health_steps.dartindex e42f5f1..c0f16d0 100644--- a/lib/services/health_steps.dart+++ b/lib/services/health_steps.dart@@ -1,7 +1,7 @@-import 'dart:io';import 'dart:math' as math;import 'package:flutter/services.dart';+import 'host.dart';enum HealthAccess { unsupported, denied, granted }@@ -17,7 +17,7 @@ class HealthSteps {}static Future<bool> takeUsage() async {- if (!Platform.isAndroid) return false;+ if (!onAndroid) return false;try {return await _channel.invokeMethod<bool>('takeUsage') ?? false;} on PlatformException {@@ -28,7 +28,7 @@ class HealthSteps {}static Future<HealthAccess> access() async {- if (!(Platform.isAndroid || Platform.isIOS)) return HealthAccess.unsupported;+ if (!onMobile) return HealthAccess.unsupported;try {final status = await _channel.invokeMethod<String>('status');return HealthAccess.values.asNameMap()[status] ?? HealthAccess.unsupported;@@ -40,7 +40,7 @@ class HealthSteps {}static Future<bool> request() async {- if (!(Platform.isAndroid || Platform.isIOS)) return false;+ if (!onMobile) return false;try {return await _channel.invokeMethod<bool>('request') ?? false;} on PlatformException {@@ -51,7 +51,7 @@ class HealthSteps {}static Future<bool> openSettings() async {- if (!(Platform.isAndroid || Platform.isIOS)) return false;+ if (!onMobile) return false;try {return await _channel.invokeMethod<bool>('openSettings') ?? false;} on PlatformException {@@ -62,7 +62,7 @@ class HealthSteps {}static Future<Map<DateTime, int>?> read(List<DateTime> days) async {- if (days.isEmpty || !(Platform.isAndroid || Platform.isIOS)) return null;+ if (days.isEmpty || !onMobile) return null;final now = DateTime.now().millisecondsSinceEpoch;final ranges = [for (final day in days)diff --git a/lib/services/live_workout.dart b/lib/services/live_workout.dartindex 5a74eb6..41f79af 100644--- a/lib/services/live_workout.dart+++ b/lib/services/live_workout.dart@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';import '../l10n/l10n.dart';import '../state/fit_state.dart';import '../widgets/ui_kit.dart';+import 'host.dart';class LiveWorkout {LiveWorkout._();@@ -24,7 +25,7 @@ class LiveWorkout {static Future<void> sync() async {if (!_supported) return;- if (!_listening && Platform.isAndroid) {+ if (!_listening && onAndroid) {_listening = true;_android.setMethodCallHandler((call) async {if (call.method == 'action') _act(call.arguments as String? ?? '');@@ -117,14 +118,14 @@ class LiveWorkout {_lastKey = key;try {- if (Platform.isIOS) {+ if (onIOS) {await _channel.invokeMethod<void>('update', {'exercise': name,'detail': detail,'index': index,'total': total,'restEnd': resting ? restEnd.millisecondsSinceEpoch : null,- 'restLabel': t.liveResting,+ 'restLabel': fit.session?.restSwitch == true ? t.switchSides : t.liveResting,'paused': paused,});return;@@ -132,7 +133,7 @@ class LiveWorkout {await _android.invokeMethod<void>('update', {'title': name,'detail': detail,- 'restLabel': t.liveResting,+ 'restLabel': fit.session?.restSwitch == true ? t.switchSides : t.liveResting,'next': nextName == null ? null : t.liveUpNext(nextName),'resting': resting,'paused': paused,@@ -190,7 +191,7 @@ class LiveWorkout {final wasShown = _lastKey.isNotEmpty;_lastKey = '';try {- if (Platform.isIOS) {+ if (onIOS) {await _channel.invokeMethod<void>('end');} else if (wasShown || !_cleared) {await _android.invokeMethod<void>('end');diff --git a/lib/services/local_store.dart b/lib/services/local_store.dartindex ea3aa1d..aa6b9d3 100644--- a/lib/services/local_store.dart+++ b/lib/services/local_store.dart@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';import 'package:shared_preferences/shared_preferences.dart';import '../models/workout.dart';+import 'server/server_link.dart';class Store {Store._();@@ -14,10 +15,20 @@ class Store {Future<void> init() async {_prefs ??= await SharedPreferences.getInstance();+ if (kIsWeb) await ServerLink.instance.connect();}Map<String, dynamic> load() {- final raw = _prefs?.getString(_key);+ final link = ServerLink.instance;+ var raw = link.available ? link.remoteText : null;+ if (raw == null) {+ raw = _prefs?.getString(_key);+ if (link.available && raw != null && raw.isNotEmpty) link.push(raw);+ }+ return decodeState(raw);+ }++ static Map<String, dynamic> decodeState(String? raw) {if (raw == null || raw.isEmpty) return {};try {final decoded = jsonDecode(raw);@@ -37,6 +48,11 @@ class Store {for (final e in raw.entries) {text = text.replaceFirst(jsonEncode(rawMark(e.key)), e.value);}+ final link = ServerLink.instance;+ if (link.available) {+ link.push(text);+ return;+ }await _prefs?.setString(_key, text);} catch (e) {debugPrint('Store.save failed: $e');diff --git a/lib/services/rest_alarm.dart b/lib/services/rest_alarm.dartindex bc7380f..a64905d 100644--- a/lib/services/rest_alarm.dart+++ b/lib/services/rest_alarm.dart@@ -1,4 +1,3 @@-import 'dart:io' show Platform;import 'package:audioplayers/audioplayers.dart';import 'package:flutter/foundation.dart';@@ -10,6 +9,8 @@ import 'package:timezone/timezone.dart' as tz;import '../l10n/l10n.dart';import 'headphones.dart';+import 'supplement_reminder.dart';+import 'host.dart';class RestAlarm {RestAlarm._();@@ -118,6 +119,8 @@ class RestAlarm {requestBadgePermission: false,),),+ onDidReceiveNotificationResponse: (r) => SupplementReminder.instance.tapped(r.payload),+ onDidReceiveBackgroundNotificationResponse: supplementActionInBackground,);_ready = true;} catch (e) {@@ -188,7 +191,7 @@ class RestAlarm {Future<bool> notificationsAllowed() async {if (!_ready) return true;try {- if (Platform.isIOS) {+ if (onIOS) {final options = await _iosPlugin?.checkPermissions();return options?.isEnabled ?? true;}@@ -201,7 +204,7 @@ class RestAlarm {Future<bool> requestPermission() async {if (!_ready) return true;try {- if (Platform.isIOS) {+ if (onIOS) {return await _iosPlugin?.requestPermissions(alert: true, sound: true) ?? true;}final granted = await _androidPlugin?.requestNotificationsPermission() ?? true;@@ -222,7 +225,7 @@ class RestAlarm {Future<void> fireNow() async {final visible = WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed;final custom = customSoundPath?.isNotEmpty ?? false;- if (_ready && !visible && !custom && Platform.isAndroid) {+ if (_ready && !visible && !custom && onAndroid) {_generation++;return;}diff --git a/lib/services/supplement_reminder.dart b/lib/services/supplement_reminder.dartindex f898157..4434deb 100644--- a/lib/services/supplement_reminder.dart+++ b/lib/services/supplement_reminder.dart@@ -1,16 +1,113 @@+import 'dart:isolate';+import 'dart:ui';+import 'package:flutter/foundation.dart';import 'package:flutter_local_notifications/flutter_local_notifications.dart';+import 'package:shared_preferences/shared_preferences.dart';import '../l10n/l10n.dart';import 'notif_sound.dart';import 'train_reminder.dart';+@pragma('vm:entry-point')+Future<void> supplementActionInBackground(NotificationResponse r) async {+ final payload = r.payload;+ if (r.actionId != SupplementReminder.takeAction || payload == null) return;+ final port = IsolateNameServer.lookupPortByName(SupplementReminder._portName);+ if (port != null) {+ port.send(payload);+ return;+ }+ try {+ final prefs = await SharedPreferences.getInstance();+ await prefs.reload();+ final list = prefs.getStringList(SupplementReminder._pendingKey) ?? const [];+ await prefs.setStringList(SupplementReminder._pendingKey, [...list, payload]);+ } catch (e) {+ debugPrint('Aviso de suplementos (tomado): $e');+ }+}+class SupplementReminder {SupplementReminder._();static final SupplementReminder instance = SupplementReminder._();static const _firstId = 1030;static const _slots = 32;+ static const payloadPrefix = 'supp:';++ static const takeAction = 'supp_take';+ static const _portName = 'gymmane_supp_take';+ static const _pendingKey = 'gm_supp_taken_pending';++ void Function(List<String> ids)? onOpen;+ void Function(DateTime day, List<String> ids)? onTaken;+ ReceivePort? _port;++ void tapped(String? payload) {+ final ids = idsOf(payload);+ if (ids != null) onOpen?.call(ids);+ }++ static List<String>? idsOf(String? payload) {+ if (payload == null || !payload.startsWith(payloadPrefix)) return null;+ return payload.substring(payloadPrefix.length).split(';').first.split(',').where((e) => e.isNotEmpty).toList();+ }++ static DateTime? dayOf(String payload) {+ final parts = payload.split(';');+ if (parts.length < 2) return null;+ final ms = int.tryParse(parts[1]);+ if (ms == null) return null;+ final at = DateTime.fromMillisecondsSinceEpoch(ms);+ return DateTime(at.year, at.month, at.day);+ }++ static String payloadFor(DateTime at, List<String> ids) =>+ '$payloadPrefix${ids.join(',')};${at.millisecondsSinceEpoch}';++ void listenTaken(void Function(DateTime day, List<String> ids) handler) {+ onTaken = handler;+ if (kIsWeb || _port != null) return;+ final port = ReceivePort();+ IsolateNameServer.removePortNameMapping(_portName);+ IsolateNameServer.registerPortWithName(port.sendPort, _portName);+ port.listen((m) {+ if (m is String) _apply(m);+ });+ _port = port;+ }++ Future<void> takePending() async {+ if (kIsWeb) return;+ try {+ final prefs = await SharedPreferences.getInstance();+ await prefs.reload();+ final list = prefs.getStringList(_pendingKey);+ if (list == null || list.isEmpty) return;+ await prefs.remove(_pendingKey);+ list.forEach(_apply);+ } catch (e) {+ debugPrint('Aviso de suplementos (pendientes): $e');+ }+ }++ void _apply(String payload) {+ final ids = idsOf(payload);+ if (ids == null || ids.isEmpty) return;+ final now = DateTime.now();+ onTaken?.call(dayOf(payload) ?? DateTime(now.year, now.month, now.day), ids);+ }++ Future<List<String>?> launchIds() async {+ try {+ final d = await _plugin.getNotificationAppLaunchDetails();+ if (d == null || !d.didNotificationLaunchApp) return null;+ return idsOf(d.notificationResponse?.payload);+ } catch (_) {+ return null;+ }+ }final _plugin = FlutterLocalNotificationsPlugin();bool enabled = true;@@ -27,6 +124,7 @@ class SupplementReminder {priority: Priority.defaultPriority,playSound: NotifSound.plays(SoundGroup.food),sound: NotifSound.soundOf(SoundGroup.food),+ actions: [AndroidNotificationAction(takeAction, t.notifSuppTake)],);DarwinNotificationDetails get _darwin => const DarwinNotificationDetails(@@ -47,30 +145,32 @@ class SupplementReminder {}}- Future<void> schedule(List<({DateTime at, List<String> names, List<String> doses})> due) =>+ Future<void> schedule(List<({DateTime at, List<String> ids, List<String> names, List<String> doses})> due) =>_serial(() => _schedule(due));- Future<void> _schedule(List<({DateTime at, List<String> names, List<String> doses})> list) async {+ Future<void> _schedule(List<({DateTime at, List<String> ids, List<String> names, List<String> doses})> list) async {if (!enabled) return;await _cancel();if (list.isEmpty) return;final mode = await reminderMode(_plugin);- final due = <(DateTime, String, String)>[+ final due = <(DateTime, String, String, String)>[for (final d in list)(d.at,t.notifSuppTitleFor(d.names.join(', ')),d.doses.isEmpty ? t.notifSuppTap : d.doses.join(' · '),+ payloadFor(d.at, d.ids),),];due.sort((a, b) => a.$1.compareTo(b.$1));var slot = 0;- for (final (day, title, body) in due.take(_slots)) {+ for (final (day, title, body, payload) in due.take(_slots)) {try {await _plugin.zonedSchedule(id: _firstId + slot,title: title,body: body,+ payload: payload,scheduledDate: atLocal(day),notificationDetails: NotificationDetails(android: _android, iOS: _darwin),androidScheduleMode: mode,