mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-19 01:54:23 +01:00
Mirror the in-progress session so an app-data wipe can't lose your set
The active session (which set you are on, and the reps done so far) lived only in app-private SQLite. An uninstall — or `pm clear`, which sounds harmless and is not — wipes that, so a user standing mid-workout loses the exact set and rep they were on. `backup.json` did not help: it mirrors only COMPLETED history. This is not hypothetical; it happened, mid-workout, and the state had to be re-entered by hand. Persistence granularity was already right (saveActiveSession fires on every set tap, untap, warmup and break change, storing `tapped` + `doneReps`). Only the LOCATION was wrong, so this mirrors it the same way the sync token already is: - BackupService.exportActiveSession/readActiveSession keep /sdcard/WorkoutTracker/active_session.json; a null export clears it. - StorageService.saveActiveSession mirrors on every write; loadActiveSession falls back to the mirror and re-seeds the table when it is empty — exactly the state after a wipe; clearActiveSession clears the mirror too, so a finished workout is never resurrected. - Both reads are defensive: a truncated/non-object mirror (battery death mid-set) is ignored rather than bricking the resume. Tested by simulating the wipe in the suite (resetForTesting + fresh init with the mirror intact), not on a real device holding real data. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Fv8ULVt3Q67GwCFbM7doHB
This commit is contained in:
parent
b026dfd074
commit
65380df425
@ -26,6 +26,14 @@ const String kBackupPath = '$kBackupDir/backup.json';
|
||||
/// Path where the GitHub sync token is mirrored on external storage.
|
||||
const String kSyncTokenBackupPath = '$kBackupDir/sync_token';
|
||||
|
||||
/// Path where the IN-PROGRESS session is mirrored on external storage.
|
||||
///
|
||||
/// The active session (which set you are on, and the reps done so far) lives
|
||||
/// in app-private SQLite, which an uninstall or `pm clear` wipes — losing the
|
||||
/// workout you are standing in the middle of. Mirroring it here means even a
|
||||
/// full app-data wipe resumes on the exact set and rep.
|
||||
const String kActiveSessionBackupPath = '$kBackupDir/active_session.json';
|
||||
|
||||
/// Handles exporting and importing the workout database (and the GitHub
|
||||
/// sync token) as files on external storage, which persist across app
|
||||
/// uninstalls.
|
||||
@ -53,6 +61,8 @@ class BackupService {
|
||||
String get _backupPath => '$_baseDir/backup.json';
|
||||
String get _syncTokenPath => '$_baseDir/sync_token';
|
||||
|
||||
String get _activeSessionPath => '$_baseDir/active_session.json';
|
||||
|
||||
// ── Permission ─────────────────────────────────────────────────────────────
|
||||
|
||||
// coverage:ignore-start
|
||||
@ -130,6 +140,40 @@ class BackupService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirrors the IN-PROGRESS session (or clears it when [data] is null).
|
||||
///
|
||||
/// Best-effort like [export]. Called on every set/rep change, so a wipe of
|
||||
/// app-private storage — an uninstall, or `pm clear` — no longer costs the
|
||||
/// user the workout they are standing in the middle of.
|
||||
Future<void> exportActiveSession(Map<String, dynamic>? data) async {
|
||||
try {
|
||||
final f = File(_activeSessionPath);
|
||||
if (data == null) {
|
||||
if (f.existsSync()) await f.delete();
|
||||
return;
|
||||
}
|
||||
final dir = Directory(_baseDir);
|
||||
if (!dir.existsSync()) {
|
||||
dir.createSync(recursive: true);
|
||||
}
|
||||
await f.writeAsString(jsonEncode(data));
|
||||
} on Exception {
|
||||
// Backup is best-effort; never throw mid-workout.
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the mirrored in-progress session, or null if none / unreadable.
|
||||
Future<Map<String, dynamic>?> readActiveSession() async {
|
||||
try {
|
||||
final f = File(_activeSessionPath);
|
||||
if (!f.existsSync()) return null;
|
||||
final decoded = jsonDecode(await f.readAsString());
|
||||
return decoded is Map<String, dynamic> ? decoded : null;
|
||||
} on Exception {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the mirrored sync token, or null if none exists / unreadable.
|
||||
Future<String?> readSyncToken() async {
|
||||
try {
|
||||
|
||||
@ -223,24 +223,46 @@ class StorageService {
|
||||
// ── Active session (crash / exit recovery) ─────────────────────────────────
|
||||
|
||||
/// Persists [data] as the currently active (in-progress) session.
|
||||
///
|
||||
/// Also mirrored to external storage: this table is app-private, so an
|
||||
/// uninstall or `pm clear` wipes it and the user loses the set they are
|
||||
/// standing on. The mirror survives both.
|
||||
Future<void> saveActiveSession(Map<String, dynamic> data) async {
|
||||
await _db.insert(
|
||||
'active_session',
|
||||
{'id': 1, 'json': jsonEncode(data)},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
unawaited(BackupService.instance.exportActiveSession(data));
|
||||
}
|
||||
|
||||
/// Returns the saved active session, or null if none exists.
|
||||
///
|
||||
/// Falls back to the external mirror (re-seeding the table from it) when the
|
||||
/// table is empty — which is exactly the state right after an app-data wipe,
|
||||
/// so the workout resumes on the same set and rep instead of vanishing.
|
||||
Future<Map<String, dynamic>?> loadActiveSession() async {
|
||||
final rows = await _db.query('active_session', where: 'id = 1');
|
||||
if (rows.isEmpty) return null;
|
||||
return jsonDecode(rows.first['json']! as String) as Map<String, dynamic>;
|
||||
if (rows.isNotEmpty) {
|
||||
return jsonDecode(rows.first['json']! as String) as Map<String, dynamic>;
|
||||
}
|
||||
final mirrored = await BackupService.instance.readActiveSession();
|
||||
if (mirrored == null) return null;
|
||||
await _db.insert(
|
||||
'active_session',
|
||||
{'id': 1, 'json': jsonEncode(mirrored)},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
return mirrored;
|
||||
}
|
||||
|
||||
/// Removes the active session record (called after a session is committed).
|
||||
///
|
||||
/// Clears the external mirror too, so a finished workout cannot be
|
||||
/// resurrected by the next [loadActiveSession].
|
||||
Future<void> clearActiveSession() async {
|
||||
await _db.delete('active_session', where: 'id = 1');
|
||||
await BackupService.instance.exportActiveSession(null);
|
||||
}
|
||||
|
||||
// ── Exercise state ─────────────────────────────────────────────────────────
|
||||
|
||||
@ -101,4 +101,37 @@ void main() {
|
||||
asDir.createSync();
|
||||
expect(await BackupService.instance.readSyncToken(), isNull);
|
||||
});
|
||||
|
||||
test('exportActiveSession then readActiveSession round-trips', () async {
|
||||
await BackupService.instance.exportActiveSession({
|
||||
'workoutType': 'B',
|
||||
'doneReps': [
|
||||
[5, 4],
|
||||
],
|
||||
});
|
||||
final got = await BackupService.instance.readActiveSession();
|
||||
expect(got!['workoutType'], 'B');
|
||||
expect((got['doneReps'] as List).first, [5, 4]);
|
||||
});
|
||||
|
||||
test('readActiveSession returns null when nothing was exported', () async {
|
||||
expect(await BackupService.instance.readActiveSession(), isNull);
|
||||
});
|
||||
|
||||
test('exportActiveSession(null) deletes the mirror', () async {
|
||||
await BackupService.instance.exportActiveSession({'workoutType': 'A'});
|
||||
await BackupService.instance.exportActiveSession(null);
|
||||
expect(await BackupService.instance.readActiveSession(), isNull);
|
||||
});
|
||||
|
||||
test('a corrupt mirror is ignored, not thrown', () async {
|
||||
// A truncated write (battery death mid-set) must not brick the resume.
|
||||
File('${tempDir.path}/active_session.json').writeAsStringSync('{not json');
|
||||
expect(await BackupService.instance.readActiveSession(), isNull);
|
||||
});
|
||||
|
||||
test('a non-object mirror is ignored', () async {
|
||||
File('${tempDir.path}/active_session.json').writeAsStringSync('[1,2]');
|
||||
expect(await BackupService.instance.readActiveSession(), isNull);
|
||||
});
|
||||
}
|
||||
|
||||
@ -53,6 +53,59 @@ void main() {
|
||||
expect(loaded!['workoutType'], 'A');
|
||||
});
|
||||
|
||||
test('survives a full app-data wipe via the external mirror', () async {
|
||||
// Regression: `pm clear` (or an uninstall) wipes app-private SQLite,
|
||||
// which is where active_session lives — the user lost the exact set and
|
||||
// reps they were standing on mid-workout. The mirror must bring it back.
|
||||
final tmp = Directory.systemTemp.createTempSync('mw_active_wipe');
|
||||
BackupService.baseDirForTesting = tmp.path;
|
||||
addTearDown(() {
|
||||
BackupService.baseDirForTesting = kBackupDir;
|
||||
tmp.deleteSync(recursive: true);
|
||||
});
|
||||
|
||||
await _svc.saveActiveSession({
|
||||
'workoutType': 'B',
|
||||
'tapped': [
|
||||
[true, true, false],
|
||||
],
|
||||
'doneReps': [
|
||||
[5, 4, 0],
|
||||
],
|
||||
});
|
||||
// Give the unawaited mirror write a turn to land.
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
// Simulate the wipe: app-private DB gone, external mirror untouched.
|
||||
StorageService.resetForTesting();
|
||||
await StorageService.init();
|
||||
|
||||
final recovered = await _svc.loadActiveSession();
|
||||
expect(recovered, isNotNull, reason: 'the in-progress set must survive');
|
||||
expect(recovered!['workoutType'], 'B');
|
||||
expect((recovered['doneReps'] as List).first, [5, 4, 0]);
|
||||
// And it re-seeded the table, so the next read needs no mirror.
|
||||
expect(await _svc.loadActiveSession(), isNotNull);
|
||||
});
|
||||
|
||||
test('clearActiveSession also clears the mirror', () async {
|
||||
// Otherwise a finished workout would be resurrected on next launch.
|
||||
final tmp = Directory.systemTemp.createTempSync('mw_active_clear');
|
||||
BackupService.baseDirForTesting = tmp.path;
|
||||
addTearDown(() {
|
||||
BackupService.baseDirForTesting = kBackupDir;
|
||||
tmp.deleteSync(recursive: true);
|
||||
});
|
||||
|
||||
await _svc.saveActiveSession({'workoutType': 'A'});
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
await _svc.clearActiveSession();
|
||||
|
||||
StorageService.resetForTesting();
|
||||
await StorageService.init();
|
||||
expect(await _svc.loadActiveSession(), isNull);
|
||||
});
|
||||
|
||||
test('saveActiveSession replaces previous entry', () async {
|
||||
await _svc.saveActiveSession({'v': 1});
|
||||
await _svc.saveActiveSession({'v': 2});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user