Release Kaleido 0.1.11 with movie details and foreground library sync
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m40s

This commit is contained in:
Elijah 2026-10-27 11:19:54 -07:00
parent 2a83fe0db5
commit 5230692b8d
17 changed files with 374 additions and 60 deletions

View file

@ -0,0 +1,77 @@
package tv.kaleido.app
import android.content.Intent
import androidx.lifecycle.ViewModelProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import java.net.ServerSocket
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.concurrent.thread
/** Exercises the real foreground timer and ViewModel against a changing HTTP library.
* Only the in-memory API endpoint is replaced; the encrypted user session and Plex stay untouched. */
@RunWith(AndroidJUnit4::class)
class LibrarySyncIntegrationTest {
@Test fun openClientReceivesNewMediaWithoutReloading()=runBlocking {
val instrumentation=InstrumentationRegistry.getInstrumentation()
val app=instrumentation.targetContext.applicationContext as KaleidoApplication
val original=app.api.session ?: error("A private test session is required")
val activity=instrumentation.startActivitySync(Intent(app,MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
lateinit var vm:KaleidoViewModel
fun main(action:()->Unit)=instrumentation.runOnMainSync(action)
main{vm=ViewModelProvider(activity)[KaleidoViewModel::class.java]}
fun await(description:String,check:()->Boolean) {
val deadline=System.currentTimeMillis()+25_000
while(true){var ready=false;main{ready=check()};if(ready)return
check(System.currentTimeMillis()<deadline){description};Thread.sleep(100)}
}
await("Initial real library load"){!vm.busy&&vm.sections.isNotEmpty()&&vm.homeHubs.isNotEmpty()}
val movie=vm.sections.first{it.type=="movie"}
val changed=AtomicBoolean(false)
val revisionRequests=java.util.concurrent.atomic.AtomicInteger()
val server=ServerSocket(0)
val worker=thread(isDaemon=true,name="LibrarySyncTestServer") {
while(!server.isClosed)try{server.accept().use{socket->
val input=socket.getInputStream().bufferedReader()
val request=input.readLine().orEmpty()
while(!input.readLine().isNullOrEmpty()){}
val path=request.split(' ').getOrElse(1){"/"}.substringBefore('?')
val added=changed.get()
val title="""{"ratingKey":"sync-${if(added)"new" else "old"}","type":"movie","title":"${if(added)"Newly added" else "Existing"} movie"}"""
val container=when(path){
"/library/sections"->{revisionRequests.incrementAndGet();"""{"Directory":[{"key":"${movie.id}","title":${JSONObject.quote(movie.title)},"type":"movie","contentChangedAt":${if(added)2 else 1}}]}"""}
"/hubs","/hubs/sections/${movie.id}"->"""{"Hub":[{"hubIdentifier":"movie.recentlyadded","title":"Recently added","Metadata":[$title]}]}"""
"/library/sections/${movie.id}/all"->"""{"size":1,"totalSize":1,"Metadata":[$title]}"""
else->"{}"
}
val body="""{"MediaContainer":$container}""".toByteArray()
val output=socket.getOutputStream()
output.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray());output.write(body);output.flush()
}}catch(_:java.io.IOException){if(!server.isClosed)throw AssertionError("Test HTTP server failed")}
}
try {
main{vm.setForeground(false);app.api.session=original.copy(server="http://127.0.0.1:${server.localPort}");vm.tab("movies")}
await("Initial section snapshot"){!vm.busy&&vm.library.firstOrNull()?.id=="sync-old"}
main{vm.setForeground(true)}
await("First foreground sync"){vm.homeHubs.any{h->h.items.any{it.id=="sync-old"}}}
changed.set(true)
await("New media must reach Home and active library without restarting"){
vm.homeHubs.any{h->h.items.any{it.id=="sync-new"}}&&vm.library.firstOrNull()?.id=="sync-new"
}
main{assertEquals("movies",vm.page.kind);assertFalse(vm.busy);assertNull(vm.error)}
assertTrue("Revision was polled again",revisionRequests.get()>=3)
main{vm.setForeground(false)}
val stoppedAt=revisionRequests.get();Thread.sleep(700)
assertEquals("Background sync must stop",stoppedAt,revisionRequests.get())
}finally {
main{vm.setForeground(false);app.api.session=original;vm.tab("home");vm.initialize()}
server.close();worker.join(1000)
activity.finish()
}
}
}

View file

@ -56,8 +56,12 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val destination=if(home)"home"else vm.page.kind
val source=if(home)vm.homeHubs else vm.discoverHubs
val hubs=remember(source,destination){editorialHubs(source,destination)}
val restore=remember(hubs){hubs.withIndex().firstNotNullOfOrNull{(row,h)->val column=h.items.indexOfFirst{"${h.id}:${it.id}"==vm.focusId};if(column>=0)row to column else null}}
val initialRow=restore?.let{it.first+if(home)1 else 0} ?: 0
var previousHubs by remember(destination){mutableStateOf(hubs)}
val restore=remember(hubs){
val focused=Snapshot.withoutReadObservation{vm.focusId}
hubs.withIndex().firstNotNullOfOrNull{(row,h)->val column=h.items.indexOfFirst{"${h.id}:${it.id}"==focused};if(column>=0)Triple(h.id,row,column)else null}
}
val initialRow=restore?.let{it.second+if(home)1 else 0} ?: 0
// Keep the hero/preview and adjacent rows prepared across vertical moves.
// Without a behind window, every return discards and recomposes those cards.
val list=rememberLazyListState(initialFirstVisibleItemIndex=initialRow,
@ -73,13 +77,16 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
repeat(45){withFrameNanos{}}
if(!list.isScrollInProgress&&list.firstVisibleItemIndex==0&&list.firstVisibleItemScrollOffset==1)list.scrollBy(-1f)
}
val rowStates=remember(hubs){List(hubs.size){row->LazyListState(
// Hub order and membership can change during a live refresh. Keep each rail's scroll
// state and each card's requester by stable Plex IDs so surviving rows/cards retain them.
val rowStateByHub=remember(destination){mutableMapOf<String,LazyListState>()}
val rowStates=remember(hubs){hubs.associate{hub->hub.id to rowStateByHub.getOrPut(hub.id){LazyListState(
cacheWindow=LazyLayoutCacheWindow(aheadFraction=1f,behindFraction=.5f),
firstVisibleItemIndex=if(restore?.first==row)restore.second else 0)}}
val requesters=remember(hubs){mutableMapOf<Pair<Int,Int>,FocusRequester>()}
val columns=remember(hubs){mutableMapOf<Int,Int>()}
val pendingColumns=remember(hubs){mutableMapOf<Int,Int>()}
val horizontalTimes=remember(hubs){mutableMapOf<Int,Long>()}
firstVisibleItemIndex=if(restore?.first==hub.id)restore.third else 0)}}}
val requesters=remember(destination){mutableMapOf<String,FocusRequester>()}
val columns=remember(destination){mutableMapOf<String,String>()}
val pendingColumns=remember(destination){mutableMapOf<String,String>()}
val horizontalTimes=remember(destination){mutableMapOf<String,Long>()}
val navigationJob=remember{arrayOfNulls<Job>(1)}
val scope=rememberCoroutineScope()
val density=LocalDensity.current
@ -90,9 +97,9 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val nextFeature=features.getOrNull(featureIndex % features.size.coerceAtLeast(1))
var selectedFeature by remember{mutableStateOf(nextFeature)}
val heroFade=remember{Animatable(1f)}
LaunchedEffect(nextFeature?.item?.id){
LaunchedEffect(nextFeature){
if(home)nextFeature?.item?.let{vm.anticipate(it,cinematic=true)}
if(home&&selectedFeature!=null&&nextFeature!=null)heroFade.animateTo(0f,tween(100))
if(home&&selectedFeature!=null&&nextFeature!=null&&selectedFeature?.item?.id!=nextFeature.item.id)heroFade.animateTo(0f,tween(100))
selectedFeature=nextFeature
heroFade.animateTo(1f,tween(180))
}
@ -107,16 +114,21 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val staging=remember{CardStaging()}
LaunchedEffect(staging){delay(1000);staging.entering=false}
val rowOffset=if(home)1 else 0
suspend fun moveToRow(row:Int,column:Int)=coroutineScope {
val state=rowStates.getOrNull(row) ?: return@coroutineScope
suspend fun moveToRow(hubId:String,titleId:String)=coroutineScope {
val row=hubs.indexOfFirst{it.id==hubId}
val hub=hubs.getOrNull(row) ?: return@coroutineScope
val column=hub.items.indexOfFirst{it.id==titleId}
if(column<0)return@coroutineScope
val state=rowStates[hub.id] ?: return@coroutineScope
val focusKey="$hubId:$titleId"
val visible=list.layoutInfo.visibleItemsInfo.any{it.index==row+rowOffset}&&state.layoutInfo.visibleItemsInfo.any{it.index==column}
val focused=visible&&runCatching{requesters[row to column]?.requestFocus()==true}.getOrDefault(false)
val focused=visible&&runCatching{requesters[focusKey]?.requestFocus()==true}.getOrDefault(false)
val scrolling=launch{list.animateBrowseTo(row+rowOffset)}
if(!state.layoutInfo.visibleItemsInfo.any{it.index==column})state.requestScrollToItem(column)
if(!focused) {
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==row+rowOffset}&&state.layoutInfo.visibleItemsInfo.any{it.index==column}}.first{it}
withFrameNanos{}
runCatching{requesters.getOrPut(row to column){FocusRequester()}.requestFocus()}
runCatching{requesters.getOrPut(focusKey){FocusRequester()}.requestFocus()}
}
scrolling.join()
}
@ -125,6 +137,58 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==0}}.first{it}
withFrameNanos{};runCatching{heroFocus.requestFocus()};scrolling.join()
}
LaunchedEffect(hubs) {
val old=previousHubs
if(old==hubs)return@LaunchedEffect
navigationJob[0]?.cancel();navigationJob[0]=null
val focus=Snapshot.withoutReadObservation{vm.focusId}
val oldRow=old.indexOfFirst{hub->hub.items.any{"${hub.id}:${it.id}"==focus}}
val oldHub=old.getOrNull(oldRow)
val oldColumn=oldHub?.items?.indexOfFirst{"${oldHub.id}:${it.id}"==focus} ?: -1
val oldTitle=oldHub?.items?.getOrNull(oldColumn)
val hubIds=hubs.map{it.id}.toSet()
val cardKeys=hubs.flatMap{hub->hub.items.map{"${hub.id}:${it.id}"}}.toSet()
rowStateByHub.keys.retainAll(hubIds)
requesters.keys.retainAll(cardKeys)
columns.keys.retainAll(hubIds)
pendingColumns.keys.retainAll(hubIds)
horizontalTimes.keys.retainAll(hubIds)
hubs.forEach{hub->
if(columns[hub.id]?.let{id->hub.items.any{it.id==id}}!=true)hub.items.firstOrNull()?.let{columns[hub.id]=it.id} ?: columns.remove(hub.id)
if(pendingColumns[hub.id]?.let{id->hub.items.any{it.id==id}}!=true)hub.items.firstOrNull()?.let{pendingColumns[hub.id]=it.id} ?: pendingColumns.remove(hub.id)
}
previousHubs=hubs
if(oldHub!=null&&oldTitle!=null) {
val sameHub=hubs.firstOrNull{it.id==oldHub.id}
val target=sameHub?.let{hub->hub.items.firstOrNull{it.id==oldTitle.id}?.let{hub to it}}
?: hubs.firstNotNullOfOrNull{hub->hub.items.firstOrNull{it.id==oldTitle.id}?.let{hub to it}}
?: (sameHub?.takeIf{it.items.isNotEmpty()} ?: hubs.withIndex().filter{it.value.items.isNotEmpty()}
.minByOrNull{kotlin.math.abs(it.index-oldRow)}?.value)
?.let{hub->hub to hub.items[oldColumn.coerceIn(0,hub.items.lastIndex)]}
if(target!=null) {
val (hub,item)=target
val survived=hub.id==oldHub.id&&item.id==oldTitle.id
columns[hub.id]=item.id;pendingColumns[hub.id]=item.id
vm.focusId="${hub.id}:${item.id}"
hovered.value=item;heroActive=false
if(!survived)navigationJob[0]=scope.launch{withFrameNanos{};moveToRow(hub.id,item.id)}
}else {
hovered.value=null
if(home&&feature!=null) {
vm.focusId="home-feature";heroActive=true
navigationJob[0]=scope.launch{list.scrollToItem(0);withFrameNanos{};runCatching{heroFocus.requestFocus()}}
}else if(!home) {
vm.focusId="discovery-entry"
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{navigation.section.requestFocus()}}
}else {
vm.focusId=""
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{navigation.top.requestFocus()}}
}
}
}
}
LaunchedEffect(home,features.isNotEmpty()){if(home&&vm.focusId=="home-feature"){list.scrollToItem(0);withFrameNanos{};runCatching{heroFocus.requestFocus()}}}
DisposableEffect(navigation,list,hubs){
navigation.scrolled=false
@ -158,7 +222,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
NavigationLabel("Discover",true,modifier=Modifier.focusRequester(navigation.section).focusProperties{up=navigation.top;down=navigation.entry}.onPreviewKeyEvent {
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
hubs.firstOrNull()?.items?.firstOrNull()?.let{item->vm.anticipate(item)}
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{moveToRow(0,0)};true
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
},initialFocus=sectionEntry){}
// Nothing sits right of Library; an unbounded search would open Home from the top bar.
@ -185,7 +249,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis)
}
Row(Modifier.padding(top=16.dp).onPreviewKeyEvent{event->
if(event.type==KeyEventType.KeyDown&&event.key==Key.DirectionDown){hubs.firstOrNull()?.items?.firstOrNull()?.let{vm.anticipate(it,cinematic=true)};navigationJob[0]?.cancel();navigationJob[0]=scope.launch{moveToRow(0,0)};true}else false
if(event.type==KeyEventType.KeyDown&&event.key==Key.DirectionDown){hubs.firstOrNull()?.items?.firstOrNull()?.let{vm.anticipate(it,cinematic=true)};navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true}else false
}.onFocusChanged{if(it.hasFocus){heroActive=true;hovered.value=null}},horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) {
ActionButton(if(item.offset>0)"Resume"else "Play",Icons.Filled.PlayArrow,primary=true,modifier=Modifier.focusRequester(heroFocus).focusProperties{up=navigation.top}.onFocusChanged{if(it.isFocused){vm.focusId="home-feature";rotating=true}}){vm.play(item)}
IconControl(Icons.Outlined.Info,"More info",modifier=Modifier.focusProperties{up=navigation.top},onFocused={rotating=false}){vm.open(item)}
@ -203,20 +267,23 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val wideEpisode=destination=="tv"&&!poster
Column {
Text(hub.title,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=5.dp))
LazyRow(state=rowStates[row],contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=3.dp,bottom=3.dp),horizontalArrangement=Arrangement.spacedBy(10.dp)) {
LazyRow(state=rowStates[hub.id]!!,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=3.dp,bottom=3.dp),horizontalArrangement=Arrangement.spacedBy(10.dp)) {
itemsIndexed(hub.items,key={_,t->t.id},contentType={_,_->poster}) {column,item->
val requester=requesters.getOrPut(row to column){FocusRequester()}
val focusKey="${hub.id}:${item.id}"
val requester=requesters.getOrPut(focusKey){FocusRequester()}
BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)navigation.entry else null,requester,staging,
Modifier.onPreviewKeyEvent{event->
if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionLeft,Key.DirectionRight)) {
val target=(pendingColumns[row] ?: column)+if(event.key==Key.DirectionLeft)-1 else 1
val pendingId=pendingColumns[hub.id]
val pendingIndex=pendingId?.let{id->hub.items.indexOfFirst{it.id==id}}?.takeIf{it>=0} ?: column
val target=pendingIndex+if(event.key==Key.DirectionLeft)-1 else 1
if(target in hub.items.indices) {
val now=event.nativeKeyEvent.eventTime
val rapid=now-(horizontalTimes[row] ?: 0L)<160L
horizontalTimes[row]=now
pendingColumns[row]=target
val rapid=now-(horizontalTimes[hub.id] ?: 0L)<160L
horizontalTimes[hub.id]=now
pendingColumns[hub.id]=hub.items[target].id
navigationJob[0]?.cancel()
val state=rowStates[row]
val state=rowStates[hub.id]!!
navigationJob[0]=scope.launch {
// KeyDown/KeyUp can arrive between frames. Commit focus once
// on the next frame, so accessibility doesn't force an extra
@ -227,7 +294,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val visible=state.layoutInfo.visibleItemsInfo.any{it.index==target}
val anchor=(target-1).coerceAtLeast(0)
if(visible&&!rapid) {
runCatching{requesters.getOrPut(row to target){FocusRequester()}.requestFocus()}
runCatching{requesters.getOrPut("${hub.id}:${hub.items[target].id}"){FocusRequester()}.requestFocus()}
val pitch=with(density){(if(poster)130.dp else if(wideEpisode)274.dp else 224.dp).toPx()}
val delta=(anchor-state.firstVisibleItemIndex)*pitch-state.firstVisibleItemScrollOffset
if(kotlin.math.abs(delta)>1)state.animateScrollBy(delta,tween(140))
@ -236,7 +303,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
// synchronous composition between rapid remote events.
state.requestScrollToItem(anchor)
snapshotFlow{state.layoutInfo.visibleItemsInfo.any{it.index==target}}.first{it}
withFrameNanos{};runCatching{requesters.getOrPut(row to target){FocusRequester()}.requestFocus()}
withFrameNanos{};runCatching{requesters.getOrPut("${hub.id}:${hub.items[target].id}"){FocusRequester()}.requestFocus()}
}
// A held direction snaps to the latest anchor. Repeatedly
// cancelling pixel animations and decoding transient backdrops
@ -255,14 +322,16 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
navigationJob[0]?.cancel()
val target=row+if(event.key==Key.DirectionUp)-1 else 1
if(target in hubs.indices) {
val col=(columns[target] ?: 0).coerceAtMost(hubs[target].items.lastIndex)
val targetHub=hubs[target]
val selectedId=columns[targetHub.id]
val col=targetHub.items.indexOfFirst{it.id==selectedId}.takeIf{it>=0} ?: 0
vm.anticipate(hubs[target].items[col],cinematic=home)
navigationJob[0]=scope.launch{moveToRow(target,col)}
navigationJob[0]=scope.launch{moveToRow(targetHub.id,targetHub.items[col].id)}
}
}
true
}else false
},onHovered={columns[row]=column;pendingColumns[row]=column;hovered.value=it;heroActive=false})
},onHovered={columns[hub.id]=item.id;pendingColumns[hub.id]=item.id;hovered.value=it;heroActive=false})
}
}
}
@ -282,16 +351,16 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
@Composable private fun HomeBackdrop(api:PlexApi,hovered:State<Title?>,feature:Title?,heroActive:Boolean) {
var displayed by remember{mutableStateOf<Title?>(null)}
val current=if(heroActive)feature else hovered.value ?: feature
LaunchedEffect(current?.id){if(!heroActive)delay(90);displayed=current}
LaunchedEffect(current){if(!heroActive)delay(90);displayed=current}
(displayed ?: feature)?.let{BrowseBackdrop(api,it.art.ifBlank{it.thumb},Modifier.fillMaxSize(),cinematic=true,animate=heroActive)}
}
@Composable private fun FocusedPreviewCanvas(vm:KaleidoViewModel,hovered:State<Title?>,fallback:Title?,destination:String) {
var displayed by remember{mutableStateOf<Title?>(null)}
val current=hovered.value
LaunchedEffect(current?.id){delay(120);displayed=current}
LaunchedEffect(current){delay(120);displayed=current}
val feature=displayed ?: fallback
val metadata by produceState(feature,feature?.id){value=feature;feature?.let{value=vm.previewDetails(it)}}
val metadata by produceState(feature,feature){value=feature;feature?.let{value=vm.previewDetails(it)}}
Box(Modifier.fillMaxSize()) {
feature?.let{item->
BrowseBackdrop(vm.api,item.art,Modifier.fillMaxSize())

View file

@ -3,16 +3,16 @@ package tv.kaleido.app
data class HomeFeature(val item:Title,val reason:String)
/** Interleave discovery categories; Continue Watching has its own rail. */
internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,continuing:List<Title>):List<HomeFeature> {
internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,continuing:List<Title>,random:kotlin.random.Random=kotlin.random.Random.Default):List<HomeFeature> {
val excluded=continuing.flatMap{listOf(it.id,it.grandparentId,it.parentId)}.filter{it.isNotBlank()}.toSet()
fun eligible(item:Title)=item.type in listOf("movie","show")&&item.art.isNotBlank()&&
item.id !in excluded&&!item.fullyWatched&&item.offset==0L
// Shuffle movies and shows together rather than always leading with the same movie section.
val buckets=listOf(
recent.filter{eligible(it)&&it.releaseDate.isNotBlank()}.sortedByDescending{it.releaseDate}.take(18).shuffled().map{HomeFeature(it,"Recently released")},
rated.filter{eligible(it)&&it.viewedLeafCount==0}.shuffled().map{HomeFeature(it,"Highly rated · Unwatched")},
recent.filter{eligible(it)&&it.releaseDate.isNotBlank()}.sortedByDescending{it.releaseDate}.take(18).shuffled(random).map{HomeFeature(it,"Recently released")},
rated.filter{eligible(it)&&it.viewedLeafCount==0}.shuffled(random).map{HomeFeature(it,"Highly rated · Unwatched")},
hubs.filterNot{h->listOf("continue","ondeck","inprogress","recentlyviewed","recentlyadded","recentlyaired","recent").any{h.id.contains(it,true)}}
.flatMap{it.items}.filter(::eligible).distinctBy{it.id}.shuffled().map{HomeFeature(it,"Suggested for you")}
.flatMap{it.items}.filter(::eligible).distinctBy{it.id}.shuffled(random).map{HomeFeature(it,"Suggested for you")}
)
val seen=mutableSetOf<String>()
return buildList {

View file

@ -20,9 +20,11 @@ import coil.imageLoader
import coil.request.Disposable
import java.util.concurrent.Executors
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.isActive
data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="",val actor:CastMember?=null)
private data class SectionContent(val hubs:List<Hub>,val genres:List<Pair<String,String>>,val library:LibraryPage)
private data class HomeContent(val hubs:List<Hub>,val features:List<HomeFeature>)
class KaleidoViewModel(app: Application): AndroidViewModel(app) {
val application = app as KaleidoApplication
val api = application.api
@ -80,11 +82,15 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
private var episodeTransitionJob:Job?=null
private var loadJob: Job? = null
private var initializeJob:Job?=null
private var librarySyncJob:Job?=null
private var foreground=false
private var loadGeneration=0
private var authJob: Job? = null
private var searchJob: Job? = null
private val detailsCache = mutableMapOf<String,Title>()
private val sectionCache=mutableMapOf<String,SectionContent>()
private var sectionStale=false
private val featureSeed=kotlin.random.Random.nextInt()
private val previews=PreviewMetadata(viewModelScope){api.details(it.id)}
private var predictedArtwork:Disposable?=null
private var predictedArtworkKey=""
@ -125,14 +131,72 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
finally{if(loadJob?.isActive!=true)busy=false}
}
}
private suspend fun loadHome(): List<Hub> = coroutineScope {
private suspend fun loadHome():List<Hub> {
val fresh=fetchHome(sections);homeFeatures=fresh.features;return fresh.hubs
}
private suspend fun fetchHome(sources:List<Section>): HomeContent = coroutineScope {
val hubs=async { api.hubs() }; val deck=async { runCatching { api.onDeck() }.getOrDefault(emptyList()) }
val recommendations=async {sections.map{s->async{runCatching{api.hubs(s.id)}.getOrDefault(emptyList())}}.awaitAll().flatten()}
val recent=async {sections.map{s->async{runCatching{api.library(s.id,sort="originallyAvailableAt:desc").items.take(18)}.getOrDefault(emptyList())}}.awaitAll().flatten()}
val rated=async {sections.map{s->async{runCatching{api.library(s.id,sort="audienceRating:desc",unwatched=true).items.take(24)}.getOrDefault(emptyList())}}.awaitAll().flatten()}
val recommendations=async {sources.map{s->async{runCatching{api.hubs(s.id)}.getOrDefault(emptyList())}}.awaitAll().flatten()}
val recent=async {sources.map{s->async{runCatching{api.library(s.id,sort="originallyAvailableAt:desc",size=18).items}.getOrDefault(emptyList())}}.awaitAll().flatten()}
val rated=async {sources.map{s->async{runCatching{api.library(s.id,sort="audienceRating:desc",unwatched=true,size=24).items}.getOrDefault(emptyList())}}.awaitAll().flatten()}
val h=hubs.await();val d=deck.await()
homeFeatures=homeFeatures(recent.await(),rated.await(),recommendations.await(),d)
if(d.isEmpty()) h else listOf(Hub("continue","Continue Watching",d))+h.filterNot { it.title.equals("Continue Watching",true) }
HomeContent(if(d.isEmpty()) h else listOf(Hub("continue","Continue Watching",d))+h.filterNot { it.title.equals("Continue Watching",true) },
homeFeatures(recent.await(),rated.await(),recommendations.await(),d,kotlin.random.Random(featureSeed)))
}
/** Lifecycle-owned, silent sync; never competes with playback or a user-requested load. */
fun setForeground(value:Boolean) {
foreground=value
librarySyncJob?.cancel();librarySyncJob=null
if(!value)return
librarySyncJob=viewModelScope.launch {
var observedSession=session
var sync=newLibrarySync()
var interval=LibrarySync.POLL_MS
while(isActive) {
delay(interval)
if(session!=observedSession){observedSession=session;sync=newLibrarySync()}
if(session==null||playing!=null||busy||markingId!=null||initializeJob?.isActive==true)continue
try{sync.check();interval=LibrarySync.POLL_MS}
catch(e:CancellationException){throw e}
catch(_:Exception){interval=(interval*2).coerceAtMost(LibrarySync.FALLBACK_MS)}
}
}
}
private fun newLibrarySync()=LibrarySync(api::libraryRevision,::syncLibrary,android.os.SystemClock::elapsedRealtime)
private suspend fun syncLibrary():Boolean {
val expectedSession=session ?: return false
val expectedPage=page;val generation=loadGeneration
val expectedSection=section;val expectedSort=sort;val expectedGenre=genre;val expectedUnwatched=unwatched
val freshSections=api.sections()
val freshHome=fetchHome(freshSections)
val sectionPage=expectedPage.kind in listOf("movies","tv")
// Keep the underlying filtered section fresh while its details/actor page is open,
// so Back can restore the same grid and card instead of resetting to Discover.
val sectionKind=pages.first().kind
val active=if(sectionKind in listOf("movies","tv"))freshSections.firstOrNull{it.id==expectedSection?.id}
?: freshSections.firstOrNull{it.type==if(sectionKind=="movies")"movie"else "show"}else null
// Preserve the loaded range and selected filters, instead of resetting the A-Z grid.
val freshSection=active?.let{s->
val raw=api.hubs(s.id);val newGenres=api.genres(s.id)
val p=api.library(s.id,sort=expectedSort,genre=expectedGenre,unwatched=expectedUnwatched,size=library.size.coerceAtLeast(100))
val seasons=if(s.type=="show")api.recentSeasons(s.id)else emptyList()
val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+
if(seasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",seasons))else emptyList()
SectionContent(rows,newGenres,p)
}
val detailSnapshot=detail?.takeIf{expectedPage.kind in listOf("details","group")&&it.type in listOf("show","season","collection")}
val freshChildren=detailSnapshot?.let{api.children(it.id)}
// All loads above are staged. A tab/filter/session change must win over this snapshot.
if(!foreground||session!=expectedSession||page!=expectedPage||generation!=loadGeneration||
section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched||
playing!=null||busy||markingId!=null)return false
sections=freshSections;homeHubs=freshHome.hubs;homeFeatures=freshHome.features
sectionCache.clear();detailsCache.clear();previews.clear()
sectionStale=freshSection==null
if(freshSection!=null){section=active;discoverHubs=freshSection.hubs;genres=freshSection.genres;library=freshSection.library.items;total=freshSection.library.total}
else if(sectionPage){section=null;discoverHubs=emptyList();genres=emptyList();library=emptyList();total=0}
if(freshChildren!=null&&detail?.id==detailSnapshot?.id)children=freshChildren
return true
}
suspend fun previewDetails(item:Title):Title {
return try{previews.details(item)}catch(e:CancellationException){throw e}catch(_:Exception){item}
@ -196,7 +260,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
"movies","tv" -> {
if(sections.isEmpty()){initialize();return}
val type=if(page.kind=="movies")"movie"else "show"
if(!resetLibrary&&section?.type==type&&library.isNotEmpty()&&discoverHubs.isNotEmpty())return
if(!resetLibrary&&!sectionStale&&section?.type==type&&library.isNotEmpty()&&discoverHubs.isNotEmpty())return
sectionStale=false
loadJob?.cancel();section=sections.firstOrNull{it.type==type};sort="titleSort:asc";genre="";unwatched=false;allTitles=false
val s=section ?: return
val cached=sectionCache[s.id]
@ -218,7 +283,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
detail=d;detailsCache[id]=d;previews.remember(d)
coroutineScope {
val groups=async{if(d.type in listOf("show","season","collection"))api.children(id)else emptyList()}
val related=async{if(d.type=="show")try{api.relatedShows(id).filter{it.id!=id}}catch(e:CancellationException){throw e}catch(_:Exception){emptyList()}else emptyList()}
val related=async{try{when(d.type){"show"->api.relatedShows(id).filter{it.id!=id};"movie"->api.relatedMovies(id);else->emptyList()}}catch(e:CancellationException){throw e}catch(_:Exception){emptyList()}}
children=groups.await();detailRelated=related.await()
}
}

View file

@ -0,0 +1,23 @@
package tv.kaleido.app
/** Check a cheap server revision first; periodically refresh even on older servers without revisions. */
internal class LibrarySync(
private val revision:suspend ()->String,
private val refresh:suspend ()->Boolean,
private val now:()->Long
) {
private var accepted:String?=null
private var refreshedAt:Long?=null
suspend fun check() {
val current=revision()
val last=refreshedAt
if(current!=accepted||last==null||now()-last>=FALLBACK_MS) {
// Navigation may supersede the snapshot while it loads. Retry instead of accepting it.
if(refresh()){accepted=current;refreshedAt=now()}
}
}
companion object {
const val POLL_MS=15_000L
const val FALLBACK_MS=60_000L
}
}

View file

@ -46,5 +46,6 @@ class MainActivity: ComponentActivity() {
intent.getStringExtra("testFixture")?.let{model.debugPlayFixture(it);return}
intent.getStringExtra("testTitleId")?.let{model.debugPlay(it,intent.getLongExtra("testOffset",90000),intent.getIntExtra("testMode",0),intent.getBooleanExtra("testValidation",false))}
}}
override fun onStart() { super.onStart(); model.checkUpdate(false) }
override fun onStart() { super.onStart(); model.checkUpdate(false);model.setForeground(true) }
override fun onStop() { model.setForeground(false);super.onStop() }
}

View file

@ -62,6 +62,10 @@ class PlexApi(val clientId: String) {
throw PlexException("Cannot reach ${server.name}. Check that the server is online and reachable from this TV.")
}
suspend fun sections() = container("/library/sections").optJSONArray("Directory").objects().filter { it.optString("type") in listOf("movie","show") }.map { Section(it.optString("key"),it.optString("title"),it.optString("type")) }
/** A small response: no catalog, artwork, or metadata downloads on an unchanged library. */
suspend fun libraryRevision():String = container("/library/sections").optJSONArray("Directory").objects()
.filter{it.optString("type") in listOf("movie","show")}.sortedBy{it.optString("key")}
.joinToString("|"){j->listOf("key","title","type","contentChangedAt","scannedAt","updatedAt").joinToString(":"){j.optString(it)}}
suspend fun hubs(section: String? = null): List<Hub> = withContext(Dispatchers.Default){container(if(section==null) "/hubs" else "/hubs/sections/$section", mapOf("count" to "18","includeExternalMetadata" to "1")).optJSONArray("Hub").objects().map { Hub(it.optString("hubIdentifier",it.optString("key",it.optString("title"))),it.optString("title"),it.optJSONArray("Metadata").objects().map(Title::parse)) }.filter { it.items.isNotEmpty() && it.items.first().type in listOf("movie","show","episode","season","collection") }}
suspend fun onDeck(): List<Title> = container("/library/onDeck",mapOf("X-Plex-Container-Size" to "30")).optJSONArray("Metadata").objects().map(Title::parse)
suspend fun recentSeasons(section:String):List<Title> = withContext(Dispatchers.Default){
@ -69,8 +73,8 @@ class PlexApi(val clientId: String) {
val seasons=container("/library/sections/$section/all",mapOf("type" to "3","sort" to "addedAt:desc","X-Plex-Container-Size" to "100")).optJSONArray("Metadata").objects().map(Title::parse)
groupRecentSeasons(seasons,::details)
}
suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false): LibraryPage = withContext(Dispatchers.Default){
val p=mutableMapOf("X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to "100","sort" to sort)
suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false, size:Int=100): LibraryPage = withContext(Dispatchers.Default){
val p=mutableMapOf("X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to size.coerceAtLeast(1).toString(),"sort" to sort)
if(genre.isNotBlank())p["genre"]=genre
if(unwatched)p["unwatched"]="1"
val d=container("/library/sections/$section/all",p)
@ -79,6 +83,7 @@ class PlexApi(val clientId: String) {
suspend fun genres(section: String): List<Pair<String,String>> = container("/library/sections/$section/genre").optJSONArray("Directory").objects().map { it.optString("key") to it.optString("title") }
suspend fun details(id: String): Title = withContext(Dispatchers.Default){container("/library/metadata/$id",mapOf("includeMarkers" to "1","includeChapters" to "1","includeExtras" to "1")).optJSONArray("Metadata").objects().firstOrNull()?.let(Title::parse) ?: throw PlexException("This title is unavailable.")}
suspend fun relatedShows(id:String):List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="show"}.distinctBy{it.id}}
suspend fun relatedMovies(id:String):List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="movie"&&it.id!=id}.distinctBy{it.id}}
/** Actor tags are server-local. Query each accessible movie/show library, with pagination. */
suspend fun actorTitles(actor:CastMember,sections:List<Section>):List<Title> = coroutineScope {
require(actor.id.isNotBlank()){"This cast member has no Plex library identifier."}

View file

@ -61,7 +61,8 @@ import kotlinx.coroutines.launch
if(target!=null)list.scrollToItem(target)
}
Box(Modifier.fillMaxSize().background(Ink)) {
if(item.type=="show") {
val usesPosterHeader=item.type in listOf("show","movie")
if(usesPosterHeader) {
BrowseBackdrop(vm.api,item.art.ifBlank{item.thumb},Modifier.fillMaxSize().graphicsLayer {
alpha=if(list.firstVisibleItemIndex>0)0f else (1f-list.firstVisibleItemScrollOffset/backdropFadeDistance).coerceIn(0f,1f)
},cinematic=true)
@ -72,14 +73,14 @@ import kotlinx.coroutines.launch
CompositionLocalProvider(LocalBringIntoViewSpec provides DetailsScroll) {
LazyColumn(state=list,contentPadding=PaddingValues(bottom=30.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) {
item(key="details-${item.id}") {
Box(Modifier.fillMaxWidth().then(if(item.type=="show")Modifier.heightIn(min=248.dp)else Modifier.height(if(item.type in listOf("movie","episode"))322.dp else 286.dp))) {
if(item.type!="show") {
Box(Modifier.fillMaxWidth().then(if(usesPosterHeader)Modifier.heightIn(min=248.dp)else Modifier.height(if(item.type=="episode")322.dp else 286.dp))) {
if(!usesPosterHeader) {
Artwork(vm.api,item.art,Modifier.fillMaxSize(),1920,1080)
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.8f),Color.Transparent))))
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha=.12f),Color.Transparent,Ink))))
}
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=14.dp)){vm.back()}
if(item.type=="show") {
if(usesPosterHeader) {
Row(Modifier.fillMaxWidth().padding(start=Cinema.gutter,end=Cinema.gutter,top=56.dp),horizontalArrangement=Arrangement.spacedBy(24.dp),verticalAlignment=Alignment.Top) {
Artwork(vm.api,item.poster.ifBlank{item.thumb},Modifier.width(128.dp).height(192.dp).clip(androidx.compose.foundation.shape.RoundedCornerShape(6.dp)),384,576,animate=false,contentScale=ContentScale.Fit)
TitleInformation(vm,item,actionFocus,childFocus,!restoreRow,Modifier.weight(1f,fill=false).widthIn(max=560.dp))
@ -89,7 +90,7 @@ import kotlinx.coroutines.launch
}
if(vm.children.isNotEmpty())item(key="children-${item.id}"){MediaRow(vm,if(item.type=="show")"Seasons"else if(item.type=="season")"Episodes"else "In this collection",vm.children,"children:${item.id}",landscape=item.type=="season",entryFocus=childFocus)}
if(item.castMembers.isNotEmpty())item(key="cast-${item.id}"){CastRail(vm,item,actionFocus)}
if(vm.detailRelated.isNotEmpty())item(key="related-${item.id}"){MediaRow(vm,"Related shows",vm.detailRelated,"related:${item.id}")}
if(vm.detailRelated.isNotEmpty())item(key="related-${item.id}"){MediaRow(vm,if(item.type=="movie")"Related movies"else "Related shows",vm.detailRelated,"related:${item.id}")}
}
}
}
@ -125,7 +126,7 @@ private object DetailsScroll:BringIntoViewSpec {
val watched=item.isWatched(vm.watchedPercent)
ActionButton(if(vm.markingId==item.id)"Updating…"else if(watched)"Mark unwatched"else "Mark watched",if(watched)Icons.Outlined.CheckCircle else Icons.Outlined.Check,modifier=actionNavigation){vm.mark(item)}
}
if(item.type=="show"&&summaryOverflow)ActionButton("Synopsis",Icons.Outlined.Description,modifier=actionNavigation){showSynopsis=true}
if(item.type in listOf("show","movie")&&summaryOverflow)ActionButton("Synopsis",Icons.Outlined.Description,modifier=actionNavigation){showSynopsis=true}
}
if(item.type!="show")item.media.firstOrNull()?.let{media->Text(listOf(media.resolution.uppercase(),media.videoCodec.uppercase(),media.audioCodec.uppercase()).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.quiet,fontSize=9.sp,modifier=Modifier.padding(top=12.dp))}
}

View file

@ -0,0 +1,26 @@
package tv.kaleido.app
import kotlinx.coroutines.runBlocking
import org.junit.Assert.*
import org.junit.Test
class LibrarySyncTest {
@Test fun detectsNewMediaWithoutRestartAndSkipsUnchangedLibraries()=runBlocking {
var revision="before";var clock=0L;var refreshes=0
val sync=LibrarySync({revision},{refreshes++;true},{clock})
sync.check();assertEquals(1,refreshes)
clock+=15_000;sync.check();assertEquals(1,refreshes)
revision="new episode";sync.check();assertEquals(2,refreshes)
clock+=59_999;sync.check();assertEquals(2,refreshes)
clock++;sync.check();assertEquals(3,refreshes)
}
@Test fun discardedOrFailedRefreshIsRetried()=runBlocking {
var applies=false;var attempts=0;var failRequest=true
val sync=LibrarySync({"revision"},{attempts++;if(failRequest)throw java.io.IOException();applies},{0})
try{sync.check();fail("Expected failure")}catch(_:java.io.IOException){}
failRequest=false;sync.check();assertEquals(2,attempts)
applies=true;sync.check();assertEquals(3,attempts)
sync.check();assertEquals(3,attempts)
}
}