LifeMate — Personal, Family & Learning Companion

docs/owner-guide-and-delivery-plan
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
dart 365 lines 12.7 KB
Raw
1 import 'dart:async';
2
3 import 'package:flutter/foundation.dart';
4 import 'package:flutter/services.dart';
5 import 'package:flutter/widgets.dart' show StringCharacters;
6 import 'package:shared_preferences/shared_preferences.dart';
7
8 /// A committed record from this device's personal planner, never a server ACK.
9 final class LocalPersonalReminder {
10 const LocalPersonalReminder(
11 {required this.id,
12 required this.planItemId,
13 required this.profileId,
14 required this.scheduledAt,
15 this.completed = false,
16 this.archived = false});
17 final String id, planItemId, profileId;
18 final DateTime scheduledAt;
19 final bool completed, archived;
20 }
21
22 final class StandaloneReminderStatus {
23 const StandaloneReminderStatus(
24 {required this.supported,
25 required this.permissionGranted,
26 required this.active,
27 required this.scheduledCount,
28 this.enabled = false,
29 this.timing = 'approximate',
30 this.activeScope,
31 this.validUntil,
32 this.exactAlarmSupported = false,
33 this.canScheduleExactAlarms = false,
34 this.eligibleCount = 0,
35 this.selectedCount = 0});
36 final bool supported, permissionGranted, active, enabled;
37 final bool exactAlarmSupported, canScheduleExactAlarms;
38 final int scheduledCount, eligibleCount, selectedCount;
39 final String timing;
40 final String? activeScope;
41 final DateTime? validUntil;
42 static const coverageDays = 28;
43 static const maximumReminders = 128;
44 }
45
46 /// Dedicated device edition port. Opening/reconciling never grants consent or
47 /// requests permission. Only [enable] can turn the two persisted choices ON.
48 final class StandaloneReminderPort {
49 StandaloneReminderPort(
50 {MethodChannel? channel,
51 SharedPreferencesAsync? preferences,
52 DateTime Function()? now})
53 : _channel = channel ??
54 const MethodChannel('lifeguide/device_planner_reminders'),
55 _preferences = preferences ?? SharedPreferencesAsync(),
56 _now = now ?? DateTime.now;
57
58 final MethodChannel _channel;
59 final SharedPreferencesAsync _preferences;
60 final DateTime Function() _now;
61 Future<void>? _tail;
62 int _generation = 0;
63 String? _profileId;
64 int _eligibleCount = 0, _selectedCount = 0;
65 static final _uuid = RegExp(
66 r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$');
67 static final _controls =
68 RegExp(r'[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]');
69 static const _unsupported = StandaloneReminderStatus(
70 supported: false,
71 permissionGranted: false,
72 active: false,
73 scheduledCount: 0);
74 bool get _native =>
75 !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
76 String _scope(String id) {
77 if (!_uuid.hasMatch(id)) throw ArgumentError('Invalid local profile ID.');
78 return 'device-planner:v1:$id';
79 }
80
81 String _key(String id) {
82 _scope(id);
83 return 'lifeguide.device_planner.reminders_enabled.v1.$id';
84 }
85
86 Future<T> _serial<T>(Future<T> Function() work) async {
87 final previous = _tail;
88 final release = Completer<void>();
89 _tail = release.future;
90 if (previous != null) await previous;
91 try {
92 return await work();
93 } finally {
94 if (identical(_tail, release.future)) _tail = null;
95 release.complete();
96 }
97 }
98
99 Future<void> _write(String method, [Map<String, Object>? args]) async {
100 if (!_native) return;
101 final result = await _channel
102 .invokeMethod<dynamic>(method, args)
103 .timeout(const Duration(seconds: 5));
104 if (result is Map && result['supported'] == false) {
105 throw UnsupportedError('Device planner reminders are unavailable.');
106 }
107 if (result != true) throw StateError('Device reminder operation failed.');
108 }
109
110 Future<void> _deactivate() async {
111 try {
112 await _write('deactivate');
113 } on MissingPluginException {
114 /* No native alarms exist in older builds. */
115 } on UnsupportedError {/* The online edition cannot own these alarms. */}
116 }
117
118 Future<StandaloneReminderStatus> _nativeStatus(
119 [String method = 'status']) async {
120 if (!_native) return _unsupported;
121 try {
122 final raw = await _channel
123 .invokeMapMethod<String, dynamic>(method)
124 .timeout(Duration(seconds: method == 'requestPermission' ? 90 : 5));
125 if (raw == null || raw['supported'] == false) return _unsupported;
126 if (raw['supported'] != true ||
127 raw['enabled'] is! bool ||
128 raw['permissionGranted'] is! bool ||
129 raw['active'] is! bool ||
130 raw['scheduledCount'] is! int ||
131 (raw['scheduledCount'] as int) < 0 ||
132 (raw['scheduledCount'] as int) > 128 ||
133 !['exact', 'approximate'].contains(raw['timing'])) {
134 throw StateError('Invalid device reminder status.');
135 }
136 return StandaloneReminderStatus(
137 supported: true,
138 enabled: raw['enabled'] == true,
139 permissionGranted: raw['permissionGranted'] == true,
140 active: raw['active'] == true,
141 scheduledCount: raw['scheduledCount'] as int,
142 timing: raw['timing'] as String,
143 activeScope: raw['activeScope'] is String
144 ? raw['activeScope'] as String
145 : null,
146 validUntil: raw['validUntilEpochMs'] is int
147 ? DateTime.fromMillisecondsSinceEpoch(
148 raw['validUntilEpochMs'] as int,
149 isUtc: true)
150 : null,
151 exactAlarmSupported: raw['exactAlarmSupported'] == true,
152 canScheduleExactAlarms: raw['canScheduleExactAlarms'] == true);
153 } on MissingPluginException {
154 return _unsupported;
155 }
156 }
157
158 StandaloneReminderStatus _view(StandaloneReminderStatus raw, bool enabled) =>
159 StandaloneReminderStatus(
160 supported: raw.supported,
161 enabled: enabled && raw.enabled,
162 permissionGranted: raw.permissionGranted,
163 active: raw.active,
164 scheduledCount: raw.scheduledCount,
165 timing: raw.timing,
166 activeScope: raw.activeScope,
167 validUntil: raw.validUntil,
168 exactAlarmSupported: raw.exactAlarmSupported,
169 canScheduleExactAlarms: raw.canScheduleExactAlarms,
170 eligibleCount: _eligibleCount,
171 selectedCount: _selectedCount);
172 Future<StandaloneReminderStatus> _readStatus(String? id,
173 [String method = 'status']) async {
174 final raw = await _nativeStatus(method);
175 final enabled = id != null && await _preferences.getBool(_key(id)) == true;
176 return _view(raw, enabled);
177 }
178
179 Future<StandaloneReminderStatus> status({String? profileId}) {
180 if (profileId != null) {
181 _scope(profileId);
182 _profileId = profileId;
183 }
184 return _serial(() => _readStatus(profileId ?? _profileId));
185 }
186
187 Future<StandaloneReminderStatus> requestPermission() =>
188 _serial(() => _readStatus(_profileId, 'requestPermission'));
189 Future<StandaloneReminderStatus> requestExactAlarmAccess() =>
190 _serial(() => _readStatus(_profileId, 'requestExactAlarmAccess'));
191
192 List<Map<String, Object>> _select(
193 List<LocalPersonalReminder> rows, String name, String profileId) {
194 _scope(profileId);
195 final trimmed = name.trim();
196 if (trimmed.isEmpty ||
197 name.length > 4096 ||
198 name.characters.length > 40 ||
199 _controls.hasMatch(name)) {
200 throw ArgumentError('Invalid companion name.');
201 }
202 final now = _now().toUtc();
203 final through = now.add(const Duration(days: 28));
204 final ids = <String>{}, eligible = <LocalPersonalReminder>[];
205 for (final row in rows) {
206 if (!_uuid.hasMatch(row.id) ||
207 !_uuid.hasMatch(row.planItemId) ||
208 !ids.add(row.id) ||
209 row.profileId != profileId ||
210 !row.scheduledAt.isUtc) {
211 throw ArgumentError(
212 'Only committed records of this local profile may schedule.');
213 }
214 if (!row.completed &&
215 !row.archived &&
216 row.scheduledAt.isAfter(now) &&
217 !row.scheduledAt.isAfter(through)) {
218 eligible.add(row);
219 }
220 }
221 eligible.sort((a, b) {
222 final time = a.scheduledAt.compareTo(b.scheduledAt);
223 return time != 0 ? time : a.id.compareTo(b.id);
224 });
225 _eligibleCount = eligible.length;
226 final selected = eligible.take(128).toList();
227 _selectedCount = selected.length;
228 return selected
229 .map((row) => <String, Object>{
230 'id': row.id,
231 'planItemId': row.planItemId,
232 'scheduledAtEpochMs': row.scheduledAt.millisecondsSinceEpoch,
233 'companionName': trimmed
234 })
235 .toList();
236 }
237
238 Future<void> _schedule(List<Map<String, Object>> payload, String profileId,
239 int generation) async {
240 if (generation != _generation) return;
241 await _deactivate();
242 if (generation != _generation) return;
243 await _write('activate', {
244 'scope': _scope(profileId),
245 'validUntilEpochMs':
246 _now().toUtc().add(const Duration(days: 31)).millisecondsSinceEpoch
247 });
248 if (generation != _generation) return;
249 await _write('replace', {'scope': _scope(profileId), 'reminders': payload});
250 }
251
252 Future<StandaloneReminderStatus> enable(List<LocalPersonalReminder> rows,
253 {required String companionName, required String profileId}) {
254 final payload = _select(rows, companionName, profileId);
255 _profileId = profileId;
256 final generation = ++_generation;
257 return _serial(() async {
258 if (generation != _generation) return _readStatus(profileId);
259 final initial = await _nativeStatus('requestPermission');
260 if (!initial.supported ||
261 !initial.permissionGranted ||
262 generation != _generation) {
263 return _view(initial, false);
264 }
265 try {
266 await _write('setEnabled', {'enabled': true});
267 if (generation != _generation) return await _readStatus(profileId);
268 await _preferences.setBool(_key(profileId), true);
269 await _schedule(payload, profileId, generation);
270 } catch (error, stack) {
271 try {
272 await _write('setEnabled', {'enabled': false});
273 } catch (_) {
274 await _deactivate();
275 }
276 try {
277 await _preferences.setBool(_key(profileId), false);
278 } catch (_) {/* Surface the original failure. */}
279 Error.throwWithStackTrace(error, stack);
280 }
281 return _readStatus(profileId);
282 });
283 }
284
285 /// Call only with a fresh, successful read of the committed local store.
286 Future<StandaloneReminderStatus> reconcile(List<LocalPersonalReminder> rows,
287 {required String companionName, required String profileId}) {
288 _scope(profileId);
289 _profileId = profileId;
290 final generation = ++_generation;
291 return _serial(() async {
292 final raw = await _nativeStatus();
293 final optedIn = await _preferences.getBool(_key(profileId)) == true;
294 if (generation != _generation) return _view(raw, optedIn);
295 if (!raw.supported) return _unsupported;
296 if (!optedIn || !raw.enabled) {
297 _eligibleCount = 0;
298 _selectedCount = 0;
299 if (!optedIn && raw.enabled) {
300 await _write('setEnabled', {'enabled': false});
301 } else {
302 await _deactivate();
303 }
304 return _readStatus(profileId);
305 }
306 try {
307 final payload = _select(rows, companionName, profileId);
308 await _schedule(payload, profileId, generation);
309 } catch (error, stack) {
310 await _deactivate();
311 Error.throwWithStackTrace(error, stack);
312 }
313 return _readStatus(profileId);
314 });
315 }
316
317 /// Invalidate queued work before a store write. Consent survives suspension;
318 /// only a fresh committed-store reconciliation can install alarms again.
319 Future<void> suspendUntilReconcile({String? profileId}) {
320 if (profileId != null) {
321 _scope(profileId);
322 _profileId = profileId;
323 }
324 ++_generation;
325 _selectedCount = 0;
326 return _serial(_deactivate);
327 }
328
329 Future<void> cancelOnStorageFailure({String? profileId}) =>
330 suspendUntilReconcile(profileId: profileId);
331
332 Future<void> disable({required String profileId}) {
333 _scope(profileId);
334 _profileId = profileId;
335 ++_generation;
336 _eligibleCount = 0;
337 _selectedCount = 0;
338 return _serial(() async {
339 Object? failure;
340 StackTrace? trace;
341 try {
342 await _write('setEnabled', {'enabled': false});
343 } on MissingPluginException {
344 /* Unsupported older build. */
345 } on UnsupportedError {/* Online edition. */} catch (error, stack) {
346 failure = error;
347 trace = stack;
348 }
349 // Cancellation is attempted independently of either preference write.
350 try {
351 await _deactivate();
352 } catch (error, stack) {
353 failure ??= error;
354 trace ??= stack;
355 }
356 try {
357 await _preferences.setBool(_key(profileId), false);
358 } catch (error, stack) {
359 failure ??= error;
360 trace ??= stack;
361 }
362 if (failure != null) Error.throwWithStackTrace(failure, trace!);
363 });
364 }
365 }