findfamily: stop sharing when you arrive at a saved place (#406)
- Commit
24d698d6f59001f53d4b206b6cc32c0ac52586a0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-12 20:47 UTC (3 months ago)
- Parents
1bcacce
Diff
findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.ktindex 65fea3d468..6e7a6eb50b 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -80,12 +80,18 @@ interface UserDao { // --- Atomic helpers for the "Disable after / Enable after" feature --- - /** Atomically set only the auto-toggle deadline (Never = null). Avoids clobbering other columns. */- @Query("UPDATE User SET sharingAutoToggleAt = :atEpochSeconds WHERE id = :id")+ /** Atomically set only the time-based auto-toggle deadline (Never = null). Also clears any+ * arrival trigger so the two auto-toggle modes stay mutually exclusive. */+ @Query("UPDATE User SET sharingAutoToggleAt = :atEpochSeconds, sharingAutoToggleWaypointId = NULL WHERE id = :id") suspend fun setSharingAutoToggleAt(id: Long, atEpochSeconds: Long?) + /** Atomically set the arrival-based auto-toggle waypoint (Never = null). Also clears any+ * time-based deadline so the two auto-toggle modes stay mutually exclusive. */+ @Query("UPDATE User SET sharingAutoToggleWaypointId = :waypointId, sharingAutoToggleAt = NULL WHERE id = :id")+ suspend fun setSharingAutoToggleWaypointId(id: Long, waypointId: Long?)+ /** Atomically set sharing enabled AND clear any pending auto-toggle (manual toggle path). */- @Query("UPDATE User SET sendingEnabled = :enabled, sharingAutoToggleAt = NULL WHERE id = :id")+ @Query("UPDATE User SET sendingEnabled = :enabled, sharingAutoToggleAt = NULL, sharingAutoToggleWaypointId = NULL WHERE id = :id") suspend fun setSendingEnabledAndClearToggle(id: Long, enabled: Boolean) /**@@ -97,6 +103,16 @@ interface UserDao { @Query("UPDATE User SET sendingEnabled = CASE WHEN sendingEnabled THEN 0 ELSE 1 END, sharingAutoToggleAt = NULL WHERE sharingAutoToggleAt IS NOT NULL AND sharingAutoToggleAt <= :nowEpochSeconds") suspend fun applyDueAutoToggles(nowEpochSeconds: Long): Int + /**+ * Atomically flip sharing for every row whose arrival trigger points at a waypoint that+ * "Me" is currently inside ([insideWaypointIds]). The waypoint id in the WHERE clause guards+ * against TOCTOU races the same way the timer does above: if the user cleared or changed the+ * trigger, the row no longer matches. Clears the trigger on flip so it fires once per arrival.+ * Returns number of rows flipped.+ */+ @Query("UPDATE User SET sendingEnabled = CASE WHEN sendingEnabled THEN 0 ELSE 1 END, sharingAutoToggleWaypointId = NULL WHERE sharingAutoToggleWaypointId IS NOT NULL AND sharingAutoToggleWaypointId IN (:insideWaypointIds)")+ suspend fun applyDueArrivalToggles(insideWaypointIds: List<Long>): Int+ // --- Atomic partial updates to avoid heartbeat clobbering sharingAutoToggleAt / sendingEnabled --- @Query("UPDATE User SET locationName = :locationName, lastWaypointId = :lastWaypointId, lastLocationChangeTime = :lastLocationChangeTime WHERE id = :id")@@ -133,7 +149,7 @@ interface TemporaryLinkDao { suspend fun delete(value: TemporaryLink): Int } -@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 8, exportSchema = false)+@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 9, exportSchema = false) @TypeConverters(DefaultConverters::class) abstract class FFDatabase : RoomDatabase() { abstract fun userDao(): UserDao@@ -192,6 +208,9 @@ abstract class FFDatabase : RoomDatabase() { ) it.execSQL("DROP TABLE `TemporaryLink`") it.execSQL("ALTER TABLE `TemporaryLink_new` RENAME TO `TemporaryLink`")+ },+ androidx.room.migration.Migration(8, 9) {+ it.execSQL("ALTER TABLE `User` ADD COLUMN `sharingAutoToggleWaypointId` INTEGER") } ) }
findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.ktindex dd48cf8a5c..d271b8ea60 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt@@ -31,6 +31,9 @@ data class User( val platform: String? = null, /** When to auto-toggle sharing (flip sendingEnabled). Null means Never / disabled. Single field. */ val sharingAutoToggleAt: Instant? = null,+ /** Waypoint whose arrival (by "Me") flips sendingEnabled. Null means no arrival trigger.+ * Mutually exclusive with [sharingAutoToggleAt]: setting one clears the other. */+ val sharingAutoToggleWaypointId: Long? = null, /** Peer post-quantum public bundle (base64: [4B kemLen][kemPubDer][dsaPubDer]), nullable for backward compat. */ val pqcEncryptionKey: String? = null ): DatabaseItem {
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex df59447e10..674b9ab87c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -358,7 +358,7 @@ fun MainPage( val personActions = object : PersonActions by ffViewModel { override fun changeConnectedContact() = requestPickContact() }- PersonDetailSheet(PersonUiState(user, userPositions[user.id]), personActions)+ PersonDetailSheet(PersonUiState(user, userPositions[user.id], waypoints), personActions) } } else if (selectedWaypointId != null) { Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 12.dp, vertical = 4.dp)) {@@ -610,9 +610,9 @@ fun PersonDetailSheet(state: PersonUiState, actions: PersonActions) { { send -> actions.setUserSharing(user, send) } ) }- // Auto-toggle: "Turn on/off after" + duration dropdown (Never default)+ // Auto-toggle: "Turn on/off after" + duration/arrival dropdown (Never default) Spacer(Modifier.height(4.dp))- AutoToggleRow(user, actions)+ AutoToggleRow(user, state.waypoints, actions) Spacer(Modifier.height(4.dp)) } OutlinedButton(@@ -842,7 +842,7 @@ private fun formatAutoToggleCountdown(remaining: Duration): String { @OptIn(ExperimentalMaterial3Api::class) @Composable-fun AutoToggleRow(user: User, actions: PersonActions) {+fun AutoToggleRow(user: User, waypoints: List<Waypoint>, actions: PersonActions) { val neverLabel = stringResource(R.string.auto_toggle_never) val opts = remember { listOf(@@ -874,6 +874,11 @@ fun AutoToggleRow(user: User, actions: PersonActions) { val labelToDuration: Map<String, Duration> = opts.associate { (k, v) -> (resolvedLabels[k] ?: k) to v } + // Arrival triggers: one "Arrival at <name>" option per named saved place.+ val arrivalWaypoints = waypoints.filter { it.name.isNotBlank() }+ val arrivalWaypointName = user.sharingAutoToggleWaypointId+ ?.let { id -> arrivalWaypoints.firstOrNull { it.id == id }?.name }+ // Live ticker for countdown — ticks every second while a timeout is active var now by remember { mutableStateOf(Clock.System.now()) } val endAt = user.sharingAutoToggleAt@@ -887,12 +892,15 @@ fun AutoToggleRow(user: User, actions: PersonActions) { } } - // If enabled, show live [hh:]mm:ss countdown; otherwise Never. Dropdown remains for picking new value.- val currentLabel = if (endAt == null) {- neverLabel- } else {- val remaining = endAt - now- if (remaining.inWholeSeconds <= 0) neverLabel else formatAutoToggleCountdown(remaining)+ // Arrival trigger wins if set; otherwise show live [hh:]mm:ss countdown; otherwise Never.+ // Auto-toggle modes are mutually exclusive, so at most one of these is active.+ val currentLabel = when {+ arrivalWaypointName != null -> stringResource(R.string.arrival_at, arrivalWaypointName)+ endAt == null -> neverLabel+ else -> {+ val remaining = endAt - now+ if (remaining.inWholeSeconds <= 0) neverLabel else formatAutoToggleCountdown(remaining)+ } } val dropdownLabel = if (user.sendingEnabled) stringResource(R.string.disable_after) else stringResource(R.string.enable_after)@@ -928,6 +936,13 @@ fun AutoToggleRow(user: User, actions: PersonActions) { actions.setUserAutoToggle(user, dur) }) }+ // Arrival triggers — flip sharing when "Me" arrives at a saved place (GitHub #406).+ arrivalWaypoints.forEach { waypoint ->+ DropdownMenuItem({ Text(stringResource(R.string.arrival_at, waypoint.name)) }, {+ expanded = false+ actions.setUserArrivalToggle(user, waypoint.id)+ })+ } } } }
findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.ktindex f3427db994..545d713785 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt@@ -55,6 +55,8 @@ interface FamilyListActions { data class PersonUiState( val user: User, val location: LocationValue? = null,+ /** Saved places, offered in the auto-toggle dropdown as "Arrival at <name>" triggers. */+ val waypoints: List<Waypoint> = emptyList(), ) /** Person-sheet callbacks. Same no-op-default arrangement as [FamilyListActions]. */@@ -64,6 +66,9 @@ interface PersonActions { /** Flip sharing after [duration]; null means Never. */ fun setUserAutoToggle(user: User, duration: Duration?) {} + /** Flip sharing when "Me" arrives at waypoint [waypointId]; null means Never. */+ fun setUserArrivalToggle(user: User, waypointId: Long?) {}+ /** Re-pick which device contact this connection is named after. */ fun changeConnectedContact() {}
findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.ktindex 9b420887b7..bf1491344f 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt@@ -375,6 +375,14 @@ class FindFamilyViewModel( } } + /** Set arrival-based auto-toggle for sharing — flips sendingEnabled when "Me" arrives at+ * [waypointId]. Null means Never. Atomic and mutually exclusive with the time-based deadline. */+ override fun setUserArrivalToggle(user: User, waypointId: Long?) {+ viewModelScope.launch(Dispatchers.IO) {+ userDao.setSharingAutoToggleWaypointId(user.id, waypointId)+ }+ }+ /** Called from foreground service (or init) when any auto-toggle is due. * Atomic SQL flip guarded by the timer value itself — prevents TOCTOU where the user * manually cleared or rescheduled the timer but a stale service snapshot still flips. */
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.ktindex 3c7774a190..1c3d029e60 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -181,6 +181,25 @@ class LocationTrackingService : Service(), SensorEventListener { Log.w("FF-Heartbeat", "auto-toggle apply failed", e) } + // Arrival auto-toggle check (GitHub #406): flip sharing for any user whose trigger+ // points at a saved place that "Me" is currently inside. Uses the same atomic,+ // waypoint-id-guarded update as the timer path so a stale snapshot cannot mis-flip.+ try {+ val myCoord = Coord(location.latitude, location.longitude)+ val insideWaypointIds = waypointDao.getAll()+ .filter { havershine(it.coord, myCoord) < it.range }+ .map { it.id }+ if (insideWaypointIds.isNotEmpty()) {+ val flippedArrival = userDao.applyDueArrivalToggles(insideWaypointIds)+ if (flippedArrival > 0) {+ Log.d("FF-Heartbeat", "arrival auto-toggle flipped $flippedArrival user(s), reloading sharing state before publish")+ publishBaseUsers = userDao.getAll()+ }+ }+ } catch (e: Exception) {+ Log.w("FF-Heartbeat", "arrival auto-toggle apply failed", e)+ }+ val publishTargets = publishBaseUsers.filter { it.id != Networking.userid && it.sendingEnabled } Log.d("FF-Heartbeat", "publish targets count=${publishTargets.size} ids=${publishTargets.map{ it.id.toULong() }} names=${publishTargets.map{ it.name }}") publishTargets.forEach {
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex 1f22d620c6..f3cda83b3b 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -118,6 +118,8 @@ <string name="enable_after">Enable after</string> <!-- UserPage: Auto-toggle dropdown option for never / disabled --> <string name="auto_toggle_never">Never</string>+ <!-- UserPage: Auto-toggle dropdown option that flips sharing when you arrive at a saved place. %1$s = place name, e.g. Home -->+ <string name="arrival_at">Arrival at %1$s</string> <!-- MainPage TopAppBar: Title when in history mode. %1$s = selected user name, e.g. Alice --> <string name="history_title">History: <xliff:g id="person_name" example="Alice">%1$s</xliff:g></string> <!-- HistoryScrubber: Button label to step back 5 minutes. Verb with duration -->