Rooms sync: a TV never syncs with itself

Ported from release-0.108 (0.108.103).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-07 23:00:10 +00:00
co-authored by Claude Opus 5.5
parent 6aed1c399e
commit e3fc8a98c1
@@ -108,6 +108,7 @@ internal object RoomSync {
fun answer(context: Context, scheduleDir: File, body: String, from: String?, nowMs: Long = System.currentTimeMillis()): Pair<Int, JSONObject> {
val req = runCatching { JSONObject(body) }.getOrNull() ?: return 400 to JSONObject()
val link = RoomLinks.of(req.optString("link"))?.takeIf { it.on } ?: return 404 to JSONObject()
if (from != null && from in ownAddresses()) return 409 to JSONObject()
val o = open(link, req.optString("sealed"), nowMs) ?: return 403 to JSONObject()
merge(context, scheduleDir, o, nowMs)
val reply = state(context, scheduleDir, o.optLong("since"), nowMs)
@@ -116,10 +117,16 @@ internal object RoomSync {
return 200 to JSONObject().put("sealed", RoomCrypto.seal(link.key, reply.toString().toByteArray()))
}
/** One round from this TV: each paired room it can reach, at its last address or as found on the Wi-Fi. */
/** This TV's own addresses: it finds itself on the Wi-Fi too, and must never sync with itself (seen 7 November 2026). */
fun ownAddresses(): Set<String> = runCatching {
java.net.NetworkInterface.getNetworkInterfaces().toList().flatMap { it.inetAddresses.toList() }.mapNotNull { it.hostAddress?.substringBefore('%') }.toSet()
}.getOrDefault(emptySet())
/** One round from this TV: each paired room it can reach, at its last address or as found on the Wi-Fi, never itself. */
fun round(context: Context, scheduleDir: File, found: List<String>, nowMs: Long = System.currentTimeMillis()) {
val mine = ownAddresses()
for (link in RoomLinks.links.filter { it.on }) {
for (address in (listOfNotNull(link.address) + found).distinct()) {
for (address in (listOfNotNull(link.address) + found).distinct().filter { it !in mine }) {
val call = roomTransport(address) ?: continue
val sent = state(context, scheduleDir, link.lastSyncMs, nowMs)
val (status, text) = runCatching { call("POST", "/room/sync", JSONObject().put("link", link.id).put("sealed", RoomCrypto.seal(link.key, sent.toString().toByteArray())).toString()) }