Rooms sync: paired rooms keep each other's family up to date

Ported from release-0.108 (0.108.102).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-07 22:42:07 +00:00
co-authored by Claude Opus 5.5
parent f4d9ce03c0
commit 6aed1c399e
9 changed files with 256 additions and 11 deletions
@@ -1,6 +1,7 @@
package tv.orbit.classic
import android.content.Context
import org.json.JSONObject
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
@@ -66,10 +67,20 @@ internal object AfterDarkLock {
}
fun set(context: Context, pin: String) {
val salt = java.util.UUID.randomUUID().toString()
prefs(context).edit().putString("after_dark_salt", salt).putString("after_dark_pin", pinHash(salt, pin)).apply()
prefs(context).edit().putString("after_dark_salt", salt).putString("after_dark_pin", pinHash(salt, pin)).putLong("pin_changed_at", System.currentTimeMillis()).apply()
pinSet = true; lock()
}
fun clear(context: Context) { prefs(context).edit().clear().apply(); pinSet = false; unlockedState = false; unlockedAt = 0L; nightly = false }
fun clear(context: Context) { prefs(context).edit().clear().putLong("pin_changed_at", System.currentTimeMillis()).apply(); pinSet = false; unlockedState = false; unlockedAt = 0L; nightly = false }
/** The PIN as rooms share it: only its salted hash and when it changed (Rooms sync). */
fun shared(context: Context): JSONObject = prefs(context).let { p -> JSONObject().put("salt", p.getString("after_dark_salt", null) ?: JSONObject.NULL)
.put("pin", p.getString("after_dark_pin", null) ?: JSONObject.NULL).put("changedAt", p.getLong("pin_changed_at", 0)) }
/** A paired room's PIN, taken when it changed more recently than this room's. Each room keeps its own unlock. */
fun takeShared(context: Context, o: JSONObject) {
val p = prefs(context); if (o.optLong("changedAt") <= p.getLong("pin_changed_at", 0)) return
val e = p.edit().putLong("pin_changed_at", o.optLong("changedAt"))
if (o.isNull("pin")) e.remove("after_dark_salt").remove("after_dark_pin") else e.putString("after_dark_salt", o.getString("salt")).putString("after_dark_pin", o.getString("pin"))
e.apply(); pinSet = !o.isNull("pin"); if (!pinSet) unlockedState = false
}
fun unlock(context: Context, pin: String) = check(context, pin).also { if (it) {
unlockedState = true; unlockedAt = System.currentTimeMillis(); prefs(context).edit().putLong("unlocked_at", unlockedAt).apply() } }
fun lock() { unlockedState = false; unlockedAt = 0L; store?.edit()?.remove("unlocked_at")?.apply() }
@@ -384,6 +384,17 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
runCatching { withContext(Dispatchers.IO) { Taste.watching(channel.number, show, channel.seriesIdAt(show.startMs), at - show.startMs, now) } }
}
}
// Rooms sync (7 November 2026): every two minutes while Orbit is open, with each paired room it can reach on the Wi-Fi.
LaunchedEffect(workspace) {
val finder = RoomFinder(appContext); finder.start()
try {
while (true) {
delay(120_000)
if (RoomLinks.links.none { it.on }) continue
withContext(Dispatchers.IO) { runCatching { RoomSync.round(appContext, workspace.scheduleDir, finder.found.map { it.second }) } }
}
} finally { finder.stop() }
}
// A channel of your own whose first plan was cut short, picked up again (set by the round below, run once setSmartSchedule exists).
var resumeNumber by remember { mutableStateOf<Int?>(null) }
// Keeps smart channels topped up in the background. A failure changes nothing on air.
@@ -77,6 +77,7 @@ class MainActivity : ComponentActivity() {
// The phone page's server runs only while Orbit is open (Create your own from a phone).
PhoneLink.init(this)
Profiles.load(this)
RoomLinks.load(this)
// The chosen look, before the first frame, so a light look never flashes navy.
OrbitTheme.load(this)
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(Navy.toArgb()))
@@ -158,7 +158,9 @@ internal object PhoneLink {
val parts = lines.first().split(' ')
if (parts.size < 2) return null
val headers = lines.drop(1).filter { ':' in it }.associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() }
val length = headers["content-length"]?.toIntOrNull()?.coerceIn(0, 65_536) ?: 0
// Rooms sync carries a family's changes, so it may be larger; everything else stays small.
val cap = if (parts[1].substringBefore('?') == "/room/sync") 2_000_000 else 65_536
val length = headers["content-length"]?.toIntOrNull()?.coerceIn(0, cap) ?: 0
val body = ByteArray(length).also { var read = 0; while (read < length) { val n = input.read(it, read, length - read); if (n < 0) break; read += n } }.toString(Charsets.UTF_8)
val path = parts[1].substringBefore('?')
val query = parts[1].substringAfter('?', "").split('&').filter { '=' in it }.associate { URLDecoder.decode(it.substringBefore('='), "UTF-8") to URLDecoder.decode(it.substringAfter('='), "UTF-8") }
@@ -219,6 +221,12 @@ internal object PhoneLink {
offerRoom(offer)
return json(out, 200, JSONObject().put("room", Rooms.name))
}
// Rooms sync between paired TVs: answered whenever Orbit is open, sealed with the pair's key, refused for anyone else.
if (r.path == "/room/sync" && r.method == "POST") {
val ctx = appContext ?: return json(out, 409, JSONObject())
val (status, reply) = runCatching { RoomSync.answer(ctx, Workspaces.current(ctx).scheduleDir, r.body, socket.inetAddress.hostAddress) }.getOrElse { 400 to JSONObject() }
return json(out, status, reply)
}
if (r.path.startsWith("/room/")) {
val offer = roomOffer ?: return json(out, 404, JSONObject().put("error", "That TV isn't adding a room right now."))
val (status, reply) = runCatching { offer.handle(r.method, r.path, r.body) }.getOrElse { 400 to JSONObject() }
@@ -43,7 +43,9 @@ internal enum class ProfileKind { Grown, Kids }
internal data class Profile(val id: String, val name: String, val picture: String, val kind: ProfileKind,
/** Kids only: the channels it sees. */
val channels: Set<Int> = emptySet(), val arcade: Boolean = true, val driveIn: Boolean = false)
val channels: Set<Int> = emptySet(), val arcade: Boolean = true, val driveIn: Boolean = false,
/** When it last changed, so paired rooms keep the newest (Rooms sync, 7 November 2026). 0 for a profile never changed. */
val updatedMs: Long = 0)
/** Kids' channels to start with, from the approved design: Tots, Junior, Wonder, PixelZ, ToonZ, Heroes, Rewind, Vortex, Terra, Wild. */
internal val KidsStartChannels = setOf(TOTS_NUMBER, 611, 612, 613, 605, 602, 604, VORTEX_NUMBER, 201, 203)
@@ -92,7 +94,7 @@ internal object Profiles {
/** Someone new (Family v2): a stable id of their own, so their Continue watching and Taste stay theirs. */
fun add(context: Context, name: String, kind: ProfileKind, picture: String): Profile {
val p = newProfile(name, kind, picture, all.map { it.id }.toSet())
val p = newProfile(name, kind, picture, all.map { it.id }.toSet()).copy(updatedMs = System.currentTimeMillis())
all = all + p; prefs(context).edit().putString("profiles", encode(all)).apply()
return p
}
@@ -100,26 +102,39 @@ internal object Profiles {
fun remove(context: Context, id: String): Boolean {
val next = profilesWithout(all, id) ?: return false
all = next; if (current?.id == id) current = null
prefs(context).edit().putString("profiles", encode(all)).apply()
// Remembered as removed, so a paired room's copy doesn't bring them back.
tombstones = tombstones + (id to System.currentTimeMillis())
prefs(context).edit().putString("profiles", encode(all)).putString("tombstones", JSONObject(tombstones).toString()).apply()
return true
}
/** Profiles removed, by id, with when: kept so Rooms sync can pass the removal on. */
var tombstones: Map<String, Long> = emptyMap()
private set
/** Everyone and every removal as a paired room sent them, merged and saved (Rooms sync). */
fun replaceFromSync(context: Context, profiles: List<Profile>, tombs: Map<String, Long>) {
all = profiles; tombstones = tombs
if (current != null && profiles.none { it.id == current?.id }) current = null else current?.let { c -> chosen = profiles.first { it.id == c.id } }
prefs(context).edit().putString("profiles", encode(all)).putString("tombstones", JSONObject(tombs).toString()).apply()
}
private fun prefs(context: Context) = context.getSharedPreferences("orbit_profiles", Context.MODE_PRIVATE)
fun load(context: Context) {
all = runCatching { decode(prefs(context).getString("profiles", null)!!) }.getOrDefault(DefaultProfiles)
kidsOn = prefs(context).getBoolean("kids_on", true)
store = prefs(context)
tombstones = runCatching { JSONObject(prefs(context).getString("tombstones", "{}")!!).let { o -> o.keys().asSequence().associateWith { o.getLong(it) } } }.getOrDefault(emptyMap())
chosen = prefs(context).getString("current", null)?.let { id -> all.firstOrNull { it.id == id } }
?.takeIf { it.kind == ProfileKind.Kids || !AfterDarkLock.pinSet || AfterDarkLock.unlocked }
}
fun update(context: Context, changed: Profile) {
fun update(context: Context, edited: Profile) {
val changed = edited.copy(updatedMs = System.currentTimeMillis())
all = all.map { if (it.id == changed.id) changed else it }
if (current?.id == changed.id) current = changed
prefs(context).edit().putString("profiles", encode(all)).apply()
}
fun encode(list: List<Profile>) = JSONArray(list.map { p ->
JSONObject().put("id", p.id).put("name", p.name).put("picture", p.picture).put("kind", p.kind.name)
.put("channels", JSONArray(p.channels.sorted())).put("arcade", p.arcade).put("driveIn", p.driveIn)
.put("channels", JSONArray(p.channels.sorted())).put("arcade", p.arcade).put("driveIn", p.driveIn).put("u", p.updatedMs)
}).toString()
fun decode(text: String): List<Profile> {
val a = JSONArray(text)
@@ -127,7 +142,7 @@ internal object Profiles {
val o = a.getJSONObject(i); val ch = o.optJSONArray("channels")
// "Grown-ups" became "Adult" (Paul, 6 November 2026): a profile saved under the old name takes the new one.
Profile(o.getString("id"), o.getString("name").let { if (it == "Grown-ups") "Adult" else it }, o.getString("picture"), ProfileKind.valueOf(o.getString("kind")),
ch?.let { c -> (0 until c.length()).map { c.getInt(it) }.toSet() }.orEmpty(), o.optBoolean("arcade", true), o.optBoolean("driveIn", false))
ch?.let { c -> (0 until c.length()).map { c.getInt(it) }.toSet() }.orEmpty(), o.optBoolean("arcade", true), o.optBoolean("driveIn", false), o.optLong("u"))
}.takeIf { list -> list.any { it.kind == ProfileKind.Grown } } ?: DefaultProfiles
}
}
@@ -0,0 +1,136 @@
package tv.orbit.classic
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.Base64
/**
* Rooms sync (Paul, 7 November 2026): rooms that have paired keep each other's family up to date on their own. Pairing (Add a
* room, Bring in from another room) leaves both TVs with a shared key; after that, while Orbit is open on both, they exchange
* what's changed every couple of minutes over the home Wi-Fi only: profiles (and removals), the PIN's salted hash, Continue
* watching and Taste. Everything is sealed with the pair's key (AES-GCM), dated, and merged, never overwritten: the same person
* by id with the newest change winning, Taste events by id, the latest place in a programme. Channels and schedules stay each
* room's own, and each room keeps its own unlock.
*/
internal class RoomLink(val id: String, val room: String, val key: ByteArray, val on: Boolean = true, val lastSyncMs: Long = 0, val address: String? = null) {
fun toJson(): JSONObject = JSONObject().put("id", id).put("room", room).put("key", Base64.getEncoder().encodeToString(key)).put("on", on)
.put("last", lastSyncMs).put("address", address ?: JSONObject.NULL)
companion object {
fun of(o: JSONObject) = RoomLink(o.getString("id"), o.optString("room").take(30), Base64.getDecoder().decode(o.getString("key")), o.optBoolean("on", true),
o.optLong("last"), o.optString("address").takeIf { !o.isNull("address") && it.isNotBlank() })
/** The lasting key and its id, worked out the same way on both TVs from the pairing's sealing key. */
fun fromPairing(seal: ByteArray, room: String): RoomLink {
val key = RoomCrypto.hmac(seal, "orbit-room-link\u0001".toByteArray())
val id = RoomCrypto.hmac(key, "orbit-room-link-id\u0001".toByteArray()).take(8).joinToString("") { "%02x".format(it) }
return RoomLink(id, room.take(30).ifBlank { "Another room" }, key)
}
}
}
internal object RoomLinks {
var links by mutableStateOf<List<RoomLink>>(emptyList())
private set
private var prefs: android.content.SharedPreferences? = null
fun load(context: Context) {
prefs = context.applicationContext.getSharedPreferences("orbit_room_links", Context.MODE_PRIVATE)
links = runCatching { JSONArray(prefs!!.getString("links", "[]")).let { a -> (0 until a.length()).map { RoomLink.of(a.getJSONObject(it)) } } }.getOrDefault(emptyList())
}
@Synchronized private fun save(next: List<RoomLink>) { links = next; prefs?.edit()?.putString("links", JSONArray(next.map { it.toJson() }).toString())?.apply() }
/** A pairing finished: keep its lasting key (the same pair pairing again replaces it). */
fun paired(seal: ByteArray, room: String) { val l = RoomLink.fromPairing(seal, room); save(links.filter { it.id != l.id && it.room != l.room } + l) }
fun setOn(id: String, on: Boolean) = save(links.map { if (it.id == id) RoomLink(it.id, it.room, it.key, on, it.lastSyncMs, it.address) else it })
fun synced(id: String, atMs: Long, address: String?) = save(links.map { if (it.id == id) RoomLink(it.id, it.room, it.key, it.on, atMs, address ?: it.address) else it })
fun of(id: String) = links.firstOrNull { it.id == id }
}
/** How far apart two TVs' clocks and a message's travel may be; older messages are refused, so one can't be replayed later. */
internal const val ROOM_SYNC_WINDOW_MS = 10 * 60_000L
/** Taste and Continue watching changes are sent from a little before the last sync, so nothing falls in a gap. */
private const val ROOM_SYNC_OVERLAP_MS = 60 * 60_000L
/** Profiles from two rooms: per person the newest change, minus anyone removed after their last change. */
internal fun mergeProfilesSync(here: List<Profile>, hereTombs: Map<String, Long>, there: List<Profile>, thereTombs: Map<String, Long>): Pair<List<Profile>, Map<String, Long>> {
val tombs = (hereTombs.keys + thereTombs.keys).associateWith { maxOf(hereTombs[it] ?: 0, thereTombs[it] ?: 0) }
val byId = LinkedHashMap<String, Profile>()
for (p in here + there) { val have = byId[p.id]; if (have == null || p.updatedMs > have.updatedMs) byId[p.id] = p }
val kept = byId.values.filter { p -> (tombs[p.id] ?: -1) < p.updatedMs || (tombs[p.id] == null) }.take(MAX_PROFILES)
// Someone must stay able to change things: if the merge would leave no grown-up, keep this room's list as it is.
return if (kept.any { it.kind == ProfileKind.Grown }) kept to tombs else here to hereTombs
}
internal object RoomSync {
private val seen = ArrayDeque<String>()
/** What this room sends: the family as it is, and Continue watching and Taste changed since [sinceMs]. */
fun state(context: Context, scheduleDir: File, sinceMs: Long, nowMs: Long): JSONObject {
val files = JSONObject()
scheduleDir.listFiles { f -> Regex("continue-[A-Za-z0-9]{1,40}\\.json").matches(f.name) }?.forEach { files.put(it.name, it.readText()) }
File(scheduleDir, "taste").listFiles()?.forEach { f ->
when {
f.name.endsWith(".events.jsonl") -> f.readLines().filter { l -> TasteEvent.of(l)?.let { it.atMs >= sinceMs - ROOM_SYNC_OVERLAP_MS } == true }
.takeIf { it.isNotEmpty() }?.let { files.put("taste/${f.name}", it.joinToString("\n") + "\n") }
f.name.endsWith(".state.json") -> files.put("taste/${f.name}", f.readText())
}
}
return JSONObject().put("v", 1).put("room", Rooms.name).put("at", nowMs).put("nonce", java.util.UUID.randomUUID().toString()).put("since", sinceMs)
.put("profiles", Profiles.encode(Profiles.all)).put("tombs", JSONObject(Profiles.tombstones)).put("lock", AfterDarkLock.shared(context)).put("files", files)
}
/** Opens and checks a sealed message: the pair's key, a fresh time, a nonce not seen before. Null when it fails any of them. */
@Synchronized fun open(link: RoomLink, sealed: String, nowMs: Long): JSONObject? {
val o = runCatching { JSONObject(String(RoomCrypto.open(link.key, sealed))) }.getOrNull() ?: return null
if (o.optInt("v") != 1 || kotlin.math.abs(nowMs - o.optLong("at")) > ROOM_SYNC_WINDOW_MS) return null
val nonce = o.optString("nonce"); if (nonce.isBlank() || nonce in seen) return null
seen.addLast(nonce); while (seen.size > 200) seen.removeFirst()
return o
}
/** Takes in what a paired room sent: profiles and removals, the PIN, Continue watching and Taste, each merged. */
fun merge(context: Context, scheduleDir: File, o: JSONObject, nowMs: Long) {
val there = runCatching { Profiles.decode(o.getString("profiles")) }.getOrNull()
val thereTombs = o.optJSONObject("tombs")?.let { t -> t.keys().asSequence().associateWith { t.getLong(it) } }.orEmpty()
if (there != null) {
val (merged, tombs) = mergeProfilesSync(Profiles.all, Profiles.tombstones, there, thereTombs)
if (merged != Profiles.all || tombs != Profiles.tombstones) Profiles.replaceFromSync(context, merged, tombs)
tombs.keys.filter { id -> merged.none { it.id == id } }.forEach { runCatching { forgetProfileData(scheduleDir, it) } }
}
o.optJSONObject("lock")?.let { AfterDarkLock.takeShared(context, it) }
o.optJSONObject("files")?.let { files -> runCatching { mergeFamilyFiles(scheduleDir, files, nowMs) } }
ContinueWatching.load(scheduleDir, Profiles.current?.id)
}
/** The answering TV's side of /room/sync: returns the status and reply. */
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()
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)
RoomLinks.synced(link.id, nowMs, from)
android.util.Log.i("OrbitRooms", "sync answered link=${link.id.take(4)}")
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. */
fun round(context: Context, scheduleDir: File, found: List<String>, nowMs: Long = System.currentTimeMillis()) {
for (link in RoomLinks.links.filter { it.on }) {
for (address in (listOfNotNull(link.address) + found).distinct()) {
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()) }
.getOrNull() ?: continue
if (status != 200) continue
val o = runCatching { open(link, JSONObject(text).getString("sealed"), System.currentTimeMillis()) }.getOrNull() ?: continue
merge(context, scheduleDir, o, System.currentTimeMillis())
RoomLinks.synced(link.id, nowMs, address)
android.util.Log.i("OrbitRooms", "sync done link=${link.id.take(4)}")
break
}
}
}
}
@@ -39,7 +39,7 @@ internal object RoomCrypto {
fun shared(mine: KeyPair, theirs: String): ByteArray = KeyAgreement.getInstance("ECDH").run {
init(mine.private); doPhase(KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(theirs))), true); generateSecret()
}
private fun hmac(key: ByteArray, data: ByteArray): ByteArray = Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(key, "HmacSHA256")); doFinal(data) }
internal fun hmac(key: ByteArray, data: ByteArray): ByteArray = Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(key, "HmacSHA256")); doFinal(data) }
/** Two keys from the agreed secret and the code: one to prove the code, one to seal what's copied. */
fun keys(secret: ByteArray, code: String, transcript: String): Pair<ByteArray, ByteArray> {
val prk = hmac(MessageDigest.getInstance("SHA-256").digest(transcript.toByteArray()), secret + code.toByteArray())
@@ -272,6 +272,8 @@ internal class RoomOffer(val code: String, val untilMs: Long, private val room:
val text = bundle().toString()
if (!RoomBundle.limit(text)) return 413 to JSONObject()
state = State.Sent
// Paired from here on: both TVs keep a lasting key for Rooms sync.
runCatching { RoomLinks.paired(seal!!, joining ?: "A new TV") }
android.util.Log.i("OrbitRooms", "copy sent bytes=${text.length}")
200 to JSONObject().put("sealed", RoomCrypto.seal(seal!!, text.toByteArray()))
}
@@ -320,7 +322,8 @@ internal class RoomJoin(private val call: (method: String, path: String, body: S
val (status, text) = call("GET", "/room/copy", "")
when (status) {
202 -> null
200 -> JSONObject(String(RoomCrypto.open(seal!!, JSONObject(text).getString("sealed")))).also { check(it.getInt("version") == 1) }
200 -> JSONObject(String(RoomCrypto.open(seal!!, JSONObject(text).getString("sealed")))).also { check(it.getInt("version") == 1)
runCatching { RoomLinks.paired(seal!!, otherRoom ?: "Another room") } }
else -> error(JSONObject(text).optString("error").ifBlank { "The copy didn't arrive." })
}
}
@@ -406,6 +406,13 @@ private fun RoomsDetail(firstSwitch: FocusRequester, modifier: Modifier) {
SettingLine("Add a room", "Set up Orbit on another TV in your home by copying this one: channels, profiles, look and more. Your password never travels.") {
OrbitButton("Add a room", onClick = { adding = true })
}
// Rooms sync (7 November 2026): each paired room, when it last synced, and a switch to stop.
RoomLinks.links.forEach { link ->
val ago = if (link.lastSyncMs == 0L) "Not synced yet: open Orbit on both TVs" else "Synced ${((System.currentTimeMillis() - link.lastSyncMs) / 60_000).coerceAtLeast(0)} min ago"
SettingLine("Sync with ${link.room}", "$ago. Profiles, the PIN, Continue watching and what Orbit has learnt. Channels and schedules stay each room's own.") {
OnOff(link.on, Modifier, onClick = { RoomLinks.setOn(link.id, !link.on) })
}
}
Rooms.joined.forEach { (room, at) ->
val day = java.time.Instant.ofEpochMilli(at).atZone(java.time.ZoneId.systemDefault()).toLocalDate()
SettingLine(room, "Copied this Orbit's set-up on ${day.dayOfMonth} ${day.month.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.UK)}. Not connected: it plans its own schedules.") {}
@@ -0,0 +1,53 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
/** Rooms sync (7 November 2026): newest change per person, removals stick, and only the paired room's fresh messages count. */
class RoomSyncTest {
private val paul = Profile("grown", "Paul", "sil-blue", ProfileKind.Grown, updatedMs = 100)
private val kids = Profile("kids", "Amelia", "ollie", ProfileKind.Kids, DefaultProfiles[1].channels, updatedMs = 100)
@Test fun aNewProfileArrivesAndTheNewestChangeWins() {
val cheryl = Profile("pcher01", "Cheryl", "sil-pink", ProfileKind.Grown, updatedMs = 300)
val renamedHere = paul.copy(name = "Paul D", updatedMs = 500)
val (merged, _) = mergeProfilesSync(listOf(renamedHere, kids), emptyMap(), listOf(paul, kids, cheryl), emptyMap())
assertEquals(listOf("grown", "kids", "pcher01"), merged.map { it.id })
assertEquals("Paul D", merged.first().name)
val (back, _) = mergeProfilesSync(listOf(paul, kids, cheryl), emptyMap(), listOf(renamedHere, kids), emptyMap())
assertEquals("Paul D", back.first { it.id == "grown" }.name)
assertEquals(3, back.size)
}
@Test fun aRemovalSticksUnlessTheProfileChangedAfterIt() {
val cheryl = Profile("pcher01", "Cheryl", "sil-pink", ProfileKind.Grown, updatedMs = 300)
val (gone, tombs) = mergeProfilesSync(listOf(paul, kids, cheryl), emptyMap(), listOf(paul, kids), mapOf("pcher01" to 400L))
assertEquals(listOf("grown", "kids"), gone.map { it.id }); assertEquals(400L, tombs["pcher01"])
// Edited in the other room after the removal: the newer edit keeps them.
val (kept, _) = mergeProfilesSync(listOf(paul, kids), mapOf("pcher01" to 400L), listOf(cheryl.copy(updatedMs = 500)), emptyMap())
assertTrue(kept.any { it.id == "pcher01" })
// A merge never leaves the house without a grown-up.
val (safe, _) = mergeProfilesSync(listOf(paul, kids), emptyMap(), emptyList(), mapOf("grown" to 900L))
assertTrue(safe.any { it.kind == ProfileKind.Grown })
}
@Test fun bothTvsWorkOutTheSameLinkAndOnlyItOpensMessages() {
val seal = ByteArray(32) { it.toByte() }
val a = RoomLink.fromPairing(seal, "Living Room"); val b = RoomLink.fromPairing(seal, "Upstairs")
assertEquals(a.id, b.id); assertArrayEquals(a.key, b.key)
val stranger = RoomLink.fromPairing(ByteArray(32) { 7 }, "Next door")
val now = 1_794_000_000_000L
fun msg(at: Long, nonce: String) = RoomCrypto.seal(a.key, JSONObject().put("v", 1).put("at", at).put("nonce", nonce).toString().toByteArray())
assertNotNull(RoomSync.open(b, msg(now, "n1"), now))
assertNull("the same message twice is refused", RoomSync.open(b, msg(now, "n1"), now))
assertNull("too old", RoomSync.open(b, msg(now - ROOM_SYNC_WINDOW_MS - 1, "n2"), now))
assertNull("another pair's key", RoomSync.open(stranger, msg(now, "n3"), now))
assertNull("tampered", RoomSync.open(b, msg(now, "n4").dropLast(4) + "AAAA", now))
}
@Test fun profilesKeepTheirChangeTimeWhenSaved() {
val back = Profiles.decode(Profiles.encode(listOf(paul.copy(updatedMs = 1234), kids)))
assertEquals(1234L, back.first().updatedMs)
}
}