LifeMate — Personal, Family & Learning Companion
feat(android): add scoped device reminder alarms and permission port
Quinn White committed
Oct 18, 2026 at 17:28 UTC
65bb8102d350e9ea5f1612af4d467fe4ed8507d9
5 files changed
+728
apps/lifemate/android/app/src/main/AndroidManifest.xml
+12
@@ -1,5 +1,8 @@
1
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
<uses-permission android:name="android.permission.INTERNET"/>
3
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
4
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
5
+ <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
6
<application
7
android:label="لایفگاید"
8
android:allowBackup="false"
@@ -28,6 +31,15 @@
31
<category android:name="android.intent.category.LAUNCHER"/>
32
</intent-filter>
33
</activity>
34
+ <receiver android:name=".LocalReminderReceiver" android:exported="false">
35
+ <intent-filter>
36
+ <action android:name="android.intent.action.BOOT_COMPLETED"/>
37
+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
38
+ <action android:name="android.intent.action.TIME_SET"/>
39
+ <action android:name="android.intent.action.TIMEZONE_CHANGED"/>
40
+ <action android:name="android.app.action.SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED"/>
41
+ </intent-filter>
42
+ </receiver>
43
<!-- Don't delete the meta-data below.
44
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
45
<meta-data
apps/lifemate/android/app/src/main/kotlin/ir/lifeguide/app/LocalReminders.kt
new
+273
@@ -0,0 +1,273 @@
1
+package ir.lifeguide.app
2
+
3
+import android.Manifest
4
+import android.app.Activity
5
+import android.app.AlarmManager
6
+import android.app.Notification
7
+import android.app.NotificationChannel
8
+import android.app.NotificationManager
9
+import android.app.PendingIntent
10
+import android.content.BroadcastReceiver
11
+import android.content.Context
12
+import android.content.Intent
13
+import android.content.pm.PackageManager
14
+import android.net.Uri
15
+import android.os.Build
16
+import android.provider.Settings
17
+import io.flutter.plugin.common.MethodCall
18
+import io.flutter.plugin.common.MethodChannel
19
+import org.json.JSONArray
20
+import org.json.JSONObject
21
+import java.util.UUID
22
+
23
+/** Device-only generic reminders. Never persist task text, credentials or tokens here. */
24
+internal object LocalReminders {
25
+ private const val PREFS = "lifeguide_local_reminders_v1"
26
+ private const val KEY = "active"
27
+ private const val CHANNEL = "lifeguide_personal_plan_v1"
28
+ private const val ACTION = "ir.lifeguide.app.LOCAL_REMINDER"
29
+ private const val MAX_LEASE = 24L * 60 * 60 * 1000
30
+ private val uuid = Regex("^[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}$")
31
+ private val controls = Regex("[\\p{Cc}\\u202a-\\u202e\\u2066-\\u2069]")
32
+ private var failedClosed = false
33
+ private fun prefs(c: Context) = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
34
+ private fun alarms(c: Context) = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
35
+ private fun notifications(c: Context) = c.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
36
+ private fun read(c: Context): JSONObject? {
37
+ if (failedClosed) return null
38
+ val raw = prefs(c).getString(KEY, null) ?: return null
39
+ return try { JSONObject(raw) } catch (_: Exception) { failedClosed = true; notifications(c).cancelAll(); null }
40
+ }
41
+ private fun store(c: Context, state: JSONObject) {
42
+ if (!prefs(c).edit().putString(KEY, state.toString()).commit()) {
43
+ failedClosed = true
44
+ throw IllegalStateException("Local reminder storage unavailable")
45
+ }
46
+ failedClosed = false
47
+ }
48
+ private fun leased(s: JSONObject, now: Long = System.currentTimeMillis()) =
49
+ s.optString("scope").isNotEmpty() && s.optString("generation").isNotEmpty() &&
50
+ s.optLong("issuedAtEpochMs") <= now && s.optLong("validUntilEpochMs") > now &&
51
+ s.optLong("validUntilEpochMs") - s.optLong("issuedAtEpochMs") in 1..MAX_LEASE
52
+ fun permission(c: Context) =
53
+ (Build.VERSION.SDK_INT < 33 || c.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) &&
54
+ notifications(c).areNotificationsEnabled() &&
55
+ (Build.VERSION.SDK_INT < 26 || notifications(c).getNotificationChannel(CHANNEL)?.importance != NotificationManager.IMPORTANCE_NONE)
56
+ fun exact(c: Context) = Build.VERSION.SDK_INT < 31 || alarms(c).canScheduleExactAlarms()
57
+ private fun channel(c: Context) {
58
+ if (Build.VERSION.SDK_INT >= 26) notifications(c).createNotificationChannel(
59
+ NotificationChannel(CHANNEL, "یادآوری برنامهٔ شخصی", NotificationManager.IMPORTANCE_HIGH).apply {
60
+ description = "زمان اعلان به مجوز، باتری و تنظیمات دستگاه وابسته است."
61
+ lockscreenVisibility = Notification.VISIBILITY_PRIVATE
62
+ enableVibration(true)
63
+ setSound(Settings.System.DEFAULT_NOTIFICATION_URI, null)
64
+ })
65
+ }
66
+ private fun pending(c: Context, generation: String, id: String) = PendingIntent.getBroadcast(c, 0,
67
+ Intent(c, LocalReminderReceiver::class.java).apply {
68
+ action = ACTION
69
+ data = Uri.Builder().scheme("lifeguide-reminder").authority("alarm").appendPath(generation).appendPath(id).build()
70
+ }, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
71
+ private fun cancelOne(c: Context, generation: String, id: String) {
72
+ val alarm = pending(c, generation, id)
73
+ alarms(c).cancel(alarm)
74
+ alarm.cancel()
75
+ notifications(c).cancel("lifeguide-plan:$id", 1)
76
+ }
77
+ private fun cancel(c: Context, s: JSONObject?) {
78
+ if (s != null) {
79
+ val rows = s.optJSONArray("reminders") ?: JSONArray()
80
+ for (i in 0 until rows.length()) rows.optJSONObject(i)?.let { cancelOne(c, s.optString("generation"), it.optString("id")) }
81
+ cancelOne(c, s.optString("generation"), "expiry")
82
+ }
83
+ notifications(c).cancelAll()
84
+ }
85
+ @Synchronized fun deactivate(c: Context) {
86
+ val old = read(c)
87
+ failedClosed = true
88
+ cancel(c, old)
89
+ if (!prefs(c).edit().remove(KEY).commit()) throw IllegalStateException("Local reminders could not be cleared")
90
+ failedClosed = false
91
+ }
92
+ private fun expire(c: Context, s: JSONObject) {
93
+ if (s.optBoolean("deliveryExpired")) return
94
+ cancel(c, s)
95
+ store(c, JSONObject(s.toString()).put("generation", UUID.randomUUID().toString()).put("deliveryExpired", true).put("reminders", JSONArray()))
96
+ }
97
+ @Synchronized fun activate(c: Context, args: Map<*, *>) {
98
+ val scope = args["scope"] as? String ?: throw IllegalArgumentException()
99
+ val until = (args["validUntilEpochMs"] as? Number)?.toLong() ?: throw IllegalArgumentException()
100
+ val now = System.currentTimeMillis()
101
+ require(scope.isNotEmpty() && scope.length <= 1024 && !controls.containsMatchIn(scope))
102
+ require(until > now && until - now <= MAX_LEASE)
103
+ val old = read(c)
104
+ val rows = if (old != null && old.optString("scope") == scope && leased(old, now)) old.optJSONArray("reminders") ?: JSONArray() else JSONArray()
105
+ val next = JSONObject().put("scope", scope).put("generation", UUID.randomUUID().toString()).put("issuedAtEpochMs", now)
106
+ .put("validUntilEpochMs", until).put("reminders", rows)
107
+ cancel(c, old)
108
+ try { store(c, next); schedule(c, next) } catch (error: Exception) { deactivate(c); throw error }
109
+ }
110
+ @Synchronized fun replace(c: Context, args: Map<*, *>) {
111
+ val old = read(c) ?: throw IllegalStateException("No reminder scope")
112
+ require(old.optString("scope") == args["scope"] && leased(old))
113
+ val raw = args["reminders"] as? List<*> ?: throw IllegalArgumentException()
114
+ require(raw.size <= 128)
115
+ val ids = mutableSetOf<String>()
116
+ val rows = JSONArray()
117
+ val now = System.currentTimeMillis()
118
+ for (rawRow in raw) {
119
+ val row = rawRow as? Map<*, *> ?: throw IllegalArgumentException()
120
+ val id = row["id"] as? String ?: throw IllegalArgumentException()
121
+ val plan = row["planItemId"] as? String ?: throw IllegalArgumentException()
122
+ val at = (row["scheduledAtEpochMs"] as? Number)?.toLong() ?: throw IllegalArgumentException()
123
+ val name = (row["companionName"] as? String)?.trim() ?: throw IllegalArgumentException()
124
+ require(uuid.matches(id) && uuid.matches(plan) && ids.add(id))
125
+ // Dart validates <=40 graphemes; UTF-16 bound defends this native boundary.
126
+ require(name.isNotEmpty() && name.length <= 4096 && !controls.containsMatchIn(name))
127
+ require(row.keys.all { it in setOf("id", "planItemId", "scheduledAtEpochMs", "companionName") })
128
+ if (at <= now || at > old.getLong("validUntilEpochMs")) continue
129
+ rows.put(JSONObject().put("id", id).put("planItemId", plan).put("scheduledAtEpochMs", at).put("companionName", name))
130
+ }
131
+ val next = JSONObject(old.toString()).put("generation", UUID.randomUUID().toString()).put("reminders", rows)
132
+ cancel(c, old)
133
+ try { store(c, next); schedule(c, next) } catch (error: Exception) { deactivate(c); throw error }
134
+ }
135
+ @Synchronized fun suppress(c: Context, args: Map<*, *>) {
136
+ val state = read(c) ?: return
137
+ require(state.optString("scope") == args["scope"])
138
+ val ids = args["planItemIds"] as? List<*> ?: throw IllegalArgumentException()
139
+ require(ids.size <= 128 && ids.all { it is String && uuid.matches(it) })
140
+ val old = state.optJSONArray("reminders") ?: JSONArray()
141
+ val remaining = JSONArray()
142
+ val removed = mutableListOf<String>()
143
+ for (i in 0 until old.length()) {
144
+ val row = old.optJSONObject(i) ?: continue
145
+ if (ids.contains(row.optString("planItemId"))) removed.add(row.optString("id")) else remaining.put(row)
146
+ }
147
+ // Receiver sees removed IDs before any OS cancellation race.
148
+ store(c, JSONObject(state.toString()).put("reminders", remaining))
149
+ for (id in removed) cancelOne(c, state.optString("generation"), id)
150
+ }
151
+ private fun setAlarm(c: Context, at: Long, alarm: PendingIntent) {
152
+ if (exact(c)) {
153
+ try { alarms(c).setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, alarm); return }
154
+ catch (_: SecurityException) { /* Permission can be revoked between check and call. */ }
155
+ }
156
+ alarms(c).setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, alarm)
157
+ }
158
+ private fun schedule(c: Context, s: JSONObject) {
159
+ if (!leased(s) || !permission(c)) return
160
+ channel(c)
161
+ val rows = s.optJSONArray("reminders") ?: JSONArray()
162
+ val now = System.currentTimeMillis()
163
+ for (i in 0 until rows.length()) {
164
+ val row = rows.optJSONObject(i) ?: continue
165
+ val at = row.optLong("scheduledAtEpochMs")
166
+ if (at <= now || at > s.optLong("validUntilEpochMs") || row.optBoolean("delivered")) continue
167
+ setAlarm(c, at, pending(c, s.getString("generation"), row.getString("id")))
168
+ }
169
+ setAlarm(c, s.getLong("validUntilEpochMs"), pending(c, s.getString("generation"), "expiry"))
170
+ }
171
+ @Synchronized fun restore(c: Context) {
172
+ val state = read(c) ?: return
173
+ if (!leased(state) || !permission(c)) { expire(c, state); return }
174
+ schedule(c, state)
175
+ }
176
+ @Synchronized fun status(c: Context): Map<String, Any?> {
177
+ var state = read(c)
178
+ if (state != null && (!leased(state) || !permission(c))) { expire(c, state); state = read(c) }
179
+ val rows = state?.optJSONArray("reminders") ?: JSONArray()
180
+ val now = System.currentTimeMillis()
181
+ var count = 0
182
+ for (i in 0 until rows.length()) if ((rows.optJSONObject(i)?.optLong("scheduledAtEpochMs") ?: 0) > now) count++
183
+ return mapOf("supported" to true, "permissionGranted" to permission(c), "active" to (state != null), "scheduledCount" to count,
184
+ "timing" to if (exact(c)) "exact" else "approximate", "activeScope" to state?.optString("scope"),
185
+ "validUntilEpochMs" to state?.optLong("validUntilEpochMs"), "exactAlarmSupported" to (Build.VERSION.SDK_INT >= 31), "canScheduleExactAlarms" to exact(c))
186
+ }
187
+ @Synchronized fun deliver(c: Context, intent: Intent) {
188
+ if (intent.action != ACTION) return
189
+ val parts = intent.data?.pathSegments ?: return
190
+ if (parts.size != 2) return
191
+ val state = read(c) ?: return
192
+ if (parts[0] != state.optString("generation")) return
193
+ if (!leased(state) || !permission(c) || parts[1] == "expiry") { expire(c, state); return }
194
+ val rows = state.optJSONArray("reminders") ?: return
195
+ val now = System.currentTimeMillis()
196
+ for (i in 0 until rows.length()) {
197
+ val row = rows.optJSONObject(i) ?: continue
198
+ if (row.optString("id") != parts[1] || row.optBoolean("delivered")) continue
199
+ val at = row.optLong("scheduledAtEpochMs")
200
+ if (now < at || now - at > 30L * 60 * 1000) return // Drop stale alarms, never claim stale tasks are current.
201
+ row.put("delivered", true)
202
+ store(c, state)
203
+ channel(c)
204
+ // Open authenticated app home; no private route/title is carried by the tap.
205
+ val open = Intent(c, MainActivity::class.java).apply {
206
+ action = Intent.ACTION_MAIN; addCategory(Intent.CATEGORY_LAUNCHER)
207
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
208
+ data = Uri.Builder().scheme("lifeguide-reminder").authority("open").appendPath(row.getString("id")).build()
209
+ }
210
+ val tap = PendingIntent.getActivity(c, 0, open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
211
+ fun builder() = if (Build.VERSION.SDK_INT >= 26) Notification.Builder(c, CHANNEL) else Notification.Builder(c)
212
+ val text = "برای دیدن برنامهٔ شخصی، لایفگاید را باز کنید."
213
+ val notification = builder().setSmallIcon(R.drawable.lifemate_logo).setContentTitle(row.getString("companionName"))
214
+ .setContentText(text).setContentIntent(tap).setAutoCancel(true).setVisibility(Notification.VISIBILITY_PRIVATE)
215
+ .setPublicVersion(builder().setSmallIcon(R.drawable.lifemate_logo).setContentTitle("LifeGuide").setContentText(text).build())
216
+ .setCategory(Notification.CATEGORY_REMINDER).apply {
217
+ if (Build.VERSION.SDK_INT < 26) setDefaults(Notification.DEFAULT_SOUND or Notification.DEFAULT_VIBRATE)
218
+ }.build()
219
+ notifications(c).notify("lifeguide-plan:${row.getString("id")}", 1, notification)
220
+ return
221
+ }
222
+ }
223
+}
224
+
225
+class LocalReminderReceiver : BroadcastReceiver() {
226
+ override fun onReceive(context: Context, intent: Intent) {
227
+ try {
228
+ when (intent.action) {
229
+ Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED, Intent.ACTION_TIME_CHANGED,
230
+ Intent.ACTION_TIMEZONE_CHANGED, AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED -> LocalReminders.restore(context)
231
+ else -> LocalReminders.deliver(context, intent)
232
+ }
233
+ } catch (_: Exception) { try { LocalReminders.deactivate(context) } catch (_: Exception) { } }
234
+ }
235
+}
236
+
237
+internal class LocalReminderChannel(private val activity: Activity) : MethodChannel.MethodCallHandler {
238
+ companion object { const val REQUEST = 8247 }
239
+ private var permissionResult: MethodChannel.Result? = null
240
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
241
+ try {
242
+ when (call.method) {
243
+ "activate" -> { LocalReminders.activate(activity, call.arguments as? Map<*, *> ?: throw IllegalArgumentException()); result.success(true) }
244
+ "replace" -> { LocalReminders.replace(activity, call.arguments as? Map<*, *> ?: throw IllegalArgumentException()); result.success(true) }
245
+ "suppressPlanItems" -> { LocalReminders.suppress(activity, call.arguments as? Map<*, *> ?: throw IllegalArgumentException()); result.success(true) }
246
+ "deactivate" -> { LocalReminders.deactivate(activity); result.success(true) }
247
+ "status" -> result.success(LocalReminders.status(activity))
248
+ "requestPermission" -> {
249
+ if (Build.VERSION.SDK_INT >= 33 && activity.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
250
+ if (permissionResult != null) { result.error("permission_request_pending", null, null); return }
251
+ permissionResult = result
252
+ activity.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST)
253
+ } else result.success(LocalReminders.status(activity))
254
+ }
255
+ "requestExactAlarmAccess" -> {
256
+ if (Build.VERSION.SDK_INT >= 31 && !LocalReminders.exact(activity)) {
257
+ activity.startActivity(Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM, Uri.parse("package:${activity.packageName}")))
258
+ }
259
+ result.success(LocalReminders.status(activity))
260
+ }
261
+ else -> result.notImplemented()
262
+ }
263
+ } catch (_: IllegalArgumentException) { result.error("invalid_local_reminder", null, null) }
264
+ catch (_: Exception) { result.error("local_reminder_unavailable", null, null) }
265
+ }
266
+ fun onPermissionResult(requestCode: Int) {
267
+ if (requestCode != REQUEST) return
268
+ val result = permissionResult ?: return
269
+ permissionResult = null
270
+ try { result.success(LocalReminders.status(activity)) }
271
+ catch (_: Exception) { result.error("local_reminder_unavailable", null, null) }
272
+ }
273
+}
apps/lifemate/android/app/src/main/kotlin/ir/lifeguide/app/MainActivity.kt
+9
@@ -5,8 +5,17 @@ import io.flutter.embedding.engine.FlutterEngine
5
import io.flutter.plugin.common.MethodChannel
6
7
class MainActivity : FlutterActivity() {
8
+ private var localReminderChannel: LocalReminderChannel? = null
9
+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
10
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults)
11
+ localReminderChannel?.onPermissionResult(requestCode)
12
+ }
13
+
14
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
15
super.configureFlutterEngine(flutterEngine)
16
+ localReminderChannel = LocalReminderChannel(this)
17
+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "lifeguide/local_reminders")
18
+ .setMethodCallHandler(localReminderChannel)
19
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "lifeguide/local_write_guard")
20
.setMethodCallHandler { call, result ->
21
when (call.method) {
apps/lifemate/lib/local_reminders.dart
new
+247
@@ -0,0 +1,247 @@
1
+import 'dart:async';
2
+import 'package:flutter/foundation.dart';
3
+import 'package:flutter/services.dart';
4
+import 'package:flutter/widgets.dart' show StringCharacters;
5
+
6
+final androidLocalReminders = AndroidLocalReminderPort();
7
+
8
+final class LocalReminder {
9
+ const LocalReminder(
10
+ {required this.id,
11
+ required this.planItemId,
12
+ required this.scheduledAt,
13
+ required this.companionName,
14
+ required this.ownerUserId,
15
+ required this.serverAcknowledged,
16
+ this.pendingMutation = false});
17
+ final String id, planItemId, companionName, ownerUserId;
18
+ final DateTime scheduledAt;
19
+ final bool serverAcknowledged, pendingMutation;
20
+}
21
+
22
+final class LocalReminderStatus {
23
+ const LocalReminderStatus(
24
+ {required this.supported,
25
+ required this.permissionGranted,
26
+ required this.active,
27
+ required this.scheduledCount,
28
+ this.timing = 'approximate',
29
+ this.activeScope,
30
+ this.validUntil,
31
+ this.exactAlarmSupported = false,
32
+ this.canScheduleExactAlarms = false});
33
+ final bool supported,
34
+ permissionGranted,
35
+ active,
36
+ exactAlarmSupported,
37
+ canScheduleExactAlarms;
38
+ final int scheduledCount;
39
+ final String timing;
40
+ final String? activeScope;
41
+ final DateTime? validUntil;
42
+}
43
+
44
+abstract interface class LocalReminderPort {
45
+ Future<void> activate(String scope, {required DateTime validUntil});
46
+ Future<void> replace(String scope, List<LocalReminder> reminders,
47
+ {required String currentUserId});
48
+ Future<void> suppressPlanItems(String scope, Set<String> ids);
49
+ Future<void> deactivate();
50
+ Future<LocalReminderStatus> status();
51
+ Future<LocalReminderStatus> requestPermission();
52
+ Future<LocalReminderStatus> requestExactAlarmAccess();
53
+}
54
+
55
+/// One shared lifecycle boundary. Native storage contains no task text or tokens.
56
+/// [LocalReminderStatus.active] means device opt-in, even after lease expiry.
57
+final class AndroidLocalReminderPort implements LocalReminderPort {
58
+ AndroidLocalReminderPort({MethodChannel? channel, DateTime Function()? now})
59
+ : _channel = channel ?? const MethodChannel('lifeguide/local_reminders'),
60
+ _now = now ?? DateTime.now;
61
+ final MethodChannel _channel;
62
+ final DateTime Function() _now;
63
+ Future<void> _tail = Future.value();
64
+ int _generation = 0;
65
+ String? _scope;
66
+ DateTime? _validUntil;
67
+ bool get _native =>
68
+ !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
69
+ static final _uuid = RegExp(
70
+ 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}$');
71
+ static final _controls =
72
+ RegExp(r'[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]');
73
+ static const _unsupported = LocalReminderStatus(
74
+ supported: false,
75
+ permissionGranted: false,
76
+ active: false,
77
+ scheduledCount: 0);
78
+ Future<void> _serial(Future<void> Function() work) {
79
+ final result = _tail.then((_) => work());
80
+ _tail = result.then((_) {}, onError: (Object _, StackTrace __) {});
81
+ return result;
82
+ }
83
+
84
+ Future<void> _write(String method, [Map<String, Object>? arguments]) async {
85
+ if (await _channel
86
+ .invokeMethod<bool>(method, arguments)
87
+ .timeout(const Duration(seconds: 5)) !=
88
+ true) {
89
+ throw StateError('Native reminder operation failed.');
90
+ }
91
+ }
92
+
93
+ @override
94
+ Future<void> activate(String scope, {required DateTime validUntil}) async {
95
+ if (!_native) return;
96
+ final now = _now().toUtc();
97
+ if (scope.isEmpty ||
98
+ scope.length > 1024 ||
99
+ _controls.hasMatch(scope) ||
100
+ !validUntil.isUtc ||
101
+ !validUntil.isAfter(now) ||
102
+ validUntil.difference(now) > const Duration(hours: 24)) {
103
+ throw ArgumentError(
104
+ 'A future UTC lease of at most 24 hours is required.');
105
+ }
106
+ final generation = ++_generation;
107
+ _scope = scope;
108
+ _validUntil = validUntil;
109
+ await _serial(() async {
110
+ if (generation != _generation) return;
111
+ try {
112
+ await _write('activate', {
113
+ 'scope': scope,
114
+ 'validUntilEpochMs': validUntil.millisecondsSinceEpoch
115
+ });
116
+ } catch (_) {
117
+ if (generation == _generation) {
118
+ _scope = null;
119
+ _validUntil = null;
120
+ }
121
+ rethrow;
122
+ }
123
+ });
124
+ }
125
+
126
+ @override
127
+ Future<void> replace(String scope, List<LocalReminder> reminders,
128
+ {required String currentUserId}) async {
129
+ if (!_native) return;
130
+ final until = _validUntil;
131
+ if (_scope != scope || until == null || !until.isAfter(_now().toUtc())) {
132
+ throw StateError('Reminder scope or lease no longer matches.');
133
+ }
134
+ if (!_uuid.hasMatch(currentUserId) || reminders.length > 128) {
135
+ throw ArgumentError('Invalid owner or reminder count.');
136
+ }
137
+ final ids = <String>{}, payload = <Map<String, Object>>[];
138
+ final now = _now().toUtc();
139
+ for (final row in reminders) {
140
+ if (!_uuid.hasMatch(row.id) ||
141
+ !_uuid.hasMatch(row.planItemId) ||
142
+ !ids.add(row.id) ||
143
+ row.ownerUserId != currentUserId ||
144
+ !row.serverAcknowledged ||
145
+ row.pendingMutation ||
146
+ !row.scheduledAt.isUtc ||
147
+ row.companionName.trim().isEmpty ||
148
+ row.companionName.characters.length > 40 ||
149
+ row.companionName.length > 4096 ||
150
+ _controls.hasMatch(row.companionName)) {
151
+ throw ArgumentError(
152
+ 'Only acknowledged owner records may schedule reminders.');
153
+ }
154
+ if (!row.scheduledAt.isAfter(now) || row.scheduledAt.isAfter(until)) {
155
+ continue;
156
+ }
157
+ payload.add({
158
+ 'id': row.id,
159
+ 'planItemId': row.planItemId,
160
+ 'scheduledAtEpochMs': row.scheduledAt.millisecondsSinceEpoch,
161
+ 'companionName': row.companionName.trim()
162
+ });
163
+ }
164
+ final generation = _generation;
165
+ await _serial(() async {
166
+ if (generation != _generation || _scope != scope) return;
167
+ await _write('replace', {'scope': scope, 'reminders': payload});
168
+ });
169
+ }
170
+
171
+ @override
172
+ Future<void> suppressPlanItems(String scope, Set<String> ids) async {
173
+ if (!_native || ids.isEmpty) return;
174
+ if (_scope != null && _scope != scope) {
175
+ throw StateError('Reminder scope no longer matches.');
176
+ }
177
+ if (ids.length > 128 || ids.any((id) => !_uuid.hasMatch(id))) {
178
+ throw ArgumentError('Invalid plan IDs.');
179
+ }
180
+ final generation = _generation;
181
+ await _serial(() async {
182
+ if (generation != _generation) return;
183
+ try {
184
+ await _write(
185
+ 'suppressPlanItems', {'scope': scope, 'planItemIds': ids.toList()});
186
+ } on MissingPluginException {/* Older builds have no native reminders. */}
187
+ });
188
+ }
189
+
190
+ @override
191
+ Future<void> deactivate() async {
192
+ ++_generation;
193
+ _scope = null;
194
+ _validUntil = null;
195
+ if (!_native) return;
196
+ await _serial(() async {
197
+ try {
198
+ await _write('deactivate');
199
+ } on MissingPluginException {/* Older builds have no native reminders. */}
200
+ });
201
+ }
202
+
203
+ Future<LocalReminderStatus> _status(String method) async {
204
+ if (!_native) return _unsupported;
205
+ try {
206
+ final raw = await _channel
207
+ .invokeMapMethod<String, dynamic>(method)
208
+ .timeout(Duration(seconds: method == 'requestPermission' ? 90 : 5));
209
+ if (raw == null ||
210
+ raw['supported'] != true ||
211
+ raw['permissionGranted'] is! bool ||
212
+ raw['active'] is! bool ||
213
+ raw['scheduledCount'] is! int ||
214
+ (raw['scheduledCount'] as int) < 0 ||
215
+ !['exact', 'approximate'].contains(raw['timing'])) {
216
+ throw StateError('Invalid native reminder status.');
217
+ }
218
+ return LocalReminderStatus(
219
+ supported: true,
220
+ permissionGranted: raw['permissionGranted'] == true,
221
+ active: raw['active'] == true,
222
+ scheduledCount: raw['scheduledCount'] as int,
223
+ timing: raw['timing'] as String,
224
+ activeScope: raw['activeScope'] is String
225
+ ? raw['activeScope'] as String
226
+ : null,
227
+ validUntil: raw['validUntilEpochMs'] is int
228
+ ? DateTime.fromMillisecondsSinceEpoch(
229
+ raw['validUntilEpochMs'] as int,
230
+ isUtc: true)
231
+ : null,
232
+ exactAlarmSupported: raw['exactAlarmSupported'] == true,
233
+ canScheduleExactAlarms: raw['canScheduleExactAlarms'] == true);
234
+ } on MissingPluginException {
235
+ return _unsupported;
236
+ }
237
+ }
238
+
239
+ @override
240
+ Future<LocalReminderStatus> status() => _status('status');
241
+ @override
242
+ Future<LocalReminderStatus> requestPermission() =>
243
+ _status('requestPermission');
244
+ @override
245
+ Future<LocalReminderStatus> requestExactAlarmAccess() =>
246
+ _status('requestExactAlarmAccess');
247
+}
apps/lifemate/test/local_reminders_test.dart
new
+187
@@ -0,0 +1,187 @@
1
+import 'dart:async';
2
+import 'package:flutter/foundation.dart';
3
+import 'package:flutter/services.dart';
4
+import 'package:flutter_test/flutter_test.dart';
5
+import 'package:lifemate/local_reminders.dart';
6
+
7
+void main() {
8
+ TestWidgetsFlutterBinding.ensureInitialized();
9
+ const channel = MethodChannel('lifeguide/local_reminders');
10
+ const owner = '11111111-1111-4111-8111-111111111111',
11
+ item = '22222222-2222-4222-8222-222222222222';
12
+ const scope = 'https://fixture.invalid/api|$owner';
13
+ final now = DateTime.utc(2026, 10, 18, 8);
14
+ final calls = <MethodCall>[];
15
+ late AndroidLocalReminderPort port;
16
+ LocalReminder row(
17
+ {String id = item,
18
+ String ownerId = owner,
19
+ bool ack = true,
20
+ bool pending = false,
21
+ DateTime? at,
22
+ String name = 'همراه من'}) =>
23
+ LocalReminder(
24
+ id: id,
25
+ planItemId: item,
26
+ scheduledAt: at ?? now.add(const Duration(hours: 1)),
27
+ companionName: name,
28
+ ownerUserId: ownerId,
29
+ serverAcknowledged: ack,
30
+ pendingMutation: pending);
31
+ setUp(() {
32
+ debugDefaultTargetPlatformOverride = TargetPlatform.android;
33
+ calls.clear();
34
+ port = AndroidLocalReminderPort(now: () => now);
35
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
36
+ .setMockMethodCallHandler(channel, (call) async {
37
+ calls.add(call);
38
+ if (['status', 'requestPermission', 'requestExactAlarmAccess']
39
+ .contains(call.method)) {
40
+ return {
41
+ 'supported': true,
42
+ 'permissionGranted': true,
43
+ 'active': true,
44
+ 'scheduledCount': 1,
45
+ 'timing': 'exact',
46
+ 'activeScope': scope,
47
+ 'validUntilEpochMs':
48
+ now.add(const Duration(hours: 24)).millisecondsSinceEpoch,
49
+ 'exactAlarmSupported': true,
50
+ 'canScheduleExactAlarms': true
51
+ };
52
+ }
53
+ return true;
54
+ });
55
+ });
56
+ tearDown(() {
57
+ debugDefaultTargetPlatformOverride = null;
58
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
59
+ .setMockMethodCallHandler(channel, null);
60
+ });
61
+ test('foreign pending and unacknowledged records never reach native alarms',
62
+ () async {
63
+ await port.activate(scope, validUntil: now.add(const Duration(hours: 24)));
64
+ for (final unsafe in [
65
+ row(ownerId: '33333333-3333-4333-8333-333333333333'),
66
+ row(ack: false),
67
+ row(pending: true)
68
+ ]) {
69
+ await expectLater(port.replace(scope, [unsafe], currentUserId: owner),
70
+ throwsArgumentError);
71
+ }
72
+ expect(calls.map((x) => x.method), ['activate']);
73
+ });
74
+ test('scope mismatch cannot replace reminders', () async {
75
+ await port.activate(scope, validUntil: now.add(const Duration(hours: 24)));
76
+ await expectLater(
77
+ port.replace('other', [row()], currentUserId: owner), throwsStateError);
78
+ });
79
+ test('native payload excludes private task text and owner metadata',
80
+ () async {
81
+ await port.activate(scope, validUntil: now.add(const Duration(hours: 24)));
82
+ await port.replace(scope, [row()], currentUserId: owner);
83
+ expect(calls.last.arguments, {
84
+ 'scope': scope,
85
+ 'reminders': [
86
+ {
87
+ 'id': item,
88
+ 'planItemId': item,
89
+ 'scheduledAtEpochMs':
90
+ now.add(const Duration(hours: 1)).millisecondsSinceEpoch,
91
+ 'companionName': 'همراه من'
92
+ }
93
+ ]
94
+ });
95
+ });
96
+ test('past and beyond-lease records are dropped', () async {
97
+ await port.activate(scope, validUntil: now.add(const Duration(hours: 24)));
98
+ await port.replace(
99
+ scope,
100
+ [
101
+ row(at: now.subtract(const Duration(seconds: 1))),
102
+ row(
103
+ id: '44444444-4444-4444-8444-444444444444',
104
+ at: now.add(const Duration(hours: 25)))
105
+ ],
106
+ currentUserId: owner);
107
+ expect((calls.last.arguments as Map)['reminders'], isEmpty);
108
+ });
109
+ test('lease duplicates and control characters fail closed', () async {
110
+ await expectLater(
111
+ port.activate(scope, validUntil: now.add(const Duration(hours: 25))),
112
+ throwsArgumentError);
113
+ await port.activate(scope, validUntil: now.add(const Duration(hours: 24)));
114
+ await expectLater(port.replace(scope, [row(), row()], currentUserId: owner),
115
+ throwsArgumentError);
116
+ await expectLater(
117
+ port.replace(scope, [row(name: 'bad\nname')], currentUserId: owner),
118
+ throwsArgumentError);
119
+ });
120
+ test('forty joined emoji fit nickname limit but forty-one do not', () async {
121
+ await port.activate(scope, validUntil: now.add(const Duration(hours: 24)));
122
+ final name = List.filled(40, '👩🔬').join();
123
+ await port.replace(scope, [row(name: name)], currentUserId: owner);
124
+ await expectLater(
125
+ port.replace(scope, [row(name: '$name!')], currentUserId: owner),
126
+ throwsArgumentError);
127
+ });
128
+ test('logout invalidates queued replacement before channel call', () async {
129
+ final entered = Completer<void>(), release = Completer<void>();
130
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
131
+ .setMockMethodCallHandler(channel, (call) async {
132
+ calls.add(call);
133
+ if (call.method == 'activate') {
134
+ entered.complete();
135
+ await release.future;
136
+ }
137
+ return true;
138
+ });
139
+ final activating =
140
+ port.activate(scope, validUntil: now.add(const Duration(hours: 24)));
141
+ await entered.future.timeout(const Duration(seconds: 1));
142
+ final replacing = port.replace(scope, [row()], currentUserId: owner);
143
+ final deactivating = port.deactivate();
144
+ release.complete();
145
+ await Future.wait([activating, replacing, deactivating]);
146
+ expect(calls.map((x) => x.method), ['activate', 'deactivate']);
147
+ });
148
+ test('offline suppression is scoped and opaque', () async {
149
+ await port.activate(scope, validUntil: now.add(const Duration(hours: 24)));
150
+ await port.suppressPlanItems(scope, {item});
151
+ expect(calls.last.method, 'suppressPlanItems');
152
+ expect(calls.last.arguments, {
153
+ 'scope': scope,
154
+ 'planItemIds': [item]
155
+ });
156
+ await expectLater(
157
+ port.suppressPlanItems('other', {item}), throwsStateError);
158
+ await expectLater(
159
+ port.suppressPlanItems(scope, {'invalid'}), throwsArgumentError);
160
+ });
161
+ test('notification and exact-alarm permissions are separate user actions',
162
+ () async {
163
+ expect(calls, isEmpty);
164
+ final normal = await port.requestPermission();
165
+ expect(calls.last.method, 'requestPermission');
166
+ expect(normal.activeScope, scope);
167
+ expect(normal.validUntil, now.add(const Duration(hours: 24)));
168
+ final exact = await port.requestExactAlarmAccess();
169
+ expect(calls.last.method, 'requestExactAlarmAccess');
170
+ expect(exact.canScheduleExactAlarms, isTrue);
171
+ expect(exact.timing, 'exact');
172
+ });
173
+ test('missing plugin never claims background support', () async {
174
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
175
+ .setMockMethodCallHandler(channel, null);
176
+ expect((await port.status()).supported, isFalse);
177
+ await port.deactivate();
178
+ });
179
+ test('non-Android fallback never calls native scheduling', () async {
180
+ debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
181
+ expect((await port.status()).supported, isFalse);
182
+ await port.activate(scope, validUntil: now.add(const Duration(hours: 1)));
183
+ await port.replace(scope, [row()], currentUserId: owner);
184
+ await port.deactivate();
185
+ expect(calls, isEmpty);
186
+ });
187
+}