findfamily: add autotoggle sharing
- Commit
eabb99ab3ae475cf9e2f00538bdfaa540f91f707- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-27 18:53 UTC (4 months ago)
- Parents
c86b2ca
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 8146d4b8f5..c3b3e7af95 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -97,7 +97,7 @@ interface TemporaryLinkDao { suspend fun delete(value: TemporaryLink): Int } -@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 5, exportSchema = false)+@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 6, exportSchema = false) @TypeConverters(DefaultConverters::class) abstract class FFDatabase : RoomDatabase() { abstract fun userDao(): UserDao@@ -121,6 +121,9 @@ abstract class FFDatabase : RoomDatabase() { }, androidx.room.migration.Migration(4, 5) { it.execSQL("ALTER TABLE `User` ADD COLUMN `platform` TEXT")+ },+ androidx.room.migration.Migration(5, 6) {+ it.execSQL("ALTER TABLE `User` ADD COLUMN `sharingAutoToggleAt` 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 3c7d46e423..ae1aee8ebb 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt@@ -28,9 +28,11 @@ data class User( @PrimaryKey(autoGenerate = true) override val id: Long = 0, val lastWaypointId: Long? = null, /** Peer device platform (`"android"` or `"ios"`), learned from heartbeat payloads. Null until first heartbeat after both sides upgrade. */- val platform: String? = null+ val platform: String? = null,+ /** When to auto-toggle sharing (flip sendingEnabled). Null means Never / disabled. Single field. */+ val sharingAutoToggleAt: Instant? = null ): DatabaseItem { companion object { val EMPTY = User(" ", null, "Unnamed Location", true, RequestStatus.MUTUAL_CONNECTION, Clock.System.now(), null) }-}\ No newline at end of file+}
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 1582275150..58ccde2d3d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -46,6 +46,9 @@ import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.ListItemDefaults import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ExposedDropdownMenuDefaults+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Slider@@ -58,6 +61,10 @@ import com.vayunmathur.library.ui.dynamicLightColorScheme import com.vayunmathur.library.ui.rememberBottomSheetScaffoldState import com.vayunmathur.library.ui.rememberSliderState import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.findfamily.ui.dialogs.interactionSourceClickable+import kotlin.time.Duration+import kotlin.time.Duration.Companion.days+import kotlin.time.Duration.Companion.hours import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -356,6 +363,9 @@ fun MainPage( { send -> ffViewModel.setUserSharing(user, send) } ) }+ // Auto-toggle: "Turn on/off after" + duration dropdown (Never default)+ Spacer(Modifier.height(4.dp))+ AutoToggleRow(user, ffViewModel) Spacer(Modifier.height(4.dp)) OutlinedButton( { requestPickContact() },@@ -741,6 +751,111 @@ fun timestring(timestamp: Instant, future: Boolean, context: Context): String { } } +private fun formatAutoToggleCountdown(remaining: Duration): String {+ val totalSeconds = remaining.inWholeSeconds.coerceAtLeast(0)+ val hours = totalSeconds / 3600+ val minutes = (totalSeconds % 3600) / 60+ val seconds = totalSeconds % 60+ return if (hours > 0) {+ "%d:%02d:%02d".format(hours, minutes, seconds)+ } else {+ "%02d:%02d".format(minutes, seconds)+ }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun AutoToggleRow(user: User, ffViewModel: FindFamilyViewModel) {+ val neverLabel = stringResource(R.string.auto_toggle_never)+ val opts = remember {+ listOf(+ Pair("15 min", 15.minutes),+ Pair("30 min", 30.minutes),+ Pair("1 hour", 1.hours),+ Pair("2 hours", 2.hours),+ Pair("4 hours", 4.hours),+ Pair("6 hours", 6.hours),+ Pair("12 hours", 12.hours),+ Pair("1 day", 1.days),+ Pair("2 days", 2.days),+ Pair("1 week", 7.days),+ )+ }++ val resolvedLabels = mapOf(+ "15 min" to stringResource(R.string.expiry_15_minutes),+ "30 min" to stringResource(R.string.expiry_30_minutes),+ "1 hour" to stringResource(R.string.expiry_1_hour),+ "2 hours" to stringResource(R.string.expiry_2_hours),+ "4 hours" to stringResource(R.string.expiry_4_hours),+ "6 hours" to stringResource(R.string.expiry_6_hours),+ "12 hours" to stringResource(R.string.expiry_12_hours),+ "1 day" to stringResource(R.string.expiry_1_day),+ "2 days" to stringResource(R.string.expiry_2_days),+ "1 week" to stringResource(R.string.expiry_1_week),+ )++ val labelToDuration: Map<String, Duration> = opts.associate { (k, v) -> (resolvedLabels[k] ?: k) to v }++ // Live ticker for countdown — ticks every second while a timeout is active+ var now by remember { mutableStateOf(Clock.System.now()) }+ val endAt = user.sharingAutoToggleAt+ LaunchedEffect(endAt) {+ if (endAt == null) return@LaunchedEffect+ while (true) {+ kotlinx.coroutines.delay(1000)+ val current = Clock.System.now()+ now = current+ if (current >= endAt) break+ }+ }++ // 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)+ }++ val dropdownLabel = if (user.sendingEnabled) stringResource(R.string.disable_after) else stringResource(R.string.enable_after)++ var expanded by remember { mutableStateOf(false) }++ Row(+ Modifier.fillMaxWidth().padding(horizontal = 4.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ dropdownLabel,+ Modifier.weight(1f),+ style = MaterialTheme.typography.bodyMedium+ )+ Box {+ OutlinedTextField(+ currentLabel, {},+ interactionSource = interactionSourceClickable { expanded = true },+ readOnly = true,+ modifier = Modifier.width(180.dp),+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }+ )+ DropdownMenu(expanded, { expanded = false }) {+ // Never option first — disables auto-toggle; others reschedule countdown+ DropdownMenuItem({ Text(neverLabel) }, {+ expanded = false+ ffViewModel.setUserAutoToggle(user, null)+ })+ labelToDuration.forEach { (label, dur) ->+ DropdownMenuItem({ Text(label) }, {+ expanded = false+ ffViewModel.setUserAutoToggle(user, dur)+ })+ }+ }+ }+ }+}+ object DateFormats { // example: Jun 4 val MONTH_DAY = LocalDate.Format {
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 8456efcd80..a4d736ddde 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt@@ -331,14 +331,51 @@ class FindFamilyViewModel( } /** Toggle per-person location sharing and reconcile the service so it stops- * when nobody is being shared with and starts when sharing is (re)enabled. */+ * when nobody is being shared with and starts when sharing is (re)enabled.+ * Manual toggle always resets auto-toggle to Never. */ fun setUserSharing(user: User, enabled: Boolean) { viewModelScope.launch(Dispatchers.IO) {- userDao.upsert(user.copy(sendingEnabled = enabled))+ userDao.upsert(user.copy(sendingEnabled = enabled, sharingAutoToggleAt = null)) LocationServiceController.syncServiceState(ctx) } } + /** Set auto-toggle for sharing — same durations as one-time links, Never = null. Single field. */+ fun setUserAutoToggle(user: User, duration: kotlin.time.Duration?) {+ viewModelScope.launch(Dispatchers.IO) {+ if (duration == null) {+ userDao.upsert(user.copy(sharingAutoToggleAt = null))+ } else {+ val at = Clock.System.now() + duration+ userDao.upsert(user.copy(sharingAutoToggleAt = at))+ }+ }+ }++ /** Called from foreground service (or init) when any auto-toggle is due. */+ suspend fun applyDueAutoToggles() {+ val now = Clock.System.now()+ val all = userDao.getAll()+ for (u in all) {+ val at = u.sharingAutoToggleAt+ if (at != null && now >= at) {+ userDao.upsert(+ u.copy(+ sendingEnabled = !u.sendingEnabled,+ sharingAutoToggleAt = null+ )+ )+ }+ }+ }++ /** Clears expired auto-toggles that are past due but without flipping — used during init cleanup. */+ fun clearExpiredAutoTogglesIfAny() {+ viewModelScope.launch(Dispatchers.IO) {+ applyDueAutoToggles()+ }+ }+ // ------------------------------------------------------------------ // Feature check (network provider + geocoder) // ------------------------------------------------------------------@@ -416,6 +453,8 @@ class FindFamilyViewModel( // it's safe for the service to also call it (it may start before the UI). viewModelScope.launch(Dispatchers.IO) { Networking.init(userDao, DataStoreUtils.getInstance(ctx), ctx.getString(R.string.me_label))+ // Apply any due auto-toggles on cold start+ applyDueAutoToggles() } // Trim location history older than a week. viewModelScope.launch(Dispatchers.IO) {
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 4a106fa743..f1078a875c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -24,6 +24,7 @@ import android.os.BatteryManager import android.os.Build import android.os.IBinder import android.os.PowerManager+import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import kotlinx.coroutines.*@@ -117,107 +118,161 @@ class LocationTrackingService : Service(), SensorEventListener { } private suspend fun syncHeartbeat() {- val location = lastKnownLocation ?: return- if (Networking.userid == 0L) return- - val currentUsers = userDao.getAll()- val currentWaypoints = waypointDao.getAll()- val currentLinks = temporaryLinkDao.getAll()- val userIDs = currentUsers.map { it.id }- val now = Clock.System.now()-- val locationValue = LocationValue(- Networking.userid,- Coord(location.latitude, location.longitude),- 0f,- location.accuracy,- now,- bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toFloat()- )+ val location = lastKnownLocation ?: run {+ Log.d("FF-Heartbeat", "syncHeartbeat: no lastKnownLocation yet")+ return+ }+ if (Networking.userid == 0L) {+ Log.d("FF-Heartbeat", "syncHeartbeat: userid==0, not initialized yet")+ return+ } - locationValueDao.upsert(locationValue)- Networking.ensureUserExists()-- if (currentUsers.none { it.id == Networking.userid }) {- userDao.upsert(- User(- getString(R.string.me_label),- null,- "Unnamed Location",- true,- RequestStatus.MUTUAL_CONNECTION,- Clock.System.now(),- null,- Networking.userid- )+ // Shield the entire heartbeat so one failing DAO / crypto / network call+ // does not kill the foreground service loop (which previously surfaced as+ // FATAL BadPaddingException in decrypt).+ try {+ val currentUsers = userDao.getAll()+ val currentWaypoints = waypointDao.getAll()+ val currentLinks = temporaryLinkDao.getAll()+ val userIDs = currentUsers.map { it.id }+ val now = Clock.System.now()++ Log.d("FF-Heartbeat", "heartbeat userid=${Networking.userid.toULong()} self raw=${Networking.userid} users=${currentUsers.size} links=${currentLinks.size} moving=$isMoving loc=${location.latitude},${location.longitude} acc=${location.accuracy}")++ val locationValue = LocationValue(+ Networking.userid,+ Coord(location.latitude, location.longitude),+ 0f,+ location.accuracy,+ now,+ bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toFloat() )- } - currentUsers.filter { it.id != Networking.userid && it.sendingEnabled }.forEach { Networking.publishLocation(locationValue, it) }- currentLinks.filter { now < it.deleteAt }.forEach { Networking.publishLocation(locationValue, it) }- currentLinks.filter { now >= it.deleteAt }.forEach { temporaryLinkDao.delete(it) }-- delay(3000)- Networking.receiveLocations()?.let { locations ->- val usersRecieved = locations.map { it.userid }.distinct()- val newUsers = usersRecieved.filter { it !in userIDs && it != Networking.userid }- userDao.insertAllIgnore(newUsers.map {- User(" ", null, "Unknown Location", false, RequestStatus.AWAITING_REQUEST, Clock.System.now(), null, it)- })-- val latestMap = locationValueDao.getLatest().first().associateBy { it.userid }- currentUsers.forEach { user ->- // Self never receives its own published location, so fall back to the fix we- // just recorded this heartbeat; otherwise "me" never gets its waypoint recomputed.- val lastLoc = if (user.id == Networking.userid) locationValue- else locations.filter { it.userid == user.id }.maxByOrNull { it.timestamp }- lastLoc ?: return@forEach- val lastSavedLoc = latestMap[user.id]-- if (lastLoc.battery <= 15f && (lastSavedLoc?.battery ?: 100f) > 15f) {- if (user.id != Networking.userid) {- createNotificationWithCategory(user.name, getString(R.string.notification_low_battery, user.name), "BATTERY_LOW", user.id)+ Log.d("FF-Heartbeat", "upsert local LocationValue for self")+ locationValueDao.upsert(locationValue)+ try {+ Log.d("FF-Heartbeat", "ensureUserExists start")+ Networking.ensureUserExists()+ Log.d("FF-Heartbeat", "ensureUserExists done")+ } catch (e: Exception) {+ Log.w("FF-Heartbeat", "ensureUserExists threw", e)+ }++ if (currentUsers.none { it.id == Networking.userid }) {+ Log.d("FF-Heartbeat", "self not in user DB, inserting me")+ userDao.upsert(+ User(+ getString(R.string.me_label),+ null,+ "Unnamed Location",+ true,+ RequestStatus.MUTUAL_CONNECTION,+ Clock.System.now(),+ null,+ Networking.userid+ )+ )+ }++ // Auto-toggle check: flip sendingEnabled when scheduled time is due (Never = disabled)+ currentUsers.forEach { u ->+ val at = u.sharingAutoToggleAt+ if (at != null && now >= at) {+ try {+ userDao.upsert(u.copy(sendingEnabled = !u.sendingEnabled, sharingAutoToggleAt = null))+ } catch (e: Exception) {+ Log.w("FF-Heartbeat", "auto-toggle failed for ${u.id}", e) } }+ } - val inWaypoint = currentWaypoints.find { havershine(it.coord, lastLoc.coord) < it.range }- val prevId = user.lastWaypointId- val stillInsidePrev = prevId?.let { pid ->- currentWaypoints.find { it.id == pid }?.let {- havershine(it.coord, lastLoc.coord) < it.range * 1.2+ val publishTargets = currentUsers.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 {+ val result = runCatching { Networking.publishLocation(locationValue, it) }+ if (result.isFailure) Log.w("FF-Heartbeat", "publish to ${it.id.toULong()} threw", result.exceptionOrNull())+ }+ currentLinks.filter { now < it.deleteAt }.forEach {+ val result = runCatching { Networking.publishLocation(locationValue, it) }+ if (result.isFailure) Log.w("FF-Heartbeat", "publish to link ${it.id} threw", result.exceptionOrNull())+ }+ currentLinks.filter { now >= it.deleteAt }.forEach { runCatching { temporaryLinkDao.delete(it) } }++ Log.d("FF-Heartbeat", "delay 3s then receive")+ delay(3000)+ val locations = try {+ Networking.receiveLocations()+ } catch (e: Exception) {+ Log.w("FF-Heartbeat", "receiveLocations threw", e)+ null+ }+ Log.d("FF-Heartbeat", "receiveLocations result=${locations?.size} for self ${Networking.userid.toULong()}")+ locations?.let { locList ->+ val usersRecieved = locList.map { it.userid }.distinct()+ Log.d("FF-Heartbeat", "received userids=${usersRecieved.map{ it.toULong() }} self=${Networking.userid.toULong()} known=${userIDs.map{ it.toULong() }}")+ val newUsers = usersRecieved.filter { it !in userIDs && it != Networking.userid }+ Log.d("FF-Heartbeat", "newUsers to insert=${newUsers.map{ it.toULong() }}")+ userDao.insertAllIgnore(newUsers.map {+ User(" ", null, "Unknown Location", false, RequestStatus.AWAITING_REQUEST, Clock.System.now(), null, it)+ })++ val latestMap = locationValueDao.getLatest().first().associateBy { it.userid }+ currentUsers.forEach { user ->+ // Self never receives its own published location, so fall back to the fix we+ // just recorded this heartbeat; otherwise "me" never gets its waypoint recomputed.+ val lastLoc = if (user.id == Networking.userid) locationValue+ else locList.filter { it.userid == user.id }.maxByOrNull { it.timestamp }+ lastLoc ?: return@forEach+ val lastSavedLoc = latestMap[user.id]++ if (lastLoc.battery <= 15f && (lastSavedLoc?.battery ?: 100f) > 15f) {+ if (user.id != Networking.userid) {+ createNotificationWithCategory(user.name, getString(R.string.notification_low_battery, user.name), "BATTERY_LOW", user.id)+ } }- } ?: false- val currentId: Long? = inWaypoint?.id ?: if (stillInsidePrev) prevId else null-- // Display name: prefer waypoint name (either entered or sticky-via-hysteresis), then geocoded address.- val displayName = inWaypoint?.name- ?: currentWaypoints.find { it.id == currentId }?.name- ?: fetchAddress(lastLoc.coord.lat, lastLoc.coord.lon)?.let {- it.featureName ?: it.thoroughfare++ val inWaypoint = currentWaypoints.find { havershine(it.coord, lastLoc.coord) < it.range }+ val prevId = user.lastWaypointId+ val stillInsidePrev = prevId?.let { pid ->+ currentWaypoints.find { it.id == pid }?.let {+ havershine(it.coord, lastLoc.coord) < it.range * 1.2+ }+ } ?: false+ val currentId: Long? = inWaypoint?.id ?: if (stillInsidePrev) prevId else null++ // Display name: prefer waypoint name (either entered or sticky-via-hysteresis), then geocoded address.+ val displayName = inWaypoint?.name+ ?: currentWaypoints.find { it.id == currentId }?.name+ ?: runCatching { fetchAddress(lastLoc.coord.lat, lastLoc.coord.lon) }.getOrNull()?.let {+ it.featureName ?: it.thoroughfare+ }+ ?: "Unknown Location"++ if (currentId != prevId || displayName != user.locationName) {+ userDao.upsert(user.copy(+ locationName = displayName,+ lastWaypointId = currentId,+ lastLocationChangeTime = lastLoc.timestamp+ )) }- ?: "Unknown Location"-- if (currentId != prevId || displayName != user.locationName) {- userDao.upsert(user.copy(- locationName = displayName,- lastWaypointId = currentId,- lastLocationChangeTime = lastLoc.timestamp- ))- } - if (currentId != prevId && user.id != Networking.userid) {- if (currentId != null) {- val enteredName = inWaypoint?.name- ?: currentWaypoints.find { it.id == currentId }?.name- ?: displayName- createNotificationWithCategory(user.name, getString(R.string.notification_entered_waypoint, user.name, enteredName), "ENTRY_EXIT", user.id)- } else if (prevId != null) {- val exitedName = currentWaypoints.find { it.id == prevId }?.name ?: user.locationName- createNotificationWithCategory(user.name, getString(R.string.notification_exited_waypoint, user.name, exitedName), "ENTRY_EXIT", user.id)+ if (currentId != prevId && user.id != Networking.userid) {+ if (currentId != null) {+ val enteredName = inWaypoint?.name+ ?: currentWaypoints.find { it.id == currentId }?.name+ ?: displayName+ createNotificationWithCategory(user.name, getString(R.string.notification_entered_waypoint, user.name, enteredName), "ENTRY_EXIT", user.id)+ } else if (prevId != null) {+ val exitedName = currentWaypoints.find { it.id == prevId }?.name ?: user.locationName+ createNotificationWithCategory(user.name, getString(R.string.notification_exited_waypoint, user.name, exitedName), "ENTRY_EXIT", user.id)+ } } }+ locationValueDao.upsertAll(locList)+ Log.d("FF-Heartbeat", "upsertAll ${locList.size} locations done") }- locationValueDao.upsertAll(locations)+ } catch (e: Exception) {+ Log.w("FF-Heartbeat", "syncHeartbeat crashed", e) } } @@ -228,7 +283,9 @@ class LocationTrackingService : Service(), SensorEventListener { * also fire a local notification so the user knows ranging is happening. */ private suspend fun drainUwbInbox() {- val envelopes = Networking.receiveUwbMessages() ?: return+ val envelopes = try {+ Networking.receiveUwbMessages() ?: return+ } catch (_: Exception) { return } if (envelopes.isEmpty()) return val users = userDao.getAll() for (envelope in envelopes) {@@ -652,7 +709,8 @@ object LocationServiceController { * answer is correct regardless of whether the UI/ViewModel is alive. */ suspend fun isSharingEnabled(context: Context): Boolean {- val selfId = DataStoreUtils.getInstance(context).getLong("userid")+ val ds = DataStoreUtils.getInstance(context)+ val selfId = try { ds.getLongAwait("userid") } catch (_: Exception) { ds.getLong("userid") } val db = context.buildDatabase<FFDatabase>() return db.userDao().getAll().any { it.sendingEnabled && it.id != selfId } }
findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.ktindex 277e68f9c5..67a6d59ab4 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -1,4 +1,5 @@ package com.vayunmathur.findfamily.util+import android.util.Log import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.LocationValueCompatible import com.vayunmathur.findfamily.data.TemporaryLink@@ -22,6 +23,7 @@ import kotlin.time.Clock object Networking { private const val URL = "https://findfamily.cc"+ private const val TAG = "FF-Networking" private val json = Json { ignoreUnknownKeys = true@@ -46,7 +48,7 @@ object Networking { /** Adapts the app's encrypted DataStore to the e2ee module's storage abstraction. */ private class DataStoreKeyStore(private val ds: DataStoreUtils) : E2eeKeyStore {- override fun getBytes(name: String): ByteArray? = ds.getByteArray(name)+ override suspend fun getBytes(name: String): ByteArray? = ds.getByteArrayAwait(name) override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) = ds.setByteArray(name, value, onlyIfAbsent) }@@ -59,9 +61,15 @@ object Networking { Networking.userDao = userDao // Loads the persisted keypair (or generates+stores one on first launch) using the same // "publicKey"/"privateKey" datastore entries as before, so existing installs keep their key.+ // Uses suspend DataStore hydration (getByteArrayAwait) to avoid the cold-start race where+ // state.value is still emptyPreferences() → ephemeral identity → OAEP_DECODING_ERROR. identity = E2eeIdentity.loadOrCreate(DataStoreKeyStore(dataStoreUtils))- dataStoreUtils.setLong("userid", Random.nextLong(), true)- userid = dataStoreUtils.getLong("userid")!!+ // Avoid negative IDs: server stores ULong but receive uses Long in request; generating+ // only positive IDs keeps both sides consistent and makes Base26 encoding stable.+ if (dataStoreUtils.getLongAwait("userid") == null) {+ dataStoreUtils.setLong("userid", Random.nextLong(from = 1, until = Long.MAX_VALUE), true)+ }+ userid = dataStoreUtils.getLongAwait("userid")!! if (userDao.getById(userid) == null) { userDao.upsert(@@ -89,6 +97,7 @@ object Networking { } catch (e: CancellationException) { throw e } catch(e: Exception) {+ Log.w(TAG, "checkNetworkDown caught exception", e) network_is_down = true } return null@@ -97,15 +106,24 @@ object Networking { private suspend inline fun <reified T, reified I> makeRequest(path: String, body: I): T? { return checkNetworkDown { try {+ // Important: NetworkClient.callJson expects body:String/ByteArray to be sent raw.+ // If we pass a @Serializable object directly, HttpUrlEngine.toBodyBytes does+ // body.toString() → "Register(userid=...)" not JSON → server returns 400+ // "expected value at line 1 column 1" which is exactly what live logs showed.+ val encodedBody = when (body) {+ is String -> body+ else -> json.encodeToString(body)+ } NetworkClient.callJson<T>( url = "$URL$path", method = "POST", headers = mapOf("Content-Type" to "application/json"),- body = body+ body = encodedBody ) } catch (e: CancellationException) { throw e } catch (e: Exception) {+ Log.w(TAG, "makeRequest $path failed", e) null } }@@ -114,33 +132,52 @@ object Networking { private suspend fun register(): Boolean { @Serializable data class Register(val userid: ULong, val key: String)- return makeRequest<Boolean, Register>("/api/register", Register(+ val ok = makeRequest<Boolean, Register>("/api/register", Register( userid.toULong(), Base64.encode(identity.publicKeyPem) ) ) ?: false+ Log.d(TAG, "register userid=${userid.toULong()} ok=$ok")+ return ok } suspend fun ensureUserExists() {- if(getKey(userid) == null) {+ val selfKey = getKey(userid)+ if(selfKey == null) {+ Log.w(TAG, "ensureUserExists: getKey failed for self ${userid.toULong()}, re-registering") register()+ } else {+ // Self-healing: if DataStore race previously registered an ephemeral key,+ // the server holds wrong key → peers encrypt to wrong pubkey → OAEP_DECODING_ERROR.+ // Detect mismatch and re-register correct key.+ val localB64 = Base64.encode(identity.publicKeyPem)+ val serverB64 = Base64.encode(selfKey)+ if (localB64 != serverB64) {+ Log.w(TAG, "ensureUserExists: server key mismatch for self ${userid.toULong()}, re-registering correct key localLen=${localB64.length} serverLen=${serverB64.length}")+ register()+ } else {+ Log.d(TAG, "ensureUserExists: self key exists and matches")+ } } } /** Fetches a peer's public key by id, returning its PEM bytes (or null if unknown/offline). */ private suspend fun getKey(userid: Long): ByteArray? {- return checkNetworkDown {+ val result = checkNetworkDown { val response = NetworkClient.performRequest( url = "$URL/api/getkey", method = "POST", headers = mapOf("Content-Type" to "application/json"), body = json.encodeToString(GetKeyRequest(userid.toULong())) )+ Log.d(TAG, "getKey id=${userid.toULong()} status=${response.status}") if(response.status != 200) { return@checkNetworkDown null } return@checkNetworkDown Base64.decode(response.body) }+ if (result == null) Log.w(TAG, "getKey failed for ${userid.toULong()}")+ return result } /** Local platform tag included in outgoing heartbeat payloads so the peer learns we're on Android. */@@ -153,19 +190,75 @@ object Networking { getKey(user.id)?.also { userDao.upsert(user.copy(encryptionKey = Base64.encode(it))) }- } ?: return false- return makeRequest<Boolean, LocationSharingData>("/api/location/publish", encryptLocation(location, user.id, keyPem)) ?: false+ }+ if (keyPem == null) {+ Log.w(TAG, "publishLocation: no key for user ${user.id.toULong()} (${user.name})")+ return false+ }+ return try {+ val encrypted = encryptLocation(location, user.id, keyPem)+ val ok = makeRequest<Boolean, LocationSharingData>("/api/location/publish", encrypted) ?: false+ Log.d(TAG, "publishLocation to ${user.id.toULong()} (${user.name}) ok=$ok coord=${location.coord.lat},${location.coord.lon} encLen=${encrypted.encryptedLocation.length}")+ ok+ } catch (e: Exception) {+ Log.w(TAG, "publishLocation to ${user.id.toULong()} failed with exception", e)+ false+ } } suspend fun publishLocation(location: LocationValue, user: TemporaryLink): Boolean {- val keyPem = Base64.decode(user.publicKey)- return makeRequest<Boolean, LocationSharingData>("/api/location/publish", encryptLocation(location, user.id, keyPem)) ?: false+ return try {+ val keyPem = Base64.decode(user.publicKey)+ val encrypted = encryptLocation(location, user.id, keyPem)+ val ok = makeRequest<Boolean, LocationSharingData>("/api/location/publish", encrypted) ?: false+ Log.d(TAG, "publishLocation to temp link ${user.id} ok=$ok encLen=${encrypted.encryptedLocation.length}")+ ok+ } catch (e: Exception) {+ Log.w(TAG, "publishLocation temp link ${user.id} exception", e)+ false+ } } suspend fun receiveLocations(): List<LocationValue>? {- val strings: List<String>? = makeRequest("/api/location/receive", json.encodeToString(UserIdRequest(userid)))- return strings?.map { decryptLocation(it) }?.also { decoded ->- // Opportunistically update peer platform tags learned from incoming heartbeats.+ // Use raw performRequest to correctly handle 204 No Content (empty queue) vs parsing error.+ val response = try {+ NetworkClient.performRequest(+ url = "$URL/api/location/receive",+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = json.encodeToString(UserIdRequest(userid.toULong()))+ )+ } catch (e: CancellationException) { throw e } catch (e: Exception) {+ Log.w(TAG, "receiveLocations: performRequest threw", e)+ return null+ }+ Log.d(TAG, "receiveLocations: status=${response.status} bodyLen=${response.body.length} for self ${userid.toULong()}")+ if (response.status == 204 || response.body.isBlank()) {+ Log.d(TAG, "receiveLocations: 204/empty, no pending")+ return emptyList()+ }+ if (response.status !in 200..299) {+ Log.w(TAG, "receiveLocations: server status ${response.status} body=${response.body.take(500)}")+ return null+ }+ val strings: List<String> = try {+ json.decodeFromString(response.body)+ } catch (e: Exception) {+ Log.w(TAG, "receiveLocations: failed to parse body ${response.body.take(500)}", e)+ return null+ }+ Log.d(TAG, "receiveLocations: got ${strings.size} raw blobs for self ${userid.toULong()}")+ // Per-message resilience: a single stale / undecryptable entry (e.g. encrypted to an old+ // rotated key) must not crash the heartbeat. Skip bad entries instead.+ var decryptFails = 0+ val decoded = strings.mapNotNull { enc ->+ runCatching { decryptLocation(enc) }.onFailure { e ->+ decryptFails+++ Log.w(TAG, "receiveLocations: decrypt failed (skipping) encLen=${enc.length}", e)+ }.getOrNull()+ }+ if (decryptFails > 0) Log.w(TAG, "receiveLocations: $decryptFails / ${strings.size} failed to decrypt")+ if (decoded.isNotEmpty()) { decoded.forEach { (loc, platform) -> if (platform != null) { val u = userDao.getById(loc.userid)@@ -174,7 +267,9 @@ object Networking { } } }- }?.map { it.first }+ }+ Log.d(TAG, "receiveLocations: returning ${decoded.size} after decrypt")+ return decoded.map { it.first } } // ----------------------------------------------------------------@@ -193,7 +288,9 @@ object Networking { getKey(recipientUserId) ?: return false } val str = json.encodeToString(envelope)- val encryptedData = Base64.encode(E2ee.encryptTo(keyPem, str.encodeToByteArray()))+ // Use hybrid sealTo (AES+GCM payload + RSA-wrapped key) so we never hit the+ // 126-byte RSA-OAEP-SHA512 limit that silently broke larger UWB payloads.+ val encryptedData = Base64.encode(E2ee.sealTo(keyPem, str.encodeToByteArray())) // We can't reuse `makeRequest<Boolean, ...>` here because the server // returns `204 No Content` (no body) on success, and Ktor's content // negotiation throws `NoTransformationFoundException` trying to@@ -214,25 +311,32 @@ object Networking { /** * Drains incoming UWB envelopes addressed to this user. The server queue * is cleared on receive (same semantics as `/api/location/receive`).+ * Supports both hybrid (sealTo) and legacy direct RSA for backward compat. */ suspend fun receiveUwbMessages(): List<UwbEnvelope>? {- val strings: List<String>? = makeRequest("/api/uwb/receive", json.encodeToString(UserIdRequest(userid)))+ val strings: List<String>? = makeRequest("/api/uwb/receive", json.encodeToString(UserIdRequest(userid.toULong()))) return strings?.mapNotNull { b64 -> runCatching {- val plain = identity.decrypt(Base64.decode(b64)).decodeToString()- json.decodeFromString<UwbEnvelope>(plain)+ val raw = Base64.decode(b64)+ // Try hybrid unseal first (new), fallback to direct decrypt (old peers).+ val plainBytes = runCatching { identity.unseal(raw) }.getOrElse { identity.decrypt(raw) }+ json.decodeFromString<UwbEnvelope>(plainBytes.decodeToString()) }.getOrNull() } } private suspend fun encryptLocation(location: LocationValue, recipientUserID: Long, keyPem: ByteArray): LocationSharingData { val str = json.encodeToString(location.toCompatible(senderPlatform = PLATFORM))- val encryptedData = Base64.encode(E2ee.encryptTo(keyPem, str.encodeToByteArray()))+ // Hybrid encryption: avoids 126-byte RSA-OAEP limit; location JSON is ~150-250 bytes.+ val encryptedData = Base64.encode(E2ee.sealTo(keyPem, str.encodeToByteArray())) return LocationSharingData(recipientUserID.toULong(), encryptedData) } private suspend fun decryptLocation(encryptedLocation: String): Pair<LocationValue, String?> {- val decryptedData = identity.decrypt(Base64.decode(encryptedLocation)).decodeToString()+ val raw = Base64.decode(encryptedLocation)+ // Backward compat: try unseal (new encrypted form) then direct decrypt (legacy peers).+ val decryptedData = runCatching { identity.unseal(raw).decodeToString() }+ .getOrElse { identity.decrypt(raw).decodeToString() } val compat = json.decodeFromString<LocationValueCompatible>(decryptedData) return compat.toLocationValue() to compat.senderPlatform }@@ -261,8 +365,9 @@ object Networking { @Serializable private data class LocationSharingData(val recipientUserID: ULong, val encryptedLocation: String) + /** Unified to ULong to match server storage from register (toULong). Prevents negative-ID mismatch. */ @Serializable- private data class UserIdRequest(val userid: Long)+ private data class UserIdRequest(val userid: ULong) @Serializable private data class GetKeyRequest(val userid: ULong)
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 aa9f09e543..46b8a201df 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -112,6 +112,12 @@ <string name="share_your_location">Share your location with this person</string> <!-- UserPage: Button to change linked contact entry. Verb phrase --> <string name="change_connected_contact">Change connected contact</string>+ <!-- UserPage: Auto-toggle dropdown label when sharing is ON — will disable after duration -->+ <string name="disable_after">Disable after</string>+ <!-- UserPage: Auto-toggle dropdown label when sharing is OFF — will enable after duration -->+ <string name="enable_after">Enable after</string>+ <!-- UserPage: Auto-toggle dropdown option for never / disabled -->+ <string name="auto_toggle_never">Never</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 -->