fix: handle deleted channels in ChannelSet DataStore

adds `removeSettings` method to delete channels with `Role.DISABLED`
This commit is contained in:
andrekir 2023-05-06 08:08:17 -03:00
parent feed8262ea
commit 41d0315b63
2 changed files with 26 additions and 24 deletions

View file

@ -7,7 +7,7 @@ import com.geeksville.mesh.ChannelProtos
import com.geeksville.mesh.ConfigProtos
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import java.io.IOException
import javax.inject.Inject
@ -40,14 +40,23 @@ class ChannelSetRepository @Inject constructor(
}
}
suspend fun addSettings(channel: ChannelProtos.Channel) {
/**
* Updates the ChannelSettings list with the provided channel and returns the index of the
* admin channel after the update (if not found, returns 0).
*/
suspend fun updateChannelSettings(channel: ChannelProtos.Channel): Int {
channelSetStore.updateData { preference ->
if (preference.settingsCount > channel.index) {
preference.toBuilder().setSettings(channel.index, channel.settings).build()
if (channel.role == ChannelProtos.Channel.Role.DISABLED) {
preference.toBuilder().removeSettings(channel.index).build()
} else {
preference.toBuilder().setSettings(channel.index, channel.settings).build()
}
} else {
preference.toBuilder().addSettings(channel.settings).build()
preference.toBuilder().addSettings(channel.index, channel.settings).build()
}
}
return getAdminChannel()
}
suspend fun addAllSettings(channelSet: ChannelSet) {
@ -62,6 +71,13 @@ class ChannelSetRepository @Inject constructor(
}
}
suspend fun fetchInitialChannelSet() = channelSetStore.data.first()
/**
* Returns the index of the admin channel (or 0 if not found).
*/
private suspend fun getAdminChannel(): Int = fetchInitialChannelSet()?.settingsList
?.indexOfFirst { it.name.lowercase() == "admin" }
?.coerceAtLeast(0) ?: 0
suspend fun fetchInitialChannelSet() = channelSetStore.data.firstOrNull()
}