From 21f266814d7d7e0fdd195821134488461f819028 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Mon, 9 Nov 2026 14:38:38 +0000 Subject: [PATCH] Taste Stage 2: real watching recorded, end-of-programme tune-ins worth nothing, Stage 1 kept Every watching signal now records the programme's length, the share watched and the airing. Finished needs at least half of the programme before its last five minutes; less is the new caught-end, with no weight. A signal counts once per airing, and another airing or day is a separate viewing. Stage 1 lines are never rewritten: tasteWeight reads them fairly. Events from before the two-copies fix (8 Nov 09:17) count nothing, and an old finished counts by its minutes. On a separate branch from the verified 0.123.0, not built into it. Co-Authored-By: Claude Opus 5.5 --- .../src/main/java/tv/orbit/classic/Taste.kt | 69 +++++++++++++--- .../orbit/classic/TasteForwardCompatTest.kt | 2 +- .../java/tv/orbit/classic/TasteStage2Test.kt | 80 +++++++++++++++++++ 3 files changed, 137 insertions(+), 14 deletions(-) create mode 100644 android/app/src/test/java/tv/orbit/classic/TasteStage2Test.kt diff --git a/android/app/src/main/java/tv/orbit/classic/Taste.kt b/android/app/src/main/java/tv/orbit/classic/Taste.kt index f3dd5531..42d91e07 100644 --- a/android/app/src/main/java/tv/orbit/classic/Taste.kt +++ b/android/app/src/main/java/tv/orbit/classic/Taste.kt @@ -21,6 +21,11 @@ internal enum class TasteKind(val key: String, val weight: Double) { Stayed("stayed", 1.0), /** Under five minutes, then moved on. Recorded with no weight: a short visit never means dislike on its own. */ Brief("brief", 0.0), + /** + * Stage 2 (9 November 2026): tuned in near the end. The programme reached its last five minutes, but less than half of what + * came before was watched, so it isn't "finished". Kept, with no weight. + */ + CaughtEnd("caught-end", 0.0), /** Taken off Continue watching: tidying, not dislike. */ Removed("removed", 0.0); companion object { fun of(key: String) = entries.firstOrNull { it.key == key } } @@ -37,12 +42,15 @@ internal const val TASTE_BRIEF_MS = 5 * 60_000L /** One signal. [id] is random so two rooms' logs can later be joined without duplicates (Rooms sync is not built yet). */ internal class TasteEvent(val id: String, val profile: String, val kind: TasteKind, val itemId: String, val seriesId: String?, val title: String, val channel: Int?, val atMs: Long, val watchedMs: Long?, val source: String, + /** Stage 2 (9 November 2026), when known: the programme's length, the share of it watched, and which airing it was. */ + val runtimeMs: Long? = null, val percent: Int? = null, val airingMs: Long? = null, /** Fields a newer Orbit added that this one doesn't know (9 November 2026): carried through untouched, never dropped. */ val extras: JSONObject? = null) { fun toLine(): String = JSONObject().apply { extras?.let { e -> e.keys().forEach { k -> put(k, e.get(k)) } } } .put("v", TASTE_SCHEMA).put("id", id).put("p", profile).put("k", kind.key).put("i", itemId) .put("s", seriesId ?: JSONObject.NULL).put("t", title.take(160)).put("c", channel ?: JSONObject.NULL).put("w", atMs) - .put("ms", watchedMs ?: JSONObject.NULL).put("src", source.take(24)).toString() + .put("ms", watchedMs ?: JSONObject.NULL).put("src", source.take(24)) + .apply { runtimeMs?.let { put("rt", it) }; percent?.let { put("pct", it) }; airingMs?.let { put("a", it) } }.toString() companion object { /** A line back, or null when it's damaged or from a newer schema: skipped, never fatal. */ fun of(line: String): TasteEvent? = runCatching { @@ -52,16 +60,41 @@ internal class TasteEvent(val id: String, val profile: String, val kind: TasteKi TasteEvent(o.getString("id"), o.getString("p"), TasteKind.of(o.getString("k")) ?: return null, item, o.optString("s").takeIf { !o.isNull("s") && EmbyClient.validId(it) }, o.optString("t"), if (o.isNull("c")) null else o.optInt("c"), o.getLong("w"), if (o.isNull("ms")) null else o.optLong("ms"), o.optString("src"), + if (o.has("rt")) o.optLong("rt") else null, if (o.has("pct")) o.optInt("pct") else null, if (o.has("a")) o.optLong("a") else null, JSONObject().also { e -> o.keys().forEach { k -> if (k !in TASTE_KNOWN_FIELDS) e.put(k, o.get(k)) } }.takeIf { it.length() > 0 }) }.getOrNull() } } -/** True when [event] repeats one already in [recent]: the same kind, title and profile within [TASTE_DUPLICATE_MS]. */ +/** + * True when [event] repeats one already in [recent]: the same kind, title and profile within [TASTE_DUPLICATE_MS], or (Stage 2) + * the same kind on the same airing at any time. Watching the same title again on another airing or another day is a new + * viewing and counts again. + */ internal fun tasteDuplicate(recent: List, event: TasteEvent): Boolean = - recent.any { it.id == event.id || (it.profile == event.profile && it.kind == event.kind && it.itemId == event.itemId && kotlin.math.abs(it.atMs - event.atMs) < TASTE_DUPLICATE_MS) } + recent.any { it.id == event.id || (it.profile == event.profile && it.kind == event.kind && it.itemId == event.itemId && + (kotlin.math.abs(it.atMs - event.atMs) < TASTE_DUPLICATE_MS || (event.airingMs != null && it.airingMs == event.airingMs))) } -internal val TASTE_KNOWN_FIELDS = setOf("v", "id", "p", "k", "i", "s", "t", "c", "w", "ms", "src") +/** + * Before this moment (8 November 2026, 09:17, when 0.108.104 stopped two copies of Orbit running at once), the watching + * signals were unreliable: the two copies took turns, so brief visits repeated every ten minutes and "finished" fired on + * tune-ins. Those events are kept as they were, but count for nothing. + */ +internal const val TASTE_RELIABLE_FROM_MS = 1_794_129_421_000L +/** Finished means at least half of the programme before its last five minutes was watched. */ +internal const val TASTE_FINISHED_SHARE = 0.5 + +/** + * What an event counts for (Stage 2, 9 November 2026). Stage 1 events are never rewritten; this reads them fairly. A + * Stage 1 "finished" has no share recorded, so its minutes decide: under 5 counts nothing, under 20 counts as a stay. + */ +internal fun tasteWeight(e: TasteEvent): Double = when { + e.source == "watching" && e.atMs < TASTE_RELIABLE_FROM_MS -> 0.0 + e.kind == TasteKind.Finished && e.percent == null -> (e.watchedMs ?: 0L).let { if (it < TASTE_BRIEF_MS) 0.0 else if (it < TASTE_STAYED_MS) TasteKind.Stayed.weight else e.kind.weight } + else -> e.kind.weight +} + +internal val TASTE_KNOWN_FIELDS = setOf("v", "id", "p", "k", "i", "s", "t", "c", "w", "ms", "src", "rt", "pct", "a") /** * The log's lines kept within its bounds, keeping what this Orbit can't read (9 November 2026): a line from a newer Orbit @@ -119,13 +152,17 @@ internal class TasteWatch { if (key != k) { out += stop() key = k; itemId = show.media.item.id; this.seriesId = seriesId; title = show.media.item.title; this.channel = channel - firstSeenMs = nowMs; stayed = false; finished = false; chosen = chose + firstSeenMs = nowMs; stayed = false; finished = false; chosen = chose; runtimeMs = show.media.durationMs } lastSeenMs = nowMs if (chose) chosen = true val watched = lastSeenMs - firstSeenMs if (!stayed && !chosen && watched >= TASTE_STAYED_MS) { stayed = true; out += Triple(TasteKind.Stayed, itemId, watched) } - if (!finished && positionMs >= show.media.durationMs - CONTINUE_END_MS) { finished = true; out += Triple(TasteKind.Finished, itemId, watched) } + if (!finished && positionMs >= show.media.durationMs - CONTINUE_END_MS) { + finished = true + val before = (show.media.durationMs - CONTINUE_END_MS).coerceAtLeast(1L) + out += Triple(if (watched >= before * TASTE_FINISHED_SHARE) TasteKind.Finished else TasteKind.CaughtEnd, itemId, watched) + } return out } /** Watching stopped, or moved on: a short visit is noted as brief, with no weight. */ @@ -136,6 +173,9 @@ internal class TasteWatch { return if (!finished && !chosen && watched < TASTE_BRIEF_MS) listOf(Triple(TasteKind.Brief, itemId, watched)) else emptyList() } val current get() = key?.let { Triple(itemId, seriesId, title) } + /** The airing being followed (its start) and its length, for the Stage 2 facts on each signal. */ + val airingMs get() = key?.second + var runtimeMs = 0L; private set val currentChannel get() = channel } @@ -184,6 +224,7 @@ internal class TasteStore(val directory: File) { val all = events(profile.id); val s = state(profile) return JSONObject().put("profile", profile.id).put("class", profile.kind.name).put("personalise", s.personalise) .put("events", all.size).put("byKind", JSONObject(TasteKind.entries.associate { k -> k.key to all.count { it.kind == k } })) + .put("weighted", all.sumOf(::tasteWeight)).put("countingNothing", all.count { tasteWeight(it) == 0.0 }) .put("stale", all.count { !known(it.itemId) }).put("suppressed", s.suppressions.size).put("resetAt", s.resetAtMs) .put("latest", JSONArray(all.takeLast(20).reversed().map { JSONObject().put("kind", it.kind.key).put("title", it.title).put("channel", it.channel ?: JSONObject.NULL).put("at", it.atMs) })) } @@ -206,11 +247,13 @@ internal object Taste { } fun record(kind: TasteKind, itemId: String, seriesId: String?, title: String, channel: Int?, source: String, watchedMs: Long? = null, - profile: Profile? = Profiles.current, nowMs: Long = System.currentTimeMillis()) { + profile: Profile? = Profiles.current, nowMs: Long = System.currentTimeMillis(), runtimeMs: Long? = null, airingMs: Long? = null) { val s = store ?: return; val p = profile ?: return if (!EmbyClient.validId(itemId)) return if (kind == TasteKind.Chose) lastChosen = itemId to nowMs - runCatching { s.record(p, TasteEvent(java.util.UUID.randomUUID().toString(), p.id, kind, itemId, seriesId, title, channel, nowMs, watchedMs, source)) } + val percent = if (watchedMs != null && runtimeMs != null && runtimeMs > 0) (watchedMs * 100 / runtimeMs).toInt().coerceIn(0, 100) else null + runCatching { s.record(p, TasteEvent(java.util.UUID.randomUUID().toString(), p.id, kind, itemId, seriesId, title, channel, nowMs, watchedMs, source, + runtimeMs?.takeIf { it > 0 }, percent, airingMs)) } } /** Whose watching [watch] is following: a profile switch closes it under the profile that was watching. */ @@ -222,15 +265,15 @@ internal object Taste { val chose = lastChosen?.let { (id, at) -> id == show.media.item.id && nowMs - at < 30 * 60_000L } == true // What was on before, for a brief visit noted as the programme changes. val (_, prevSeries, prevTitle) = watch.current ?: Triple("", null, "") - val prevChannel = watch.currentChannel + val prevChannel = watch.currentChannel; val prevAiring = watch.airingMs; val prevRuntime = watch.runtimeMs watch.observe(channel, show, seriesId, positionMs, chose, nowMs).forEach { (kind, item, ms) -> - if (item == show.media.item.id && kind != TasteKind.Brief) record(kind, item, seriesId, show.media.item.title, channel, "watching", ms, profile, nowMs) - else record(kind, item, prevSeries, prevTitle, prevChannel, "watching", ms, profile, nowMs) + if (item == show.media.item.id && kind != TasteKind.Brief) record(kind, item, seriesId, show.media.item.title, channel, "watching", ms, profile, nowMs, show.media.durationMs, show.startMs) + else record(kind, item, prevSeries, prevTitle, prevChannel, "watching", ms, profile, nowMs, prevRuntime, prevAiring) } } @Synchronized fun stopped(nowMs: Long = System.currentTimeMillis()) { val (_, series, title) = watch.current ?: return - val channel = watch.currentChannel - watch.stop().forEach { (kind, item, ms) -> record(kind, item, series, title, channel, "watching", ms, watcher, nowMs) } + val channel = watch.currentChannel; val airing = watch.airingMs; val runtime = watch.runtimeMs + watch.stop().forEach { (kind, item, ms) -> record(kind, item, series, title, channel, "watching", ms, watcher, nowMs, runtime, airing) } } } diff --git a/android/app/src/test/java/tv/orbit/classic/TasteForwardCompatTest.kt b/android/app/src/test/java/tv/orbit/classic/TasteForwardCompatTest.kt index 14cf14e4..fb7c3258 100644 --- a/android/app/src/test/java/tv/orbit/classic/TasteForwardCompatTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/TasteForwardCompatTest.kt @@ -14,7 +14,7 @@ class TasteForwardCompatTest { // Today's line, a Stage 2 line with fields this version doesn't know, and a kind it doesn't know. private val today = """{"v":1,"id":"a1","p":"grown","k":"stayed","i":"4455505","s":null,"t":"Film","c":304,"w":${now - 3_000},"ms":1500000,"src":"watching"}""" private val newer = """{"v":1,"id":"b2","p":"grown","k":"finished","i":"4455506","s":null,"t":"Film 2","c":304,"w":${now - 2_000},"ms":4000000,"src":"watching","rt":5820000,"pct":69,"a":1794290000000}""" - private val unknownKind = """{"v":1,"id":"c3","p":"grown","k":"caught-end","i":"4455507","s":null,"t":"Film 3","c":304,"w":${now - 1_000},"ms":420000,"src":"watching","rt":5820000,"pct":7}""" + private val unknownKind = """{"v":1,"id":"c3","p":"grown","k":"future-kind","i":"4455507","s":null,"t":"Film 3","c":304,"w":${now - 1_000},"ms":420000,"src":"watching","rt":5820000,"pct":7}""" private fun fields(line: String) = JSONObject(line).let { o -> o.keys().asSequence().associateWith { o.get(it).toString() } } @Test fun tidyingKeepsEverything() { diff --git a/android/app/src/test/java/tv/orbit/classic/TasteStage2Test.kt b/android/app/src/test/java/tv/orbit/classic/TasteStage2Test.kt new file mode 100644 index 00000000..41fb2a2c --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/TasteStage2Test.kt @@ -0,0 +1,80 @@ +package tv.orbit.classic + +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +/** Taste Stage 2 (Paul, 9 November 2026): Stage 1 kept as it is, real watching recorded, tune-ins near the end worth nothing. */ +class TasteStage2Test { + @get:Rule val tmp = TemporaryFolder() + private val minute = 60_000L + private val after = TASTE_RELIABLE_FROM_MS + 86_400_000L + private val adult = Profile("grown", "Adult", "sil-blue", ProfileKind.Grown) + private fun show(minutes: Long, start: Long, id: String = "6048906") = + SampleBroadcast(ScheduledMedia(SampleItem("Fictional Film", "Movie", minutes, "", id, minutes * minute), "src", minutes * minute), start) + /** Half-minute notes from [fromMin] into the programme to its end, as the TV sends them. */ + private fun watch(s: SampleBroadcast, fromMin: Long, channel: Int = 304) { + var at = fromMin * minute + while (at <= s.media.durationMs) { Taste.watching(channel, s, null, at, s.startMs + at, adult); at += 30_000L } + Taste.stopped(s.startMs + s.media.durationMs + 1) + } + + @Test fun stage1LinesAreKeptExactly() { + // The shapes in Paul's own log (titles made up), including the night before the two-copies fix. + val lines = listOf( + """{"v":1,"id":"dcf536a5-4384-4b1e-ab08-f67d00d67ae9","p":"grown","k":"finished","i":"4455505","s":"4455505","t":"Fictional Film","c":601,"w":1794090780777,"ms":0,"src":"watching"}""", + """{"v":1,"id":"68a49973-c81f-4695-8ce8-b7d6d48b3503","p":"grown","k":"brief","i":"7408042","s":null,"t":"Show / S1 E1 / Pilot","c":304,"w":1794092980560,"ms":0,"src":"watching"}""", + """{"v":1,"id":"0a6e7f6b-1111-4c1e-9d55-2f1a3b4c5d6e","p":"grown","k":"saved","i":"7408043","s":null,"t":"Another Film","c":304,"w":1794200000000,"ms":null,"src":"reminder"}""") + // Field for field (Android keeps the key order; the JVM's org.json used in tests doesn't, so compare the content). + fun same(a: String, b: String): Boolean { val x = org.json.JSONObject(a); val y = org.json.JSONObject(b) + return x.keys().asSequence().toSet() == y.keys().asSequence().toSet() && x.keys().asSequence().all { x.get(it).toString() == y.get(it).toString() } } + for (l in lines) assertTrue(l, same(l, TasteEvent.of(l)!!.toLine())) + val merged = compactTaste(lines.mapNotNull(TasteEvent::of), 1_794_300_000_000L).map { it.toLine() } + assertEquals(lines.size, merged.size); lines.zip(merged).forEach { (a, b) -> assertTrue(a, same(a, b)) } + } + + @Test fun tuningInNearTheEndIsCaughtEndNotFinished() { + Taste.attach(tmp.root, after) + watch(show(97, after), fromMin = 85) // the last 12 minutes of a film + val e = Taste.store!!.events("grown") + assertEquals(listOf(TasteKind.CaughtEnd), e.map { it.kind }) + assertEquals(0.0, tasteWeight(e.single()), 0.0) + assertEquals(97 * minute, e.single().runtimeMs); assertEquals(after, e.single().airingMs) + assertTrue("${e.single().percent}", e.single().percent!! in 5..13) // 7 of its 97 minutes when the end arrived + } + + @Test fun watchingMostOfItIsFinishedWithItsShare() { + Taste.attach(tmp.root, after) + watch(show(120, after), fromMin = 40) // 75 of the 115 minutes before the end: 65% + val kinds = Taste.store!!.events("grown").map { it.kind to it.percent } + assertTrue(kinds.toString(), TasteKind.Stayed in kinds.map { it.first }) + val finished = Taste.store!!.events("grown").single { it.kind == TasteKind.Finished } + assertTrue(finished.percent!! in 60..66); assertEquals(2.0, tasteWeight(finished), 0.0) + } + + @Test fun aShortEpisodeWatchedWholeIsFinished() { + Taste.attach(tmp.root, after) + watch(show(22, after, "7408042"), fromMin = 0) + assertTrue(Taste.store!!.events("grown").any { it.kind == TasteKind.Finished }) + } + + @Test fun stage1EventsAreReadFairly() { + fun e(kind: TasteKind, at: Long, ms: Long?, src: String = "watching") = TasteEvent("x$at$kind", "grown", kind, "4455505", null, "t", 304, at, ms, src) + val before = TASTE_RELIABLE_FROM_MS - 1 + assertEquals(0.0, tasteWeight(e(TasteKind.Finished, before, 58 * minute)), 0.0) // the two-copies night counts for nothing + assertEquals(0.0, tasteWeight(e(TasteKind.Stayed, before, 25 * minute)), 0.0) + assertEquals(3.0, tasteWeight(e(TasteKind.Chose, before, null, "catchup")), 0.0) // a deliberate pick wasn't affected + assertEquals(0.0, tasteWeight(e(TasteKind.Finished, after, 0)), 0.0) // tuned in at the end + assertEquals(1.0, tasteWeight(e(TasteKind.Finished, after, 8 * minute + 30_000)), 0.0) + assertEquals(2.0, tasteWeight(e(TasteKind.Finished, after, 58 * minute)), 0.0) + } + + @Test fun oneSignalPerAiringButARepeatViewingCounts() { + fun e(id: String, at: Long, airing: Long?) = TasteEvent(id, "grown", TasteKind.Stayed, "4455505", null, "t", 304, at, 25 * minute, "watching", 97 * minute, 30, airing) + val first = e("a", after, after) + assertTrue(tasteDuplicate(listOf(first), e("b", after + 60 * minute, after))) // same airing, an hour later + assertFalse(tasteDuplicate(listOf(first), e("c", after + 26 * 60 * minute, after + 26 * 60 * minute))) // tomorrow's airing + assertTrue(tasteDuplicate(listOf(first), e("d", after + 5 * minute, null))) // the ten-minute rule still holds + } +}