Taste, Stage 1: profile-aware signals, recorded only
Each profile gets its own bounded, recoverable signal log (chose, finished, saved, stayed, brief with no weight, removed) in taste/<profile>.events.jsonl, with a state file for Personalise (on for Adult, off for Kids until an adult turns it on) and reversible suppressions. Events carry random ids and a schema version, ready for Rooms merging. Inspect and reset through the phone for adults. Nothing on screen, in schedules or in playback changes. 0.108.97. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,8 +9,8 @@ android {
|
||||
applicationId = "tv.orbit.classic"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 256
|
||||
versionName = "0.108.96-evening-rotation"
|
||||
versionCode = 257
|
||||
versionName = "0.108.97-taste-signals"
|
||||
}
|
||||
buildFeatures { compose = true }
|
||||
// The finished build for the TVs (Paul, 6 November 2026: the test build stuttered on the box). Not debuggable, so
|
||||
|
||||
@@ -266,7 +266,10 @@ internal fun CatchUpScreen(channels: List<SampleChannel>, session: EmbySampleSes
|
||||
Text("It stays in Catch Up until ${guideDayPrefix(c.entry.untilMs, now).trim().ifEmpty { "today" }} ${clock(c.entry.untilMs)}, from the start.", color = Muted, fontSize = 14.sp)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
OrbitButton("Remove", Modifier.focusRequester(removeFocus)) { ContinueWatching.remove(c.entry.channel.number, c.entry.show.startMs); removing = null }
|
||||
OrbitButton("Remove", Modifier.focusRequester(removeFocus)) {
|
||||
ContinueWatching.remove(c.entry.channel.number, c.entry.show.startMs); removing = null
|
||||
Taste.record(TasteKind.Removed, c.entry.show.media.item.id, null, c.entry.show.media.item.title, c.entry.channel.number, "continue")
|
||||
}
|
||||
OrbitButton("Keep it") { removing = null }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,9 +62,9 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
|
||||
}
|
||||
/** The sign-in headers for this kind of server. */
|
||||
internal fun authHeaders(token: String?): Map<String, String> = when (kind) {
|
||||
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.96\"") +
|
||||
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.97\"") +
|
||||
(token?.let { mapOf("X-Emby-Token" to it) } ?: emptyMap())
|
||||
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.96\"" +
|
||||
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.97\"" +
|
||||
(token?.let { ", Token=\"$it\"" } ?: ""))
|
||||
}
|
||||
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
|
||||
|
||||
@@ -370,15 +370,18 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
|
||||
// Continue watching (Paul, 7 November 2026): every half minute of watching notes where you are in the programme, live or
|
||||
// catching up, for whoever's watching; Catch Up offers it back once it has aired.
|
||||
LaunchedEffect(workspace, Profiles.current?.id) { withContext(Dispatchers.IO) { ContinueWatching.load(workspace.scheduleDir, Profiles.current?.id) } }
|
||||
// Taste, Stage 1: signals per profile, recorded only (Profile-Aware Director's Chair doc).
|
||||
LaunchedEffect(workspace) { withContext(Dispatchers.IO) { runCatching { Taste.attach(workspace.scheduleDir) } } }
|
||||
LaunchedEffect(session) {
|
||||
while (true) {
|
||||
delay(30_000)
|
||||
if (!watchingChannel || selectedNumber == DRIVE_IN_NUMBER) continue
|
||||
if (!watchingChannel || selectedNumber == DRIVE_IN_NUMBER) { withContext(Dispatchers.IO) { Taste.stopped() }; continue }
|
||||
val channel = scheduledChannels[selectedNumber] ?: continue
|
||||
val now = System.currentTimeMillis(); val at = now + channelClockOffset
|
||||
val show = runCatching { channel.at(at) }.getOrNull() ?: continue
|
||||
if (show.endMs - show.startMs < 10 * 60_000L) continue
|
||||
runCatching { withContext(Dispatchers.IO) { ContinueWatching.note(channel.number, show, at - show.startMs, now) } }
|
||||
runCatching { withContext(Dispatchers.IO) { Taste.watching(channel.number, show, channel.seriesIdAt(show.startMs), at - show.startMs, now) } }
|
||||
}
|
||||
}
|
||||
// A channel of your own whose first plan was cut short, picked up again (set by the round below, run once setSmartSchedule exists).
|
||||
@@ -450,6 +453,9 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
|
||||
if (mainDriveIn) { driveInVisits++; if (pendingDriveInWatch) { pendingDriveInWatch = false; watchingDriveIn = true } } else watchingDriveIn = false
|
||||
}
|
||||
fun saveTickets(changed: Map<Long, Int>) {
|
||||
// A new ticket saves its films for later (Taste, Stage 1).
|
||||
(changed.keys - tickets.keys).forEach { start -> driveInPlan?.let { plan -> driveInBills(plan).firstOrNull { it.startMs == start }?.entries?.forEach { e ->
|
||||
Taste.record(TasteKind.Saved, e.media.item.id, null, e.media.item.title, DRIVE_IN_NUMBER, "ticket") } } }
|
||||
tickets = changed
|
||||
val active = session ?: return
|
||||
scope.launch(Dispatchers.IO) { runCatching { scheduleStore.saveTickets(active.accountId, changed) } }
|
||||
@@ -758,18 +764,25 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
|
||||
CatchUpCard(entry, System.currentTimeMillis(), onDismiss = { catchUpOpen = null }, onWatch = {
|
||||
catchUpOpen = null
|
||||
// Still in Catch Up by the time OK is pressed: replay the channel from the programme's start.
|
||||
if (entry.show.startMs >= System.currentTimeMillis() - CATCH_UP_MS) tune(entry.channel.number, entry.offsetFrom(System.currentTimeMillis()))
|
||||
if (entry.show.startMs >= System.currentTimeMillis() - CATCH_UP_MS) {
|
||||
tune(entry.channel.number, entry.offsetFrom(System.currentTimeMillis()))
|
||||
Taste.record(TasteKind.Chose, entry.show.media.item.id, (entry.channel as? ScheduledChannel)?.seriesIdAt(entry.show.startMs), entry.show.media.item.title, entry.channel.number, "catchup")
|
||||
}
|
||||
})
|
||||
}
|
||||
val picture = @Composable { GuidePicture(liveSession, liveChannel, live = !watchingChannel, handoff = liveHandoff, onUnplayable = ::rememberUnplayable) }
|
||||
when {
|
||||
mainHome -> HomeScreen(availableChannels, modifier, onCategory = { guideCategory = it; onGuide() })
|
||||
mainCatchUp -> CatchUpScreen(availableChannels, liveSession, modifier, onOpen = { catchUpOpen = it },
|
||||
onResume = { c -> if (c.entry.show.startMs >= System.currentTimeMillis() - CATCH_UP_MS) tune(c.entry.channel.number, c.entry.show.startMs + c.positionMs - System.currentTimeMillis()) })
|
||||
onResume = { c -> if (c.entry.show.startMs >= System.currentTimeMillis() - CATCH_UP_MS) {
|
||||
tune(c.entry.channel.number, c.entry.show.startMs + c.positionMs - System.currentTimeMillis())
|
||||
Taste.record(TasteKind.Chose, c.entry.show.media.item.id, (c.entry.channel as? ScheduledChannel)?.seriesIdAt(c.entry.show.startMs), c.entry.show.media.item.title, c.entry.channel.number, "continue")
|
||||
} })
|
||||
mainWhatsOn -> WhatsOnScreen(liveSession, scheduledChannels.filterKeys { !lockedOut(it) && !profileHides(it) }.mapValues { it.value.plan },
|
||||
driveInPlan.takeIf { Profiles.current?.let { it.kind != ProfileKind.Kids || it.driveIn } ?: true }, modifier, reminders,
|
||||
onWatch = { tune(it, 0) }, onDriveIn = onDriveIn, onBack = onHome,
|
||||
onRemind = { item -> saveReminders(liveReminders(reminders, System.currentTimeMillis()) + ProgrammeReminder(item.channel, item.startMs, item.title)) })
|
||||
onRemind = { item -> saveReminders(liveReminders(reminders, System.currentTimeMillis()) + ProgrammeReminder(item.channel, item.startMs, item.title))
|
||||
if (item.driveIn == null) Taste.record(TasteKind.Saved, item.entry.media.item.id, item.entry.seriesId, item.entry.media.item.title, item.channel, "reminder") })
|
||||
else -> GuideGrid(channelsIn(guideCategory, availableChannels).ifEmpty { availableChannels }, selectedNumber, modifier, guideCategory, homeCategories(availableChannels.map { it.number }), picture,
|
||||
onCategory = { guideCategory = it }, onWatch = ::tune, onBack = { guideCategory = ChannelCategory.All; onHome() }, onCatchUp = { catchUpOpen = it },
|
||||
onPicture = { tune(selectedNumber, 0) }, onRest = { rested -> scope.launch { TuneAhead.warm(liveSession, rested) } })
|
||||
|
||||
@@ -167,6 +167,8 @@ internal object OrbitCompanion {
|
||||
then.media.item.id, (channel as? ScheduledChannel)?.seriesIdAt(then.startMs)) }
|
||||
}
|
||||
queue = queue + item
|
||||
// Queued to watch next: picked deliberately (Taste, Stage 1).
|
||||
item.itemId.takeIf { it.isNotEmpty() }?.let { Taste.record(TasteKind.Chose, it, item.seriesId, item.title, number, "queue") }
|
||||
return item
|
||||
}
|
||||
fun queueJson(): JSONArray = JSONArray(queue.map { q ->
|
||||
|
||||
@@ -428,6 +428,22 @@ internal object PhoneLink {
|
||||
val said = runBlocking { withContext(mainDispatcher) { h.maker.arrivals(number, ids, o.optBoolean("add")) } }
|
||||
json(out, 200, JSONObject().put("message", said))
|
||||
}
|
||||
// Taste, Stage 1: what's been learnt for the profile watching now, and wiping it. Adults only.
|
||||
"GET /api/taste" -> {
|
||||
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult."))
|
||||
val p = Profiles.current ?: return json(out, 409, JSONObject().put("error", "Nobody's chosen on the TV yet."))
|
||||
val s = Taste.store ?: return json(out, 409, JSONObject().put("error", "Orbit is starting up on the TV."))
|
||||
json(out, 200, s.summary(p))
|
||||
}
|
||||
"POST /api/taste/reset" -> {
|
||||
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult."))
|
||||
val o = runCatching { JSONObject(r.body) }.getOrNull() ?: JSONObject()
|
||||
val p = o.optString("profile").takeIf { it.isNotEmpty() }?.let { id -> Profiles.all.firstOrNull { it.id == id } } ?: Profiles.current
|
||||
?: return json(out, 409, JSONObject().put("error", "Nobody's chosen on the TV yet."))
|
||||
val s = Taste.store ?: return json(out, 409, JSONObject().put("error", "Orbit is starting up on the TV."))
|
||||
s.reset(p, System.currentTimeMillis())
|
||||
json(out, 200, JSONObject().put("message", "What Orbit had learnt for ${p.name} is cleared."))
|
||||
}
|
||||
"POST /api/channels/remove" -> {
|
||||
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult to remove channels."))
|
||||
val number = runCatching { JSONObject(r.body).getInt("number") }.getOrNull()?.takeIf { n -> CustomChannels.list.any { it.number == n } }
|
||||
|
||||
@@ -39,7 +39,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
|
||||
next.instanceFollowRedirects = false
|
||||
next.connectTimeout = 10_000
|
||||
next.readTimeout = 20_000
|
||||
next.setRequestProperty("User-Agent", "OrbitTV/0.108.96")
|
||||
next.setRequestProperty("User-Agent", "OrbitTV/0.108.97")
|
||||
next.setRequestProperty("Accept-Encoding", "identity")
|
||||
session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) }
|
||||
if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) {
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Taste, Stage 1 (approved by Paul, 7 November 2026; design in the Profile-Aware Director's Chair doc): what each profile
|
||||
* actually watches, recorded as small signals in its own files, on this box only. The Director's Chair stays the household's
|
||||
* editor; Taste is a separate, profile-scoped layer. Stage 1 only records: nothing here changes What's On, Catch Up, the
|
||||
* Drive-In, a schedule or playback.
|
||||
*/
|
||||
internal enum class TasteKind(val key: String, val weight: Double) {
|
||||
/** Picked deliberately: opened from Catch Up or Continue watching, a ticket. */
|
||||
Chose("chose", 3.0),
|
||||
/** Watched to its last few minutes. */
|
||||
Finished("finished", 2.0),
|
||||
/** Saved for later: a reminder or a ticket. */
|
||||
Saved("saved", 2.0),
|
||||
/** 20 minutes or more of something not picked: a light touch. */
|
||||
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),
|
||||
/** Taken off Continue watching: tidying, not dislike. */
|
||||
Removed("removed", 0.0);
|
||||
companion object { fun of(key: String) = entries.firstOrNull { it.key == key } }
|
||||
}
|
||||
|
||||
internal const val TASTE_SCHEMA = 1
|
||||
internal const val TASTE_MAX_EVENTS = 5_000
|
||||
internal const val TASTE_MAX_AGE_MS = 365L * 24 * 60 * 60_000L
|
||||
/** The same kind on the same title within this long counts once. */
|
||||
internal const val TASTE_DUPLICATE_MS = 10 * 60_000L
|
||||
internal const val TASTE_STAYED_MS = 20 * 60_000L
|
||||
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) {
|
||||
fun toLine(): String = JSONObject().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()
|
||||
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 {
|
||||
val o = JSONObject(line)
|
||||
if (o.optInt("v") != TASTE_SCHEMA) return null
|
||||
val item = o.getString("i").takeIf(EmbyClient::validId) ?: return null
|
||||
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"))
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/** True when [event] repeats one already in [recent]: the same kind, title and profile within [TASTE_DUPLICATE_MS]. */
|
||||
internal fun tasteDuplicate(recent: List<TasteEvent>, 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) }
|
||||
|
||||
/** The log kept within its bounds: a year at most, the newest [TASTE_MAX_EVENTS], no repeated event ids, oldest first. */
|
||||
internal fun compactTaste(events: List<TasteEvent>, nowMs: Long): List<TasteEvent> =
|
||||
events.filter { nowMs - it.atMs <= TASTE_MAX_AGE_MS && it.atMs <= nowMs + 60_000L }.distinctBy { it.id }.sortedBy { it.atMs }.takeLast(TASTE_MAX_EVENTS)
|
||||
|
||||
/**
|
||||
* A profile's own settings. Personalise starts on for the Adult class and off for Kids until an adult turns it on. Suppressions
|
||||
* are kept here for later stages, each reversible: "not-for-me" lowers related titles gently, "hide" takes one title away.
|
||||
*/
|
||||
internal class TasteState(val personalise: Boolean, val suppressions: Map<String, String> = emptyMap(), val resetAtMs: Long = 0) {
|
||||
fun toJson(): JSONObject = JSONObject().put("v", TASTE_SCHEMA).put("personalise", personalise).put("suppress", JSONObject(suppressions)).put("resetAt", resetAtMs)
|
||||
companion object {
|
||||
fun defaultFor(profile: Profile) = TasteState(profile.kind == ProfileKind.Grown)
|
||||
fun of(o: JSONObject, profile: Profile) = TasteState(if (o.has("personalise")) o.optBoolean("personalise") else defaultFor(profile).personalise,
|
||||
o.optJSONObject("suppress")?.let { s -> s.keys().asSequence().filter(EmbyClient::validId).associateWith { s.getString(it) }.filterValues { it == "not-for-me" || it == "hide" } }.orEmpty(),
|
||||
o.optLong("resetAt"))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the TV notes while you watch, turned into signals: [TasteKind.Stayed] after 20 minutes of something not picked,
|
||||
* [TasteKind.Finished] at its last five minutes, [TasteKind.Brief] for a visit under five minutes. One programme at a time.
|
||||
*/
|
||||
internal class TasteWatch {
|
||||
private var key: Pair<Int, Long>? = null
|
||||
private var itemId = ""; private var seriesId: String? = null; private var title = ""; private var channel = 0
|
||||
private var firstSeenMs = 0L; private var lastSeenMs = 0L
|
||||
private var stayed = false; private var finished = false; private var chosen = false
|
||||
|
||||
/** The programme now on screen, at [positionMs] into it; [chose] when it was picked deliberately. The signals it adds. */
|
||||
fun observe(channel: Int, show: SampleBroadcast, seriesId: String?, positionMs: Long, chose: Boolean, nowMs: Long): List<Triple<TasteKind, String, Long>> {
|
||||
val out = mutableListOf<Triple<TasteKind, String, Long>>()
|
||||
val k = channel to show.startMs
|
||||
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
|
||||
}
|
||||
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) }
|
||||
return out
|
||||
}
|
||||
/** Watching stopped, or moved on: a short visit is noted as brief, with no weight. */
|
||||
fun stop(): List<Triple<TasteKind, String, Long>> {
|
||||
if (key == null) return emptyList()
|
||||
key = null
|
||||
val watched = lastSeenMs - firstSeenMs
|
||||
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) }
|
||||
val currentChannel get() = channel
|
||||
}
|
||||
|
||||
/** The store: a folder of per-profile files. All of it can be deleted; Orbit carries on as before. */
|
||||
internal class TasteStore(val directory: File) {
|
||||
private fun safe(profile: String) = profile.filter { it.isLetterOrDigit() || it == '-' || it == '_' }.take(40).ifEmpty { "profile" }
|
||||
fun eventsFile(profile: String) = File(directory, "${safe(profile)}.events.jsonl")
|
||||
fun stateFile(profile: String) = File(directory, "${safe(profile)}.state.json")
|
||||
private val recent = HashMap<String, MutableList<TasteEvent>>()
|
||||
|
||||
@Synchronized fun state(profile: Profile): TasteState = runCatching { TasteState.of(JSONObject(stateFile(profile.id).readText()), profile) }.getOrElse { TasteState.defaultFor(profile) }
|
||||
@Synchronized fun saveState(profile: Profile, state: TasteState) { directory.mkdirs(); writeWhole(stateFile(profile.id), state.toJson().toString()) }
|
||||
|
||||
/** Every readable event for [profile], oldest first. Damaged lines are skipped. */
|
||||
@Synchronized fun events(profile: String): List<TasteEvent> =
|
||||
runCatching { eventsFile(profile).readLines().mapNotNull { TasteEvent.of(it) }.filter { it.profile == profile } }.getOrDefault(emptyList())
|
||||
|
||||
/** Adds [event] for [profile] when its Personalise is on and it isn't a repeat. True when it was written. */
|
||||
@Synchronized fun record(profile: Profile, event: TasteEvent): Boolean {
|
||||
if (event.profile != profile.id || !state(profile).personalise) return false
|
||||
val mine = recent.getOrPut(profile.id) { events(profile.id).takeLast(50).toMutableList() }
|
||||
if (tasteDuplicate(mine, event)) return false
|
||||
directory.mkdirs()
|
||||
runCatching { eventsFile(profile.id).appendText(event.toLine() + "\n") }.onFailure { return false }
|
||||
mine += event; if (mine.size > 50) mine.removeAt(0)
|
||||
return true
|
||||
}
|
||||
|
||||
/** The log within its bounds, written through a temporary file with one backup kept. */
|
||||
@Synchronized fun compact(profile: String, nowMs: Long) {
|
||||
val file = eventsFile(profile); if (!file.exists()) return
|
||||
val kept = compactTaste(events(profile), nowMs)
|
||||
runCatching { file.copyTo(File(directory, file.name + ".bak"), overwrite = true) }
|
||||
writeWhole(file, kept.joinToString("") { it.toLine() + "\n" })
|
||||
recent.remove(profile)
|
||||
}
|
||||
|
||||
/** Clears [profile]'s signals and suppressions; its Personalise choice stays. */
|
||||
@Synchronized fun reset(profile: Profile, nowMs: Long) {
|
||||
eventsFile(profile.id).delete(); File(directory, eventsFile(profile.id).name + ".bak").delete(); recent.remove(profile.id)
|
||||
saveState(profile, TasteState(state(profile).personalise, emptyMap(), nowMs))
|
||||
}
|
||||
|
||||
/** What's been learnt, for inspection: counts by kind, how many name titles no longer in the library, and the latest few. */
|
||||
@Synchronized fun summary(profile: Profile, known: (String) -> Boolean = { true }): JSONObject {
|
||||
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("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) }))
|
||||
}
|
||||
|
||||
private fun writeWhole(file: File, text: String) {
|
||||
val temp = File(directory, file.name + ".tmp")
|
||||
temp.writeText(text)
|
||||
if (!temp.renameTo(file)) { file.writeText(text); temp.delete() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The box's Taste: the store for the server in use, and what's being watched now. */
|
||||
internal object Taste {
|
||||
@Volatile var store: TasteStore? = null
|
||||
private set
|
||||
private val watch = TasteWatch()
|
||||
/** The item last picked deliberately, so the programme it opens counts as chosen rather than passive. */
|
||||
@Volatile private var lastChosen: Pair<String, Long>? = null
|
||||
|
||||
fun attach(scheduleDir: File, nowMs: Long = System.currentTimeMillis()) {
|
||||
val s = TasteStore(File(scheduleDir, "taste")); store = s
|
||||
// Kept in bounds once a start-up; a failure leaves the files as they were.
|
||||
runCatching { s.directory.listFiles { f -> f.name.endsWith(".events.jsonl") }?.forEach { s.compact(it.name.removeSuffix(".events.jsonl"), nowMs) } }
|
||||
}
|
||||
|
||||
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()) {
|
||||
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)) }
|
||||
}
|
||||
|
||||
/** Whose watching [watch] is following: a profile switch closes it under the profile that was watching. */
|
||||
@Volatile private var watcher: Profile? = null
|
||||
|
||||
/** From the half-minute watching note: the programme on screen now. */
|
||||
@Synchronized fun watching(channel: Int, show: SampleBroadcast, seriesId: String?, positionMs: Long, nowMs: Long = System.currentTimeMillis(), profile: Profile? = Profiles.current) {
|
||||
if (watcher?.id != profile?.id) { stopped(); watcher = profile }
|
||||
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
|
||||
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)
|
||||
}
|
||||
}
|
||||
@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) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
/** Taste, Stage 1: signals recorded accurately, per profile, bounded, recoverable, inspectable and removable. */
|
||||
class TasteTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
private val minute = 60_000L
|
||||
private val now = 1_794_000_000_000L
|
||||
private val adult = Profile("grown", "Adult", "sil-blue", ProfileKind.Grown)
|
||||
private val dad = Profile("dad", "Dad", "rocket", ProfileKind.Grown)
|
||||
private val kids = Profile("kids", "Kids", "ollie", ProfileKind.Kids, KidsStartChannels)
|
||||
private var n = 0
|
||||
private fun event(p: Profile, kind: TasteKind, item: String = "1001", at: Long = now) =
|
||||
TasteEvent("e${n++}", p.id, kind, item, null, "Title $item", 106, at, null, "test")
|
||||
private fun show(item: String, start: Long, minutes: Long = 45) =
|
||||
SampleBroadcast(ScheduledMedia(SampleItem("Show / S1 E1 / Pilot", "Episode", minutes, "", item, minutes * minute), "src-$item", minutes * minute), start)
|
||||
|
||||
@Test fun eachProfileHasItsOwnSignals() {
|
||||
val store = TasteStore(tmp.newFolder("taste"))
|
||||
assertTrue(store.record(adult, event(adult, TasteKind.Chose, "1001")))
|
||||
assertTrue(store.record(dad, event(dad, TasteKind.Chose, "2002")))
|
||||
assertEquals(listOf("1001"), store.events("grown").map { it.itemId })
|
||||
assertEquals(listOf("2002"), store.events("dad").map { it.itemId })
|
||||
// An event filed under another profile is never written to this one.
|
||||
assertFalse(store.record(adult, event(dad, TasteKind.Chose, "3003")))
|
||||
assertNotEquals(store.eventsFile("grown"), store.eventsFile("dad"))
|
||||
}
|
||||
|
||||
@Test fun kidsRecordsNothingUntilAnAdultTurnsItOn() {
|
||||
val store = TasteStore(tmp.newFolder("taste"))
|
||||
assertFalse(TasteState.defaultFor(kids).personalise); assertTrue(TasteState.defaultFor(adult).personalise)
|
||||
assertFalse(store.record(kids, event(kids, TasteKind.Chose)))
|
||||
assertTrue(store.events("kids").isEmpty())
|
||||
store.saveState(kids, TasteState(true))
|
||||
assertTrue(store.record(kids, event(kids, TasteKind.Chose)))
|
||||
// Kids' file never holds Adult's history, and Adult's never holds Kids'.
|
||||
store.record(adult, event(adult, TasteKind.Finished, "4004"))
|
||||
assertTrue(store.events("kids").none { it.itemId == "4004" })
|
||||
assertTrue(store.events("grown").none { it.profile == "kids" })
|
||||
}
|
||||
|
||||
@Test fun repeatsCountOnce() {
|
||||
val store = TasteStore(tmp.newFolder("taste"))
|
||||
assertTrue(store.record(adult, event(adult, TasteKind.Chose, "1001", now)))
|
||||
assertFalse(store.record(adult, event(adult, TasteKind.Chose, "1001", now + 3 * minute)))
|
||||
assertTrue(store.record(adult, event(adult, TasteKind.Finished, "1001", now + 3 * minute)))
|
||||
assertTrue(store.record(adult, event(adult, TasteKind.Chose, "1001", now + 30 * minute)))
|
||||
assertEquals(3, store.events("grown").size)
|
||||
// The same event id arriving twice (as a later Rooms join would bring it) counts once.
|
||||
val e = event(adult, TasteKind.Saved, "5005")
|
||||
assertEquals(1, compactTaste(listOf(e, e), now).size)
|
||||
}
|
||||
|
||||
@Test fun theLogStaysWithinItsBounds() {
|
||||
val many = (0 until TASTE_MAX_EVENTS + 300).map { event(adult, TasteKind.Stayed, "${1000 + it}", now - it * minute) }
|
||||
val old = event(adult, TasteKind.Chose, "9009", now - TASTE_MAX_AGE_MS - minute)
|
||||
val kept = compactTaste(many + old, now)
|
||||
assertEquals(TASTE_MAX_EVENTS, kept.size)
|
||||
assertTrue(kept.none { it.itemId == "9009" })
|
||||
assertEquals(kept.sortedBy { it.atMs }, kept)
|
||||
val store = TasteStore(tmp.newFolder("taste"))
|
||||
many.take(50).forEach { store.record(adult, it) }
|
||||
store.compact("grown", now)
|
||||
assertTrue(java.io.File(store.directory, "grown.events.jsonl.bak").exists())
|
||||
assertEquals(50, store.events("grown").size)
|
||||
}
|
||||
|
||||
@Test fun damagedFilesAreRecovered() {
|
||||
val store = TasteStore(tmp.newFolder("taste"))
|
||||
store.record(adult, event(adult, TasteKind.Chose, "1001"))
|
||||
store.eventsFile("grown").appendText("{not json\n" + """{"v":99,"id":"x","p":"grown","k":"chose","i":"1002","w":1}""" + "\n")
|
||||
store.record(adult, event(adult, TasteKind.Finished, "1003", now + minute))
|
||||
assertEquals(listOf("1001", "1003"), store.events("grown").map { it.itemId })
|
||||
store.stateFile("grown").writeText("{broken")
|
||||
assertTrue(store.state(adult).personalise)
|
||||
assertFalse(store.state(kids).personalise)
|
||||
}
|
||||
|
||||
@Test fun inspectAndReset() {
|
||||
val store = TasteStore(tmp.newFolder("taste"))
|
||||
store.record(adult, event(adult, TasteKind.Chose, "1001"))
|
||||
store.record(adult, event(adult, TasteKind.Brief, "1002", now + minute))
|
||||
val s = store.summary(adult) { it == "1001" }
|
||||
assertEquals(2, s.getInt("events")); assertEquals(1, s.getJSONObject("byKind").getInt("brief"))
|
||||
// A title gone from the library is counted as stale, never a crash.
|
||||
assertEquals(1, s.getInt("stale"))
|
||||
assertEquals("Title 1002", s.getJSONArray("latest").getJSONObject(0).getString("title"))
|
||||
store.saveState(adult, TasteState(false, mapOf("1001" to "hide")))
|
||||
store.reset(adult, now)
|
||||
assertTrue(store.events("grown").isEmpty())
|
||||
assertTrue(store.state(adult).suppressions.isEmpty())
|
||||
assertFalse("reset keeps the Personalise choice", store.state(adult).personalise)
|
||||
}
|
||||
|
||||
@Test fun watchingBecomesSignals() {
|
||||
val w = TasteWatch()
|
||||
val a = show("1001", now)
|
||||
assertTrue(w.observe(106, a, null, 0, false, now).isEmpty())
|
||||
assertEquals(listOf(TasteKind.Stayed), w.observe(106, a, null, 21 * minute, false, now + 21 * minute).map { it.first })
|
||||
assertEquals(listOf(TasteKind.Finished), w.observe(106, a, null, 41 * minute, false, now + 41 * minute).map { it.first })
|
||||
assertTrue(w.observe(106, a, null, 42 * minute, false, now + 42 * minute).isEmpty())
|
||||
// A short visit is noted as brief, with no weight, when you move on.
|
||||
val b = show("1002", now + 45 * minute)
|
||||
w.observe(106, b, null, 0, false, now + 45 * minute)
|
||||
val moved = w.observe(107, show("1003", now + 40 * minute), null, 8 * minute, false, now + 47 * minute)
|
||||
assertEquals(listOf(TasteKind.Brief to "1002"), moved.map { it.first to it.second })
|
||||
assertEquals(0.0, TasteKind.Brief.weight, 0.0)
|
||||
// Picked deliberately: no "stayed" on top of the choice.
|
||||
val w2 = TasteWatch(); val c = show("1004", now)
|
||||
w2.observe(106, c, null, 0, true, now)
|
||||
assertTrue(w2.observe(106, c, null, 25 * minute, false, now + 25 * minute).isEmpty())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user