Skip to content

Offline gym log for Android. No account, no ads, no internet.

Back up to a ZIP that carries the media with it

InlitXb740c6408c9d
diff --git a/lib/services/backup_zip.dart b/lib/services/backup_zip.dart
new file mode 100644
index 0000000..fa69a70
--- /dev/null
+++ b/lib/services/backup_zip.dart
@@ -0,0 +1,217 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:archive/archive.dart';
+
+import '../models/exercise.dart';
+import '../models/note.dart';
+import '../models/progress_shot.dart';
+import '../state/fit_state.dart';
+import 'alarm_store.dart';
+import 'media_store.dart';
+
+const String kBackupJsonEntry = 'gymmane.json';
+const String _imagesDir = 'media/images';
+const String _videosDir = 'media/videos';
+const String _notesDir = 'media/notes';
+const String _progressDir = 'media/progress';
+const String _alarmDir = 'alarm';
+
+bool looksLikeZip(Uint8List b) =>
+ b.length > 4 && b[0] == 0x50 && b[1] == 0x4B && (b[2] == 0x03 || b[2] == 0x05 || b[2] == 0x07);
+
+/// Copia completa: el JSON de datos más el media propio del usuario,
+/// repartido en carpetas y renombrado con el ejercicio al que pertenece.
+Future<Uint8List> buildBackupZip() async {
+ final data = fit.toJson();
+ final archive = Archive();
+ final used = <String>{};
+ final paths = <String, String>{};
+
+ for (final entry in fit.exerciseMedia.entries) {
+ final bytes = await MediaStore.readBytes(entry.value);
+ if (bytes == null || bytes.isEmpty) continue;
+ final ex = fit.exerciseById(entry.key);
+ final dir = MediaStore.isVideo(entry.value) ? _videosDir : _imagesDir;
+ final name = _uniqueName(used, slugify(ex == null ? entry.key : exerciseName(ex)),
+ MediaStore.extOf(entry.value));
+ archive.addFile(ArchiveFile.noCompress('$dir/$name', bytes.length, bytes));
+ paths[entry.key] = '$dir/$name';
+ }
+ data['media'] = paths;
+
+ final noteMedia = <String, String>{};
+ for (final note in fit.notes) {
+ for (final m in note.media) {
+ if (noteMedia.containsKey(m)) continue;
+ final bytes = await MediaStore.readBytes(m);
+ if (bytes == null || bytes.isEmpty) continue;
+ final name = _uniqueName(used, _noteSlug(note), MediaStore.extOf(m));
+ archive.addFile(ArchiveFile.noCompress('$_notesDir/$name', bytes.length, bytes));
+ noteMedia[m] = '$_notesDir/$name';
+ }
+ }
+ data['noteMedia'] = noteMedia;
+
+ final shotMedia = <String, String>{};
+ for (final entry in fit.timelineAsc) {
+ for (final pose in kPoses) {
+ final name = entry.shot(pose);
+ if (name == null || shotMedia.containsKey(name)) continue;
+ final bytes = await MediaStore.readBytes(name);
+ if (bytes == null || bytes.isEmpty) continue;
+ final file = _uniqueName(used, '${_day(entry.date)}-$pose', MediaStore.extOf(name));
+ archive.addFile(ArchiveFile.noCompress('$_progressDir/$file', bytes.length, bytes));
+ shotMedia[name] = '$_progressDir/$file';
+ }
+ }
+ data['shotMedia'] = shotMedia;
+
+ final alarm = fit.alarmSound;
+ final alarmPath = alarm == null ? null : AlarmStore.pathFor(alarm);
+ if (alarm != null && alarmPath != null) {
+ try {
+ final bytes = await File(alarmPath).readAsBytes();
+ archive.addFile(ArchiveFile.noCompress('$_alarmDir/$alarm', bytes.length, bytes));
+ } catch (_) {}
+ }
+
+ archive.addFile(
+ ArchiveFile.string(kBackupJsonEntry, const JsonEncoder.withIndent(' ').convert(data)));
+ return ZipEncoder().encodeBytes(archive);
+}
+
+/// Restaura una copia en zip: vuelca el media a disco con nombres internos y
+/// deja el JSON apuntando a los ficheros ya restaurados.
+Future<bool> restoreBackupZip(Uint8List zipBytes) async {
+ final Archive archive;
+ try {
+ archive = ZipDecoder().decodeBytes(zipBytes);
+ } catch (_) {
+ return false;
+ }
+
+ final jsonFile = _findJson(archive);
+ if (jsonFile == null) return false;
+ final Map<String, dynamic> data;
+ try {
+ final decoded = jsonDecode(utf8.decode(jsonFile.readBytes() ?? const []));
+ if (decoded is! Map<String, dynamic>) return false;
+ data = decoded;
+ } catch (_) {
+ return false;
+ }
+
+ await MediaStore.clearAll();
+ final wanted = <String, String>{};
+ ((data['media'] as Map?) ?? {}).forEach((k, v) {
+ if (k is String && v is String && v.isNotEmpty) wanted[k] = v;
+ });
+ final restored = <String, String>{};
+ for (final e in wanted.entries) {
+ final bytes = archive.findFile(e.value)?.readBytes();
+ if (bytes == null) continue;
+ final base = await MediaStore.saveBytes(e.key, MediaStore.extOf(e.value), bytes);
+ if (base != null) restored[e.key] = base;
+ }
+
+ final wantedNotes = <String, String>{};
+ ((data['noteMedia'] as Map?) ?? {}).forEach((k, v) {
+ if (k is String && v is String && v.isNotEmpty) wantedNotes[k] = v;
+ });
+ final restoredNotes = <String, String>{};
+ for (final e in wantedNotes.entries) {
+ final bytes = archive.findFile(e.value)?.readBytes();
+ if (bytes == null) continue;
+ final base = await MediaStore.saveBytes('note', MediaStore.extOf(e.value), bytes);
+ if (base != null) restoredNotes[e.key] = base;
+ }
+
+ final wantedShots = <String, String>{};
+ ((data['shotMedia'] as Map?) ?? {}).forEach((k, v) {
+ if (k is String && v is String && v.isNotEmpty) wantedShots[k] = v;
+ });
+ final restoredShots = <String, String>{};
+ for (final e in wantedShots.entries) {
+ final bytes = archive.findFile(e.value)?.readBytes();
+ if (bytes == null) continue;
+ final base = await MediaStore.saveBytes('shot', MediaStore.extOf(e.value), bytes);
+ if (base != null) restoredShots[e.key] = base;
+ }
+
+ final alarmName = data['alarmSound'] as String?;
+ String? alarmBase;
+ if (alarmName != null && alarmName.isNotEmpty) {
+ final bytes = archive.findFile('$_alarmDir/$alarmName')?.readBytes();
+ if (bytes != null) alarmBase = await AlarmStore.saveBytes(alarmName, bytes);
+ }
+
+ fit.applyBackup(data,
+ restoredMedia: restored,
+ restoredNoteMedia: restoredNotes,
+ restoredShots: restoredShots);
+ if (alarmBase != null) {
+ fit.setAlarmSound(alarmBase, (data['alarmSoundName'] as String?) ?? alarmBase);
+ } else {
+ await fit.clearAlarmSound();
+ }
+ return true;
+}
+
+ArchiveFile? _findJson(Archive a) {
+ ArchiveFile? fallback;
+ for (final f in a.files) {
+ if (!f.isFile || !f.name.toLowerCase().endsWith('.json')) continue;
+ if (f.name == kBackupJsonEntry) return f;
+ fallback ??= f;
+ }
+ return fallback;
+}
+
+String _day(DateTime d) => '${d.year}-${_two(d.month)}-${_two(d.day)}';
+
+String _noteSlug(GymNote n) {
+ final day = _day(n.date);
+ final title = slugify(n.title);
+ final short = title.length <= 28 ? title : title.substring(0, 28);
+ return short.isEmpty ? day : '$day-$short';
+}
+
+String _two(int n) => n.toString().padLeft(2, '0');
+
+String _uniqueName(Set<String> used, String slug, String ext) {
+ final base = slug.isEmpty ? 'exercise' : slug;
+ var name = '$base.$ext';
+ var n = 2;
+ while (!used.add(name)) {
+ name = '$base-$n.$ext';
+ n++;
+ }
+ return name;
+}
+
+const Map<String, String> _fold = {
+ 'á': 'a', 'à': 'a', 'ä': 'a', 'â': 'a', 'ã': 'a', 'å': 'a',
+ 'é': 'e', 'è': 'e', 'ë': 'e', 'ê': 'e',
+ 'í': 'i', 'ì': 'i', 'ï': 'i', 'î': 'i',
+ 'ó': 'o', 'ò': 'o', 'ö': 'o', 'ô': 'o', 'õ': 'o',
+ 'ú': 'u', 'ù': 'u', 'ü': 'u', 'û': 'u',
+ 'ñ': 'n', 'ç': 'c', 'ß': 'ss',
+};
+
+String slugify(String name) {
+ final buffer = StringBuffer();
+ for (final ch in name.toLowerCase().split('')) {
+ final folded = _fold[ch] ?? ch;
+ if (RegExp(r'^[a-z0-9]+$').hasMatch(folded)) {
+ buffer.write(folded);
+ } else {
+ buffer.write('-');
+ }
+ }
+ return buffer
+ .toString()
+ .replaceAll(RegExp('-+'), '-')
+ .replaceAll(RegExp(r'^-|-$'), '');
+}
diff --git a/test/backup_zip_test.dart b/test/backup_zip_test.dart
new file mode 100644
index 0000000..921f6ba
--- /dev/null
+++ b/test/backup_zip_test.dart
@@ -0,0 +1,215 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:archive/archive.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:gymmane/catalog/exercise_catalog.dart';
+import 'package:gymmane/models/exercise.dart';
+import 'package:gymmane/models/note.dart';
+import 'package:gymmane/services/progress_reminder.dart';
+import 'package:gymmane/services/backup_zip.dart';
+import 'package:gymmane/services/local_store.dart';
+import 'package:gymmane/services/media_store.dart';
+import 'package:gymmane/state/fit_state.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ late Directory tmp;
+ final png = Uint8List.fromList([0x89, 0x50, 0x4E, 0x47, 1, 2, 3, 4]);
+ final mp4 = Uint8List.fromList(List<int>.generate(64, (i) => i));
+
+ final pushUp = kExercises.firstWhere((e) => e.equipment == 'Bodyweight');
+ final bench = kExercises.firstWhere((e) => e.equipment == 'Barbell');
+
+ setUp(() async {
+ SharedPreferences.setMockInitialValues({});
+ await Store.instance.init();
+ tmp = await Directory.systemTemp.createTemp('gymmane_media');
+ MediaStore.directory = tmp.path;
+ ProgressReminder.instance.enabled = false;
+ fit.resetAllData();
+ });
+
+ tearDown(() async {
+ MediaStore.directory = null;
+ if (tmp.existsSync()) await tmp.delete(recursive: true);
+ });
+
+ Future<String> source(String name, Uint8List bytes) async {
+ final f = File('${tmp.path}/$name');
+ await f.writeAsBytes(bytes, flush: true);
+ return f.path;
+ }
+
+ test('the zip keeps the data json and renames the media after the exercise', () async {
+ await fit.attachExerciseMedia(pushUp.id, await source('IMG_1800.png', png));
+ await fit.attachExerciseMedia(bench.id, await source('clip.mp4', mp4));
+
+ final archive = ZipDecoder().decodeBytes(await buildBackupZip());
+ final names = archive.files.map((f) => f.name).toList();
+
+ expect(names, contains(kBackupJsonEntry));
+ expect(names, contains('media/images/${slugify(exerciseName(pushUp))}.png'));
+ expect(names, contains('media/videos/${slugify(exerciseName(bench))}.mp4'));
+ expect(archive.findFile('media/images/${slugify(exerciseName(pushUp))}.png')!.readBytes(), png);
+
+ final data = jsonDecode(utf8.decode(archive.findFile(kBackupJsonEntry)!.readBytes()!))
+ as Map<String, dynamic>;
+ expect((data['media'] as Map)[pushUp.id], 'media/images/${slugify(exerciseName(pushUp))}.png');
+ });
+
+ test('two exercises with the same name do not overwrite each other', () async {
+ final id = fit.addCustomExercise(
+ name: exerciseName(pushUp), primary: 'chest', equipment: 'Bodyweight');
+ await fit.attachExerciseMedia(pushUp.id, await source('a.png', png));
+ await fit.attachExerciseMedia(id, await source('b.png', png));
+
+ final slug = slugify(exerciseName(pushUp));
+ final names = ZipDecoder().decodeBytes(await buildBackupZip()).files.map((f) => f.name);
+ expect(names, contains('media/images/$slug.png'));
+ expect(names, contains('media/images/$slug-2.png'));
+ });
+
+ test('importing the zip brings back the data and the media files', () async {
+ fit.updateProfile(name: 'Alex');
+ fit.toggleRepsOnly(bench.id);
+ await fit.attachExerciseMedia(pushUp.id, await source('IMG_1800.png', png));
+ final zip = await buildBackupZip();
+
+ fit.resetAllData();
+ expect(fit.mediaFor(pushUp.id), '');
+
+ expect(await restoreBackupZip(zip), true);
+ expect(fit.profile.name, 'Alex');
+ expect(fit.isRepsOnly(bench.id), true);
+
+ final restored = fit.mediaFor(pushUp.id);
+ expect(restored, isNotEmpty);
+ expect(await MediaStore.readBytes(restored), png);
+ });
+
+ test('a zip without media still restores, and a broken file is rejected', () async {
+ fit.updateProfile(name: 'Alex');
+ final zip = await buildBackupZip();
+ fit.resetAllData();
+
+ expect(await restoreBackupZip(zip), true);
+ expect(fit.profile.name, 'Alex');
+ expect(fit.exerciseMedia, isEmpty);
+ expect(await restoreBackupZip(Uint8List.fromList([1, 2, 3, 4, 5])), false);
+ });
+
+ test('a json backup from 1.0 still imports, media included', () async {
+ await fit.attachExerciseMedia(pushUp.id, await source('IMG_1800.png', png));
+ final legacy = fit.exportJson();
+ final basename = fit.mediaFor(pushUp.id);
+
+ fit.exerciseMedia.clear();
+ expect(fit.importJson(legacy), true);
+ expect(fit.mediaFor(pushUp.id), basename);
+ });
+
+ test('the zip carries the photos hanging off a note and brings them back', () async {
+ fit.saveNote(
+ exerciseId: pushUp.id,
+ date: DateTime(2026, 9, 3),
+ kind: NoteKind.done,
+ text: 'Primera dominada limpia',
+ media: [(await MediaStore.importFor('note', await source('shot.png', png)))!]);
+
+ final zip = await buildBackupZip();
+ final archive = ZipDecoder().decodeBytes(zip);
+ expect(archive.files.map((f) => f.name),
+ contains('media/notes/2026-09-03-primera-dominada-limpia.png'));
+
+ fit.resetAllData();
+ expect(await restoreBackupZip(zip), true);
+
+ final note = fit.notes.single;
+ expect(note.text, 'Primera dominada limpia');
+ expect(note.media, hasLength(1));
+ expect(await MediaStore.readBytes(note.media.single), png);
+ });
+
+ test('a 1.0 backup with the old per-exercise notes lands in the journal', () {
+ expect(
+ fit.importJson(jsonEncode({
+ 'profile': {'name': 'Alex'},
+ 'exNotes': {
+ pushUp.id: [
+ {'d': '2026-07-16T17:12:08.558090', 't': 'Subir a 82.5 la próxima.'},
+ ],
+ },
+ })),
+ true);
+
+ final note = fit.notesFor(pushUp.id).single;
+ expect(note.text, 'Subir a 82.5 la próxima.');
+ expect(note.kind, NoteKind.note);
+ expect(note.date, DateTime(2026, 7, 16));
+ });
+
+ test('a note whose file is gone does not sink the backup', () async {
+ fit.saveNote(
+ exerciseId: pushUp.id,
+ date: DateTime(2026, 9, 3),
+ kind: NoteKind.note,
+ text: 'sin foto',
+ media: const ['note-desaparecida.png']);
+
+ final zip = await buildBackupZip();
+ fit.resetAllData();
+ expect(await restoreBackupZip(zip), true);
+ expect(fit.notes.single.media, isEmpty);
+ });
+
+ test('the progress photos travel in the zip named by day and pose', () async {
+ await fit.attachShot(DateTime(2026, 2, 1), 'front', await source('f.png', png));
+ await fit.attachShot(DateTime(2026, 2, 1), 'back', await source('b.png', png));
+ fit.setPhotoInterval(15);
+
+ final zip = await buildBackupZip();
+ final names = ZipDecoder().decodeBytes(zip).files.map((f) => f.name);
+ expect(names, contains('media/progress/2026-02-01-front.png'));
+ expect(names, contains('media/progress/2026-02-01-back.png'));
+
+ fit.resetAllData();
+ expect(await restoreBackupZip(zip), true);
+
+ final entry = fit.timeline.single;
+ expect(entry.date, DateTime(2026, 2, 1));
+ expect(entry.shots.keys, containsAll(['front', 'back']));
+ expect(await MediaStore.readBytes(entry.shot('front')!), png);
+ expect(fit.photoIntervalDays, 15);
+ });
+
+ test('a day whose photos are missing from the zip is dropped, not left broken', () async {
+ await fit.attachShot(DateTime(2026, 2, 1), 'front', await source('f.png', png));
+ final zip = await buildBackupZip();
+ final stripped = Archive();
+ for (final f in ZipDecoder().decodeBytes(zip).files) {
+ if (f.name.startsWith('media/progress/')) continue;
+ final bytes = f.readBytes()!;
+ stripped.addFile(ArchiveFile.noCompress(f.name, bytes.length, bytes));
+ }
+
+ fit.resetAllData();
+ expect(await restoreBackupZip(ZipEncoder().encodeBytes(stripped)), true);
+ expect(fit.timeline, isEmpty);
+ });
+
+ test('slugs are file-safe and keep the exercise readable', () {
+ expect(slugify('Flexiones'), 'flexiones');
+ expect(slugify('Press de banca — inclinado'), 'press-de-banca-inclinado');
+ expect(slugify('Curl 21s / bíceps'), 'curl-21s-biceps');
+ expect(slugify('...'), '');
+ });
+
+ test('looksLikeZip only accepts a real zip header', () {
+ expect(looksLikeZip(Uint8List.fromList([0x50, 0x4B, 0x03, 0x04, 0])), true);
+ expect(looksLikeZip(Uint8List.fromList(utf8.encode('{"profile":{}}'))), false);
+ });
+}