fix #2062: Remap channels when rearranged (#3561)

This commit is contained in:
Dane Evans 2025-10-31 01:55:37 +11:00 committed by GitHub
parent 4f6140c1d6
commit 2b79590881
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 38 additions and 1 deletions

View file

@ -30,6 +30,7 @@ import org.meshtastic.core.database.entity.PacketEntity
import org.meshtastic.core.database.entity.ReactionEntity
import org.meshtastic.core.model.DataPacket
import org.meshtastic.core.model.MessageStatus
import org.meshtastic.proto.ChannelProtos.ChannelSettings
@Suppress("TooManyFunctions")
@Dao
@ -250,4 +251,29 @@ interface PacketDao {
@Query("DELETE FROM packet")
suspend fun deleteAll()
/**
* One-time migration: Remap all message DataPacket.channel indices to new mapping using PSK after a channel
* reorder. For each Packet (with port_num = 1), finds the old PSK then sets the channel index to the matching
* newSettings index. Skips if PSKs do not match or are missing.
*/
@Transaction
suspend fun migrateChannelsByPSK(oldSettings: List<ChannelSettings>, newSettings: List<ChannelSettings>) {
val pskToNewIndex = newSettings.mapIndexed { idx, ch -> ch.psk to idx }.toMap()
val allPackets = getAllUserPacketsForMigration()
for (packet in allPackets) {
val oldIndex = packet.data.channel
val oldPSK = oldSettings.getOrNull(oldIndex)?.psk
val newIndex = if (oldPSK != null) pskToNewIndex[oldPSK] else null
if (oldPSK != null && newIndex != null && oldIndex != newIndex) {
// Rebuild contact_key with the new index, keeping the rest unchanged
val oldKeySuffix = packet.contact_key.drop(1) // removes only the channelIndex prefix
val newContactKey = "$newIndex$oldKeySuffix"
update(packet.copy(contact_key = newContactKey, data = packet.data.copy(channel = newIndex)))
}
}
}
@Query("SELECT * FROM packet WHERE port_num = 1")
suspend fun getAllUserPacketsForMigration(): List<Packet>
}