LifeMate — Personal, Family & Learning Companion
docs/offline-data-rescue-options
chore/phase1-repository-cleanup
deploy/stable-web-apk
deployment-static
design/mobile-accessibility-v2
design/mobile-navigation-review
docs/child-education-access-decision
docs/offline-data-rescue-options
docs/owner-guide-and-delivery-plan
docs/phase1-policy-options
docs/public-review-live-2026-10-15
feat/aparat-learning-library
feat/child-device-safety
feat/child-identity-schema
feat/flutter-mobile-navigation
feat/learning-content-operations
feat/local-signing-preflight
feat/online-family-stage0
feat/personal-encrypted-recovery
feat/private-planner-series-api
feat/public-review-page
feat/standalone-weekly-planner
feat/weekly-planner-android
final-feature-1/iran-family-school
fix/auth-abuse-expiry-safety
fix/auth-expiry-after-lock
fix/backend-request-safety
fix/lifeguide-bootstrap-naming-ci
fix/lifeguide-pages-qa-base-preflight
fix/lifeguide-qa-pages-env-deployment
fix/local-task-persistence
fix/managed-child-session-boundary
fix/personal-jalali-dates
fix/personal-notification-controls
fix/personal-upgrade-delivery-guard
fix/sms-approval-gates
fix/study-duration-display
infra/cloudflare-neon-migration
infra/lifeguide-cloudflare-qa
infra/lifeguide-github-pages-qa
infra/lifeguide-supabase-qa
main
phase-1/foundation-completion
phase-2/product-foundation-identity
phase-3/planner-school-family-core
phase-4/ai-learning-wellbeing
phase-5/hardening-observability-release
test/android-reminder-acceptance
test/personal-notification-settings
test/personal-recovery-acceptance
test/role-entry-apk
| 1 | import 'dart:async'; |
| 2 | import 'dart:convert'; |
| 3 | |
| 4 | import 'package:http/http.dart' as http; |
| 5 | import 'package:shared_preferences/shared_preferences.dart'; |
| 6 | |
| 7 | import 'api.dart'; |
| 8 | import 'local_write_guard.dart'; |
| 9 | |
| 10 | bool isOfflineFailure(Object error) => |
| 11 | error is TimeoutException || |
| 12 | error is http.ClientException || |
| 13 | (error is ApiException && |
| 14 | error.statusCode == 0 && |
| 15 | const {'network_unavailable', 'request_timeout'}.contains(error.code)); |
| 16 | |
| 17 | /// One isolate's serialization, with native protection across Android engines. |
| 18 | class OfflineSession { |
| 19 | Future<void>? _tail; |
| 20 | bool _uncertain = false; |
| 21 | final _guard = const LocalWriteGuard(); |
| 22 | Future<void> available() async { |
| 23 | try { |
| 24 | if (!_uncertain) _uncertain = await _guard.getBlocked(); |
| 25 | } catch (_) { |
| 26 | _uncertain = true; |
| 27 | } |
| 28 | if (_uncertain) { |
| 29 | throw const ApiException(500, 'local_storage_restart_required'); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | Future<T> run<T>(Future<T> Function() operation) { |
| 34 | final previous = _tail; |
| 35 | final release = Completer<void>(); |
| 36 | _tail = release.future; |
| 37 | Future<T> execute() async { |
| 38 | if (previous != null) await previous; |
| 39 | try { |
| 40 | await available(); |
| 41 | return await operation(); |
| 42 | } finally { |
| 43 | if (identical(_tail, release.future)) _tail = null; |
| 44 | release.complete(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | return execute(); |
| 49 | } |
| 50 | |
| 51 | Future<void> write( |
| 52 | SharedPreferencesAsync prefs, String key, String raw) async { |
| 53 | try { |
| 54 | final token = await _guard.beginWrite(); |
| 55 | await prefs.setString(key, raw); |
| 56 | await _guard.completeWrite(token); |
| 57 | } catch (_) { |
| 58 | _uncertain = true; |
| 59 | throw const ApiException(500, 'local_storage_restart_required'); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /// Cache and pending queue scoped to authenticated server and user. |
| 65 | /// Shared data and permissions remain server-authoritative. |
| 66 | class OfflineStore { |
| 67 | OfflineStore.forNamespace(this.scope, {OfflineSession? session}) |
| 68 | : _session = session ?? _processSession, |
| 69 | _generation = _generations[scope] ?? 0 { |
| 70 | if (scope.isEmpty || scope.length > 4096) { |
| 71 | throw ArgumentError('Invalid cache scope'); |
| 72 | } |
| 73 | } |
| 74 | factory OfflineStore.forApi(IdentityApi api) { |
| 75 | if (api is HttpIdentityApi) { |
| 76 | final scope = api.cacheNamespace; |
| 77 | if (scope == null) { |
| 78 | throw const ApiException(401, 'authenticated_cache_required'); |
| 79 | } |
| 80 | return OfflineStore.forNamespace(scope); |
| 81 | } |
| 82 | return OfflineStore.forNamespace('injected-api:${identityHashCode(api)}'); |
| 83 | } |
| 84 | static final _processSession = OfflineSession(); |
| 85 | static final _generations = <String, int>{}; |
| 86 | final int _generation; |
| 87 | final OfflineSession _session; |
| 88 | final String scope; |
| 89 | String get _key => |
| 90 | 'lifeguide.offline.v2.${base64Url.encode(utf8.encode(scope))}'; |
| 91 | |
| 92 | /// Stop every existing handle before identity changes without deleting its |
| 93 | /// durable work. A fresh authenticated handle can reopen the same namespace. |
| 94 | static Future<void> invalidateNamespace(String scope) { |
| 95 | _generations[scope] = (_generations[scope] ?? 0) + 1; |
| 96 | return Future<void>.value(); |
| 97 | } |
| 98 | |
| 99 | static Future<void> clearNamespace(String scope) { |
| 100 | // Invalidate old stores immediately, including futures waiting for the lock. |
| 101 | _generations[scope] = (_generations[scope] ?? 0) + 1; |
| 102 | final current = OfflineStore.forNamespace(scope); |
| 103 | return current._session.run(() => current._save(current._empty())); |
| 104 | } |
| 105 | |
| 106 | void _checkGeneration() { |
| 107 | if ((_generations[scope] ?? 0) != _generation) { |
| 108 | throw const ApiException(401, 'cache_scope_closed'); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | Map<String, dynamic> _empty() => { |
| 113 | 'version': 2, |
| 114 | 'scope': scope, |
| 115 | 'caches': <String, dynamic>{}, |
| 116 | 'queue': <dynamic>[], |
| 117 | 'lastSyncAt': null, |
| 118 | 'lastAckAt': null |
| 119 | }; |
| 120 | Future<Map<String, dynamic>> _read() async { |
| 121 | _checkGeneration(); |
| 122 | final String? raw; |
| 123 | try { |
| 124 | raw = await SharedPreferencesAsync().getString(_key); |
| 125 | } catch (_) { |
| 126 | throw const ApiException(500, 'local_storage_failed'); |
| 127 | } |
| 128 | await _session.available(); |
| 129 | _checkGeneration(); |
| 130 | if (raw == null) return _empty(); |
| 131 | try { |
| 132 | final doc = jsonDecode(raw) as Map<String, dynamic>; |
| 133 | if (doc['version'] != 2 || |
| 134 | doc['scope'] != scope || |
| 135 | doc['caches'] is! Map || |
| 136 | doc['queue'] is! List) { |
| 137 | throw const FormatException(); |
| 138 | } |
| 139 | for (final entry in doc['queue'] as List) { |
| 140 | if (entry is! Map || |
| 141 | entry['id'] is! String || |
| 142 | entry['payload'] is! Map || |
| 143 | entry['entityId'] is! String) { |
| 144 | throw const FormatException(); |
| 145 | } |
| 146 | } |
| 147 | return doc; |
| 148 | } catch (_) { |
| 149 | throw const ApiException(500, 'local_data_corrupt'); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | Future<void> _save(Map<String, dynamic> doc) async { |
| 154 | _checkGeneration(); |
| 155 | final raw = jsonEncode(doc); |
| 156 | if (utf8.encode(raw).length > 2 * 1024 * 1024 || |
| 157 | (doc['queue'] as List).length > 100) { |
| 158 | throw const ApiException(413, 'offline_capacity_exceeded'); |
| 159 | } |
| 160 | await _session.write(SharedPreferencesAsync(), _key, raw); |
| 161 | } |
| 162 | |
| 163 | Future<T> _mutate<T>(T Function(Map<String, dynamic>) change) => |
| 164 | _session.run(() async { |
| 165 | final doc = await _read(); |
| 166 | final result = change(doc); |
| 167 | await _save(doc); |
| 168 | return result; |
| 169 | }); |
| 170 | Future<void> writeList(String key, List<Map<String, dynamic>> value) => |
| 171 | _mutate((doc) { |
| 172 | (doc['caches'] as Map)[key] = key == 'planner' || key == 'today' |
| 173 | ? _overlayPending(doc, value, todayOnly: key == 'today') |
| 174 | : value; |
| 175 | doc['lastSyncAt'] = DateTime.now().toUtc().toIso8601String(); |
| 176 | }); |
| 177 | Future<List<Map<String, dynamic>>> readList(String key) => |
| 178 | _session.run(() async { |
| 179 | final doc = await _read(); |
| 180 | final list = (doc['caches'] as Map)[key] as List? ?? []; |
| 181 | return list |
| 182 | .map((item) => Map<String, dynamic>.from(item as Map)) |
| 183 | .toList(); |
| 184 | }); |
| 185 | Future<void> cacheToday(List<Map<String, dynamic>> items) => |
| 186 | writeList('today', items); |
| 187 | Future<List<Map<String, dynamic>>> readToday() => readList('today'); |
| 188 | Future<void> cachePlanner(List<Map<String, dynamic>> items) => |
| 189 | writeList('planner', items); |
| 190 | Future<List<Map<String, dynamic>>> readPlanner() => readList('planner'); |
| 191 | Future<void> cacheSchool(List<Map<String, dynamic>> items) => |
| 192 | writeList('school', items); |
| 193 | Future<List<Map<String, dynamic>>> readSchool() => readList('school'); |
| 194 | Future<List<Map<String, dynamic>>> readQueue() => |
| 195 | _session.run(() async => ((await _read())['queue'] as List) |
| 196 | .map((m) => Map<String, dynamic>.from(m as Map)) |
| 197 | .toList()); |
| 198 | Future<int> pendingCount() async => (await readQueue()).length; |
| 199 | Future<DateTime?> _timestamp(String field) => _session.run( |
| 200 | () async => DateTime.tryParse((await _read())[field] as String? ?? '')); |
| 201 | Future<DateTime?> readLastSync() => _timestamp('lastSyncAt'); |
| 202 | Future<DateTime?> readLastAck() => _timestamp('lastAckAt'); |
| 203 | Future<void> enqueue(Map<String, dynamic> mutation, |
| 204 | {Map<String, dynamic>? optimisticItem}) => |
| 205 | _mutate((doc) { |
| 206 | final id = mutation['id']; |
| 207 | if (id is! String || |
| 208 | !RegExp(r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$') |
| 209 | .hasMatch(id) || |
| 210 | mutation['entityId'] is! String || |
| 211 | mutation['payload'] is! Map) { |
| 212 | throw const ApiException(400, 'invalid_offline_mutation'); |
| 213 | } |
| 214 | final queue = doc['queue'] as List; |
| 215 | final existing = queue.where((m) => (m as Map)['id'] == id); |
| 216 | if (existing.isNotEmpty) { |
| 217 | final prior = Map<String, dynamic>.from(existing.single as Map) |
| 218 | ..remove('queueStatus') |
| 219 | ..remove('queuedAt') |
| 220 | ..remove('lastError'); |
| 221 | if (jsonEncode(prior) != jsonEncode(mutation)) { |
| 222 | throw const ApiException(409, 'mutation_id_reused'); |
| 223 | } |
| 224 | return; |
| 225 | } |
| 226 | queue.add({ |
| 227 | ...mutation, |
| 228 | 'queueStatus': 'queued', |
| 229 | 'queuedAt': DateTime.now().toUtc().toIso8601String() |
| 230 | }); |
| 231 | if (optimisticItem != null) _saveOptimistic(doc, optimisticItem); |
| 232 | }); |
| 233 | Future<void> markQueued(String id, String status, {String? error}) => |
| 234 | _mutate((doc) { |
| 235 | for (final entry in doc['queue'] as List) { |
| 236 | if ((entry as Map)['id'] == id) { |
| 237 | entry['queueStatus'] = status; |
| 238 | entry['lastError'] = error; |
| 239 | } |
| 240 | } |
| 241 | }); |
| 242 | Future<void> removeQueued(Set<String> ids) => _mutate((doc) { |
| 243 | doc['queue'] = (doc['queue'] as List) |
| 244 | .where((m) => !ids.contains((m as Map)['id'])) |
| 245 | .toList(); |
| 246 | }); |
| 247 | Future<void> acknowledge(String id, |
| 248 | {Map<String, dynamic>? item, String? acceptedAt, String? cacheKey}) => |
| 249 | _mutate((doc) { |
| 250 | doc['queue'] = (doc['queue'] as List) |
| 251 | .where((m) => (m as Map)['id'] != id) |
| 252 | .toList(); |
| 253 | doc['lastAckAt'] = |
| 254 | acceptedAt ?? DateTime.now().toUtc().toIso8601String(); |
| 255 | if (item != null) { |
| 256 | for (final key |
| 257 | in cacheKey == null ? ['planner', 'today'] : [cacheKey]) { |
| 258 | final list = (doc['caches'] as Map)[key] as List? ?? []; |
| 259 | final index = |
| 260 | list.indexWhere((x) => (x as Map)['id'] == item['id']); |
| 261 | if (index >= 0) { |
| 262 | list[index] = item; |
| 263 | } else if (key != 'today') { |
| 264 | list.add(item); |
| 265 | } |
| 266 | (doc['caches'] as Map)[key] = key == 'planner' || key == 'today' |
| 267 | ? _overlayPending( |
| 268 | doc, |
| 269 | list |
| 270 | .map((x) => Map<String, dynamic>.from(x as Map)) |
| 271 | .toList(), |
| 272 | todayOnly: key == 'today') |
| 273 | : list; |
| 274 | } |
| 275 | } |
| 276 | }); |
| 277 | void _saveOptimistic(Map<String, dynamic> doc, Map<String, dynamic> item) { |
| 278 | final list = (doc['caches'] as Map)['planner'] as List? ?? []; |
| 279 | final index = list.indexWhere((x) => (x as Map)['id'] == item['id']); |
| 280 | if (index >= 0) { |
| 281 | list[index] = item; |
| 282 | } else { |
| 283 | list.add(item); |
| 284 | } |
| 285 | (doc['caches'] as Map)['planner'] = list; |
| 286 | } |
| 287 | |
| 288 | Future<void> saveOptimisticItem(Map<String, dynamic> item) => |
| 289 | _mutate((doc) => _saveOptimistic(doc, item)); |
| 290 | List<Map<String, dynamic>> _overlayPending( |
| 291 | Map<String, dynamic> doc, List<Map<String, dynamic>> items, |
| 292 | {bool todayOnly = false}) { |
| 293 | final result = items.map((x) => Map<String, dynamic>.from(x)).toList(); |
| 294 | final prior = ((doc['caches'] as Map)['planner'] as List? ?? []) |
| 295 | .map((x) => Map<String, dynamic>.from(x as Map)); |
| 296 | for (final raw in doc['queue'] as List) { |
| 297 | final mutation = raw as Map; |
| 298 | if (mutation['entityType'] != 'plan_item' || |
| 299 | mutation['queueStatus'] == 'rejected') { |
| 300 | continue; |
| 301 | } |
| 302 | final id = mutation['entityId']; |
| 303 | final index = result.indexWhere((x) => x['id'] == id); |
| 304 | final old = prior.where((x) => x['id'] == id).firstOrNull; |
| 305 | final base = |
| 306 | index < 0 ? old ?? <String, dynamic>{'id': id} : result[index]; |
| 307 | final overlay = optimisticPlanItem(base, mutation); |
| 308 | if (todayOnly && index < 0) { |
| 309 | final date = DateTime.tryParse( |
| 310 | (overlay['due_at'] ?? overlay['starts_at'] ?? '').toString()); |
| 311 | final now = DateTime.now(); |
| 312 | if (date == null || |
| 313 | date.toLocal().year != now.year || |
| 314 | date.toLocal().month != now.month || |
| 315 | date.toLocal().day != now.day) { |
| 316 | continue; |
| 317 | } |
| 318 | } |
| 319 | if (index < 0) { |
| 320 | result.add(overlay); |
| 321 | } else { |
| 322 | result[index] = overlay; |
| 323 | } |
| 324 | } |
| 325 | return result; |
| 326 | } |
| 327 | |
| 328 | Future<void> clear() => clearNamespace(scope); |
| 329 | |
| 330 | Future<List<Map<String, dynamic>>> readDiscardedChanges() => |
| 331 | _session.run(() async { |
| 332 | final journal = (await _read())['discardedChanges']; |
| 333 | if (journal == null) return []; |
| 334 | if (journal is! List || |
| 335 | journal.any((m) => m is! Map || m['payload'] is! Map)) { |
| 336 | throw const ApiException(500, 'local_data_corrupt'); |
| 337 | } |
| 338 | return journal.map((m) => Map<String, dynamic>.from(m as Map)).toList(); |
| 339 | }); |
| 340 | |
| 341 | Future<void> discardEntityChanges(String entityId, |
| 342 | {Map<String, dynamic>? serverItem, |
| 343 | String? cacheKey, |
| 344 | String? entityType}) => |
| 345 | _mutate((doc) { |
| 346 | if (serverItem != null && |
| 347 | (serverItem['id'] != entityId || |
| 348 | int.tryParse(serverItem['version'].toString()) == null)) { |
| 349 | throw const ApiException(400, 'invalid_server_item'); |
| 350 | } |
| 351 | final rawJournal = doc['discardedChanges']; |
| 352 | if (rawJournal != null && rawJournal is! List) { |
| 353 | throw const ApiException(500, 'local_data_corrupt'); |
| 354 | } |
| 355 | final queue = doc['queue'] as List; |
| 356 | bool matches(dynamic raw) => |
| 357 | (raw as Map)['entityId'] == entityId && |
| 358 | (entityType == null || raw['entityType'] == entityType); |
| 359 | final removed = queue.where(matches).toList(); |
| 360 | if (removed.isEmpty) return; |
| 361 | final title = removed.reversed |
| 362 | .map((m) => (m as Map)['payload'] as Map) |
| 363 | .map((p) => p['title']) |
| 364 | .whereType<String>() |
| 365 | .firstOrNull; |
| 366 | final discardedAt = DateTime.now().toUtc().toIso8601String(); |
| 367 | doc['discardedChanges'] = [ |
| 368 | ...?rawJournal as List?, |
| 369 | for (final mutation in removed) |
| 370 | { |
| 371 | ...mutation as Map, |
| 372 | 'discardedAt': discardedAt, |
| 373 | 'recoveryTitle': title |
| 374 | } |
| 375 | ]; |
| 376 | doc['queue'] = queue.where((m) => !matches(m)).toList(); |
| 377 | for (final key |
| 378 | in cacheKey == null ? ['planner', 'today'] : [cacheKey]) { |
| 379 | final list = (doc['caches'] as Map)[key] as List? ?? []; |
| 380 | final hadItem = list.any((m) => (m as Map)['id'] == entityId); |
| 381 | final replacement = |
| 382 | list.where((m) => (m as Map)['id'] != entityId).toList(); |
| 383 | if (serverItem != null && (key != 'today' || hadItem)) { |
| 384 | replacement.add(Map<String, dynamic>.from(serverItem)); |
| 385 | } |
| 386 | (doc['caches'] as Map)[key] = replacement; |
| 387 | } |
| 388 | }); |
| 389 | } |
| 390 | |
| 391 | Map<String, dynamic> optimisticPlanItem( |
| 392 | Map<String, dynamic> base, Map mutation) { |
| 393 | final payload = Map<String, dynamic>.from(mutation['payload'] as Map); |
| 394 | const columns = { |
| 395 | 'subjectId': 'subject_id', |
| 396 | 'durationMinutes': 'duration_minutes', |
| 397 | 'gradePoints': 'grade_points', |
| 398 | 'gradeOutOf': 'grade_out_of', |
| 399 | 'parentItemId': 'parent_item_id', |
| 400 | 'dueAt': 'due_at', |
| 401 | 'startsAt': 'starts_at', |
| 402 | 'endsAt': 'ends_at', |
| 403 | 'familyId': 'family_id', |
| 404 | 'schoolSubjectId': 'school_subject_id', |
| 405 | 'plannedDurationSeconds': 'planned_duration_seconds' |
| 406 | }; |
| 407 | final expected = int.tryParse(mutation['expectedVersion'].toString()) ?? 0; |
| 408 | return { |
| 409 | ...base, |
| 410 | for (final entry in payload.entries) |
| 411 | columns[entry.key] ?? entry.key: entry.value, |
| 412 | 'version': mutation['operation'] == 'create' ? 1 : expected + 1, |
| 413 | 'pending_sync': true, |
| 414 | 'acknowledged': false, |
| 415 | 'sync_conflict': mutation['queueStatus'] == 'conflict' |
| 416 | }; |
| 417 | } |