diff --git a/AGENTS.md b/AGENTS.md index 0cd7d46..22392e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,6 +55,7 @@ Use `& $KaleidoPython` before the Python commands below. Run only checks relevan | `scripts/verify_navigation_sounds.py` | Sound toggle and cold-start persistence; leaves sounds On | | `scripts/verify_details.py` | Cast/actor navigation, related shows and watched sync; temporarily marks validated unwatched movie/show fixtures, then restores them | | `scripts/verify_details_layout.py` | Fresh TV show header bounds and Seasons before Cast; debug or release | +| `scripts/verify_movie_details.py` | Movie safe header, related movies and Back focus restoration; debug or release | | `scripts/verify_settings.py` | Category navigation, preference-dialog cancellation and live update check; expects Original quality / 80% test preferences | Live Android integration tests (currently six) cover secure persistence, library APIs, episodes, PIN, preview JPEGs/new seasons and supported HEVC remux negotiation: @@ -72,6 +73,7 @@ These require the private test session. Playback test intents (`testTitleId`, `t ## Important regression traps - Keep initialization independent of cancellable tab requests and apply section results atomically. Cancelling initialization during a startup tab switch previously left Movies/TV blank. +- Foreground library sync polls revisions every 15 seconds with a 60-second refresh fallback; pause it for playback/background and stage updates before applying them. Preserve stable hub/card focus IDs and current library filters/range. `LibrarySyncIntegrationTest` tests the real timer against an in-memory HTTP fixture without changing Plex or the encrypted session. - Preserve explicit D-pad row/column targets and fixed card geometry. Avoid expensive beyond-bounds focus searches, per-focus catalog recomposition and full-screen gradient overdraw. Contrast is baked into cached backdrop bitmaps off the main thread. - Give every Media3 session a unique ID: next-episode creation can overlap the old controller's disposal. Plex HLS position is absolute; **do not add the requested resume offset again**. - Handle remote Back explicitly before default focus handling. Wait for menu focus restoration in tests instead of sending blind rapid button sequences. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d2b131..b0b9127 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Kaleido releases +## 0.1.11 + +- Give movie information the fitted poster, cinematic backdrop and safe header placement used by TV shows. Add related movies from Plex beneath the cast. +- Keep open libraries current: check Plex for library changes every 15 seconds and refresh Home and the active movie/TV section silently, with a 60-second fallback. Preserve filters, loaded titles and D-pad focus; pause checks during playback and while the app is in the background. + ## 0.1.10 - Play the original media file first at Original quality, preserving supported 4K video, Dolby Vision/HDR metadata and multichannel audio instead of unnecessarily converting to 1080p/stereo. diff --git a/app/src/androidTest/java/tv/kaleido/app/LibrarySyncIntegrationTest.kt b/app/src/androidTest/java/tv/kaleido/app/LibrarySyncIntegrationTest.kt new file mode 100644 index 0000000..7076a2d --- /dev/null +++ b/app/src/androidTest/java/tv/kaleido/app/LibrarySyncIntegrationTest.kt @@ -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() + 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() + } + } +} diff --git a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt index 0591bd1..99a00cb 100644 --- a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt +++ b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt @@ -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()} + 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,FocusRequester>()} - val columns=remember(hubs){mutableMapOf()} - val pendingColumns=remember(hubs){mutableMapOf()} - val horizontalTimes=remember(hubs){mutableMapOf()} + firstVisibleItemIndex=if(restore?.first==hub.id)restore.third else 0)}}} + val requesters=remember(destination){mutableMapOf()} + val columns=remember(destination){mutableMapOf()} + val pendingColumns=remember(destination){mutableMapOf()} + val horizontalTimes=remember(destination){mutableMapOf()} val navigationJob=remember{arrayOfNulls(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,feature:Title?,heroActive:Boolean) { var displayed by remember{mutableStateOf(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,fallback:Title?,destination:String) { var displayed by remember{mutableStateOf(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()) diff --git a/app/src/main/java/tv/kaleido/app/HomeFeatures.kt b/app/src/main/java/tv/kaleido/app/HomeFeatures.kt index d25b524..2b174a7 100644 --- a/app/src/main/java/tv/kaleido/app/HomeFeatures.kt +++ b/app/src/main/java/tv/kaleido/app/HomeFeatures.kt @@ -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,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 { diff --git a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt index 9bcca8a..4b08727 100644 --- a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt +++ b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt @@ -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&§ion?.type==type&&library.isNotEmpty()&&discoverHubs.isNotEmpty())return + if(!resetLibrary&&!sectionStale&§ion?.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() } } diff --git a/app/src/main/java/tv/kaleido/app/LibrarySync.kt b/app/src/main/java/tv/kaleido/app/LibrarySync.kt new file mode 100644 index 0000000..28b46d9 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/LibrarySync.kt @@ -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 + } +} diff --git a/app/src/main/java/tv/kaleido/app/MainActivity.kt b/app/src/main/java/tv/kaleido/app/MainActivity.kt index 8f81828..6e14a4c 100644 --- a/app/src/main/java/tv/kaleido/app/MainActivity.kt +++ b/app/src/main/java/tv/kaleido/app/MainActivity.kt @@ -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() } } diff --git a/app/src/main/java/tv/kaleido/app/PlexApi.kt b/app/src/main/java/tv/kaleido/app/PlexApi.kt index f661618..3d8b4bb 100644 --- a/app/src/main/java/tv/kaleido/app/PlexApi.kt +++ b/app/src/main/java/tv/kaleido/app/PlexApi.kt @@ -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."} diff --git a/app/src/main/java/tv/kaleido/app/TitleDetails.kt b/app/src/main/java/tv/kaleido/app/TitleDetails.kt index 9be63f5..2264b97 100644 --- a/app/src/main/java/tv/kaleido/app/TitleDetails.kt +++ b/app/src/main/java/tv/kaleido/app/TitleDetails.kt @@ -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))} } diff --git a/app/src/test/java/tv/kaleido/app/LibrarySyncTest.kt b/app/src/test/java/tv/kaleido/app/LibrarySyncTest.kt new file mode 100644 index 0000000..6243913 --- /dev/null +++ b/app/src/test/java/tv/kaleido/app/LibrarySyncTest.kt @@ -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) + } +} + diff --git a/distribution/Kaleido.apk b/distribution/Kaleido.apk index 233ebbc..904c126 100644 Binary files a/distribution/Kaleido.apk and b/distribution/Kaleido.apk differ diff --git a/distribution/Kaleido.apk.sha256 b/distribution/Kaleido.apk.sha256 index a0389a5..a260aba 100644 --- a/distribution/Kaleido.apk.sha256 +++ b/distribution/Kaleido.apk.sha256 @@ -1 +1 @@ -f93e377fd6746d0bb64689de3102a6da2615a790e46b023c78c885760bfe41e7 Kaleido.apk +ac32fe3f35376c91b7a9dc0876106c0f6f03a849ece6a6796e8a097e7345e897 Kaleido.apk diff --git a/distribution/latest.json b/distribution/latest.json index fd40d6b..6cc528e 100644 --- a/distribution/latest.json +++ b/distribution/latest.json @@ -1,7 +1,7 @@ { - "version": "0.1.10", - "versionCode": 11, - "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.10/distribution/Kaleido.apk", - "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.10/distribution/Kaleido.apk.sha256", - "notes": "- Play the original media file first at Original quality, preserving supported 4K video, Dolby Vision/HDR metadata and multichannel audio instead of unnecessarily converting to 1080p/stereo.\n- Automatically fall back to Plex when the native player cannot render the source video, including files that previously produced audio without a picture. Movie controls identify server conversions of video or audio.\n- Use Android's standard mono PCM output mask when a source specifies a center-only mono layout, fixing the tested 24-bit/96 kHz WAV without changing its sample rate. Preserve multichannel layouts and compressed-audio passthrough.\n- Honor Plex's selected audio and subtitle tracks during native playback, including Subtitles Off, and serialize stream changes to keep seeks and quality changes from competing." + "version": "0.1.11", + "versionCode": 12, + "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.11/distribution/Kaleido.apk", + "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.11/distribution/Kaleido.apk.sha256", + "notes": "- Give movie information the fitted poster, cinematic backdrop and safe header placement used by TV shows. Add related movies from Plex beneath the cast.\n- Keep open libraries current: check Plex for library changes every 15 seconds and refresh Home and the active movie/TV section silently, with a 60-second fallback. Preserve filters, loaded titles and D-pad focus; pause checks during playback and while the app is in the background." } diff --git a/docs/runtime-verification.md b/docs/runtime-verification.md index 7d8a727..652207a 100644 --- a/docs/runtime-verification.md +++ b/docs/runtime-verification.md @@ -4,6 +4,14 @@ For the 2026-10-26 codec/HDR sweep and its native-versus-converted playback find Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`. +## 2026-10-27 movie details and foreground library sync (0.1.11) + +- Movies now share TV shows' fitted poster, cinematic backdrop and safe header; related movie cards come from Plex's related metadata endpoint, below Cast. +- Foreground sync checks the small `/library/sections` revision response every 15 seconds. Content changes trigger a staged Home/active-section refresh, with a 60-second fallback for servers without useful revision fields. Current filters and loaded range survive. No loading overlay is shown, and unchanged state compares equal to avoid unnecessary UI updates. Playback/background pause the loop; connection failures back off to 60 seconds. +- Home feature selection keeps the same random seed for the current process, avoiding reshuffling unchanged content on each refresh. Browse rails and focus requesters use stable hub/title IDs across updates; removing a focused title selects a nearby surviving card. +- Seven unit tests passed, including revision changes, unchanged-library polling, fallback refreshes and retries after failed/superseded updates. `LibrarySyncIntegrationTest` passed on the onn in 42 seconds: its local HTTP fixture changes revision/content and the real ViewModel timer updates Home and the active movie library without a restart. It substitutes only the API's in-memory endpoint, restoring it afterward; it does not import/delete media on Plex or overwrite the encrypted session. This validates the client refresh path, not a real server scan/import event. +- `scripts/verify_movie_details.py` passed against real Plex content on the profiled release: safe movie header and initial action focus, related movies, opening a related title, and Back restoration. Screenshots `movie-details-0.1.11.png` and `movie-related-0.1.11.png` were inspected for fitted artwork and readable rows. Release build and lint passed; existing lint warnings remain. No playback or broad navigation sweep was needed for these changes. + ## Browsing - Cold-start switching to Movies reproduced an empty page: tab loading cancelled server initialization before library discovery finished. Initialization now has its own job; section requests update their cache and visible results atomically. `scripts/repro_runtime.py sections` passes the same startup switch, TV loading and cached Movies return. diff --git a/scripts/verify_movie_details.py b/scripts/verify_movie_details.py new file mode 100644 index 0000000..ecb1d41 --- /dev/null +++ b/scripts/verify_movie_details.py @@ -0,0 +1,32 @@ +"""Targeted movie detail layout and related-title check on the authorized onn.""" +import re +from device import screenshot +from verify_ui import launch,key,focused,wait,focus,labels,snapshot + +launch();key(22);focused('Movies');key(20);focused('Discover');key(22);focused('Library');key(23) +wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Movie library loaded') +key(20) +wait(lambda r:bool(focus(r)) and focus(r) not in ('Library','Discover') and 'All genres' not in focus(r),'Movie card focus') +selected=focus(snapshot());key(23) +wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Movie play action') +root=snapshot();screenshot('movie-details-0.1.11') +back=next((n for n in root.iter('node') if n.get('content-desc')=='Back'),None) +assert back is not None,'Movie Back control must be visible on entry' +assert any(n.get('text') and n.get('text') in selected and int(re.findall(r'\d+',n.get('bounds'))[1])>=88 for n in root.iter('node')),'Movie title must remain below the safe header' +print('PASS movie safe header and initial action focus',flush=True) +key(20) +wait(lambda r:focus(r) not in ('Play','') and not focus(r).startswith('Resume'),'Cast or related row focus') +for _ in range(3): + root=snapshot() + if 'Related movies' in labels(root):break + key(20) +assert 'Related movies' in labels(root),'Plex related movies must appear beneath Cast' +key(20) +root=wait(lambda r:bool(focus(r)) and 'Related movies' in labels(r),'Related movie focus') +screenshot('movie-related-0.1.11') +key(23) +wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Related movie opens') +key(4) +wait(lambda r:bool(focus(r)) and 'Related movies' in labels(r),'Related movie restores row focus') +print('PASS related movies open and Back restores the selected card',flush=True) +key(4);focused(selected);key(4);key(4) diff --git a/version.properties b/version.properties index f64821d..a99ad37 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionName=0.1.10 -versionCode=11 +versionName=0.1.11 +versionCode=12