Release Kaleido 0.3.0 with categories, alphabet jumps and audio preferences
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m24s

This commit is contained in:
Elijah 2026-10-27 20:33:20 -07:00
parent 54519d4581
commit 0c62d7414e
31 changed files with 1051 additions and 80 deletions

View file

@ -0,0 +1,62 @@
package tv.kaleido.app
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
/** Read-only checks against the private server, including the same filters used by category jumps. */
@RunWith(AndroidJUnit4::class)
class BrowseAudioIntegrationTest {
private val app get()=InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as KaleidoApplication
private val api get()=app.api.apply { session=app.secure.load() }
@Test fun exactShowRanksAheadOfMetadataMovieMatch()=runBlocking {
val results=api.search("Silo")
assertEquals("Silo",searchGroups(results.titles,"Silo").first().second.first().title)
assertEquals("show",searchGroups(results.titles,"Silo").first().second.first().type)
}
@Test fun plexThemesAreInheritedAndPlayable()=runBlocking {
val show=api.details("6115")
val episode=api.details("7599")
assertTrue(show.theme.startsWith("/library/"))
assertEquals(show.theme,episode.theme)
val season=api.details(episode.parentId)
val inherited=season.theme.ifBlank { api.details(season.parentId).theme }
assertEquals(show.theme,inherited)
val request=okhttp3.Request.Builder().url(api.url(show.theme)).apply {
api.headers().filterKeys { it!="Accept" }.forEach { (k,v)->header(k,v) }
header("Range","bytes=0-1023")
}.build()
api.http.newCall(request).execute().use { response->
assertTrue(response.isSuccessful)
assertTrue(response.body!!.source().readByteArray(32).isNotEmpty())
}
val movie=Title.parse(JSONObject().put("type","movie").put("theme","/library/metadata/1/theme/2"))
assertEquals("/library/metadata/1/theme/2",movie.theme)
}
@Test fun letterCountsRespectCategoriesAndMediaType()=runBlocking {
for(section in api.sections().filter { it.type in listOf("movie","show") }) {
val type=plexLibraryType(section.type)
val genres=api.genres(section.id)
val genre=genres.firstOrNull { it.second=="Animation" } ?: genres.first()
for(unwatched in listOf(false,true)) {
val page=api.library(section.id,genre=genre.first,unwatched=unwatched,type=type)
val characters=api.firstCharacters(section.id,genre.first,unwatched,type)
assertEquals(page.total,characters.sumOf { it.size })
assertTrue(page.items.all { it.type==section.type })
val offsets=libraryCharacterOffsets(characters)
assertTrue(offsets.values.all { it in 0 until page.total })
val last=characters.lastOrNull { it.size>0 } ?: continue
val offset=offsets[last.title] ?: continue
val tail=api.library(section.id,start=offset,genre=genre.first,unwatched=unwatched,type=type)
assertEquals(last.size,tail.items.size)
}
}
}
}

View file

@ -8,6 +8,7 @@ HPLtv/kaleido/app/NavigationSoundsKt**->**(**)**
HPLtv/kaleido/app/NavigationSoundController;->**(**)**
HPLtv/kaleido/app/TitleDetailsKt**->**(**)**
HPLtv/kaleido/app/SettingsScreenKt**->**(**)**
HPLtv/kaleido/app/LibraryNavigationKt**->**(**)**
HPLtv/kaleido/app/ScreensKt**->**(**)**
HPLtv/kaleido/app/TitleActionsNode;->**(**)**
HPLtv/kaleido/app/TitleActionsElement;->**(**)**

View file

@ -33,6 +33,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.shape.CircleShape
@ -154,34 +155,87 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
var sortMenu by remember{mutableStateOf(false)}
var genreMenu by remember{mutableStateOf(false)}
var sectionMenu by remember{mutableStateOf(false)}
// Without explicit links, Right from Library searches upward and lands on (and opens) Home.
val libraryFocus=remember{FocusRequester()};val filterFocus=remember{FocusRequester()}
val discoverFocus=remember{FocusRequester()};val libraryFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()}
val filterFocus=remember{FocusRequester()};val categoryEntryFocus=remember{FocusRequester()};val railFocus=remember{FocusRequester()};val sectionFocus=remember{FocusRequester()}
val filters=vm.section!=null||vm.busy
Column(Modifier.fillMaxSize()) {
Row(Modifier.fillMaxWidth().height(64.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) {
Text(name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)
Spacer(Modifier.width(21.dp))
NavigationLabel("Discover",!vm.allTitles){vm.setAll(false)}
NavigationLabel("Library",vm.allTitles,modifier=Modifier.focusRequester(libraryFocus).focusProperties{right=if(filters)filterFocus else FocusRequester.Cancel},initialFocus=vm.focusId=="library-entry"){vm.setAll(true)}
NavigationLabel("Discover",!vm.allTitles,modifier=Modifier.focusRequester(discoverFocus).focusProperties{right=libraryFocus},onClick={vm.setAll(false)})
NavigationLabel("Library",!vm.categories,modifier=Modifier.focusRequester(libraryFocus).focusProperties{right=categoriesFocus;down=if(filters)filterFocus else FocusRequester.Cancel},initialFocus=vm.focusId=="library-entry"){vm.setAll(true)}
NavigationLabel("Categories",vm.categories,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{right=if(vm.sections.count{it.type==vm.section?.type}>1)sectionFocus else FocusRequester.Cancel;down=if(vm.categories&&vm.genre.isBlank())categoryEntryFocus else if(filters)filterFocus else FocusRequester.Cancel}){vm.openCategories()}
Spacer(Modifier.weight(1f))
if(vm.sections.count{it.type==vm.section?.type}>1)TvButton(vm.section?.title ?: "Library"){sectionMenu=true}
else if(!vm.allTitles)Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp)
if(vm.sections.count{it.type==vm.section?.type}>1)TvButton(vm.section?.title ?: "Library",Modifier.focusRequester(sectionFocus).focusProperties{left=categoriesFocus}){sectionMenu=true}
}
if(!filters)EmptyState("No $name library","This server has no matching library.")
if(vm.categories&&vm.genre.isBlank()) {
if(vm.section==null)EmptyState("No $name library","This server has no matching library.")
else if(vm.genres.isEmpty()&&vm.busy)Text("Loading categories…",color=Muted,fontSize=13.sp,modifier=Modifier.padding(start=Cinema.gutter,top=24.dp))
else if(vm.genres.isEmpty())EmptyState("No categories available","This Plex library has no genre categories.")
else {
val categoryRequesters=remember(vm.section?.id,vm.genres){vm.genres.associate{it.first to FocusRequester()}.toMutableMap()}
LazyVerticalGrid(GridCells.Fixed(5),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=18.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(12.dp),modifier=Modifier.fillMaxSize()) {
itemsIndexed(vm.genres,key={_,it->it.first}){index,entry->
val requester=if(index==0)categoryEntryFocus else categoryRequesters.getValue(entry.first)
val selected=vm.focusId=="category:${entry.first}"
Box(Modifier.fillMaxWidth().height(54.dp).focusRequester(requester).onFocusChanged{if(it.isFocused)vm.focusId="category:${entry.first}"}.navigationSound().clip(RoundedCornerShape(Cinema.radius)).background(Color.White.copy(alpha=if(selected) .13f else .07f)).border(1.dp,Color.White.copy(alpha=if(selected) .38f else .08f),RoundedCornerShape(Cinema.radius)).clickable{vm.selectCategory(entry.first)}.padding(horizontal=14.dp),contentAlignment=Alignment.CenterStart) {
Text(entry.second,color=if(selected)Accent else Cinema.secondary,fontSize=13.sp,fontWeight=if(selected)FontWeight.SemiBold else FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis)
}
LaunchedEffect(vm.focusId,index){if((vm.focusId=="categories-entry"&&index==0)||vm.focusId=="category:${entry.first}"){withFrameNanos{};runCatching{requester.requestFocus()}}}
}
}
}
} else if(!filters)EmptyState("No $name library","This server has no matching library.")
else {
Row(Modifier.fillMaxWidth().height(43.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(8.dp)) {
Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp)
Spacer(Modifier.weight(1f))
TvButton((if(vm.genre.isBlank())"All genres"else vm.genres.firstOrNull{it.first==vm.genre}?.second ?: "Genre")+" ⌄",Modifier.focusRequester(filterFocus).focusProperties{left=libraryFocus}){genreMenu=true}
TvButton((if(vm.genre.isBlank())"All genres"else vm.genres.firstOrNull{it.first==vm.genre}?.second ?: "Genre")+" ⌄",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus}){genreMenu=true}
TvButton(if(vm.unwatched)"Unwatched ✓"else "Unwatched",selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)}
TvButton((sortLabels.firstOrNull{it.first==vm.sort}?.second ?: "Title: A–Z")+" ⌄",Modifier.focusProperties{right=FocusRequester.Cancel}){sortMenu=true}
}
val grid=rememberLazyGridState()
val tileRequesters=remember{mutableMapOf<String,FocusRequester>()}
val scope=rememberCoroutineScope()
val enabledLetters=remember{LibraryJumpLetters.toSet()}
LaunchedEffect(grid,vm.library.size,vm.total){snapshotFlow{grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0}.collect{if(it>=vm.library.size-18&&vm.library.isNotEmpty())vm.more()}}
LazyVerticalGrid(GridCells.Fixed(6),state=grid,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=10.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) {
itemsIndexed(vm.library,key={_,it->it.id}){index,item->MediaTile(vm,item,"library:${item.id}",fillWidth=true,onMove={anticipateTileMove(vm,vm.library,index,it,6)})}
if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another genre or watch filter.")}
if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}}
LaunchedEffect(vm.libraryJumpRequest){
val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size} ?: return@LaunchedEffect
grid.scrollToItem(index)
}
LaunchedEffect(vm.libraryFocusRequest){
val itemId=vm.focusId.removePrefix("library:").takeIf{vm.focusId.startsWith("library:")}
val index=itemId?.let{id->vm.library.indexOfFirst{it.id==id}}?.takeIf{it>=0}
?: if(vm.focusId=="category-grid"&&!vm.busy&&vm.library.isNotEmpty())0 else -1
if(index>=0){
grid.scrollToItem(index)
snapshotFlow{grid.layoutInfo.visibleItemsInfo.any{it.index==index}}.first{it}
withFrameNanos{}
tileRequesters[vm.library[index].id]?.requestFocus()
}
}
suspend fun returnFocusToGrid(){
val itemId=vm.focusId.removePrefix("library:").takeIf{vm.focusId.startsWith("library:")}
val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size}
?: itemId?.let{id->vm.library.indexOfFirst{it.id==id}}?.takeIf{it>=0} ?: 0
if(vm.library.isNotEmpty()){
grid.scrollToItem(index)
snapshotFlow{grid.layoutInfo.visibleItemsInfo.any{it.index==index}}.first{it}
withFrameNanos{}
tileRequesters[vm.library[index].id]?.requestFocus()
}
}
Row(Modifier.fillMaxWidth().weight(1f),horizontalArrangement=Arrangement.spacedBy(7.dp),verticalAlignment=Alignment.Top) {
LazyVerticalGrid(GridCells.Fixed(6),state=grid,contentPadding=PaddingValues(start=Cinema.gutter,end=5.dp,top=10.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.weight(1f)) {
itemsIndexed(vm.library,key={_,it->it.id}){index,item->
val requester=tileRequesters.getOrPut(item.id){FocusRequester()}
val lastColumn=index%6==5||index==vm.library.lastIndex
MediaTile(vm,item,"library:${item.id}",fillWidth=true,modifier=Modifier.focusRequester(requester).then(if(lastColumn)Modifier.focusProperties{right=railFocus}else Modifier),onMove={anticipateTileMove(vm,vm.library,index,it,6)},onFocused={vm.onLibraryGridFocused()})
}
if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another genre or watch filter.")}
if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}}
}
LibraryJumpRail(enabledLetters,vm.libraryJumpLetter,railFocus,{scope.launch{runCatching{ returnFocusToGrid() }}},{vm.jumpToLibraryLetter(it)})
}
}
}
@ -213,7 +267,7 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
fun listen(){keyboard?.hide();runCatching{voice.launch(voiceIntent)}}
LaunchedEffect(vm.voicePending){if(vm.voicePending){vm.voiceStarted();if(canSpeak)listen()}}
LaunchedEffect(vm.query){if(vm.query!=value.text)value=TextFieldValue(vm.query,TextRange(vm.query.length))}
val groups=remember(vm.searchResults){searchGroups(vm.searchResults.titles)}
val groups=remember(vm.searchResults,vm.query){searchGroups(vm.searchResults.titles,vm.query)}
val people=vm.searchResults.people
val hasResults=groups.isNotEmpty()||people.isNotEmpty()
fun enterResults(){keyboard?.hide();runCatching{resultsFocus.requestFocus()}}
@ -246,9 +300,9 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
}
}
internal fun searchGroups(titles:List<Title>):List<Pair<String,List<Title>>> =
listOf("movie" to "Movies","show" to "TV shows","season" to "Seasons","collection" to "Collections","episode" to "Episodes")
.map{(type,label)->label to titles.filter{it.type==type}}.filter{it.second.isNotEmpty()}
internal fun searchGroups(titles:List<Title>,query:String=""):List<Pair<String,List<Title>>> = rankSearchGroups(
titles,query,Title::type
){title->listOf(title.title,title.parentTitle,title.grandparentTitle)}
@Composable private fun PeopleRow(vm:KaleidoViewModel,people:List<CastMember>,entryFocus:FocusRequester?) {
Column {

View file

@ -9,7 +9,13 @@ import androidx.media3.exoplayer.audio.ForwardingAudioSink
/** Android rejects a center-only PCM mask; one-channel audio uses its standard mono output. */
@androidx.annotation.OptIn(UnstableApi::class)
internal class CompatibleAudioSink(sink:AudioSink):ForwardingAudioSink(sink) {
internal class CompatibleAudioSink(sink:AudioSink,private val decodedOnly:Boolean=false):ForwardingAudioSink(sink) {
override fun supportsFormat(format:Format):Boolean =
if(decodedOnly&&format.sampleMimeType!=MimeTypes.AUDIO_RAW)false else super.supportsFormat(format)
override fun getFormatSupport(format:Format):Int =
if(decodedOnly&&format.sampleMimeType!=MimeTypes.AUDIO_RAW)AudioSink.SINK_FORMAT_UNSUPPORTED else super.getFormatSupport(format)
override fun getFormatOffloadSupport(format:Format):androidx.media3.exoplayer.audio.AudioOffloadSupport =
if(decodedOnly)androidx.media3.exoplayer.audio.AudioOffloadSupport.DEFAULT_UNSUPPORTED else super.getFormatOffloadSupport(format)
@Suppress("DEPRECATION")
override fun configure(config:AudioSink.AudioSinkConfig) {
val format=compatiblePcmFormat(config.format)

View file

@ -240,7 +240,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
}
var sectionMenu by remember{mutableStateOf(false)}
val sectionChoices=vm.sections.filter{it.type==vm.section?.type}
val sectionFocus=remember{FocusRequester()}
val sectionFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()}
val title=when(destination){"movies"->"Movies";"tv"->"TV Shows";else->"Home"}
BoxWithConstraints(Modifier.fillMaxSize()) {
val heroHeight=maxHeight*.80f-62.dp
@ -257,8 +257,12 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
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.
NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry;right=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}){vm.setAll(true)}
NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry;right=categoriesFocus}){vm.setAll(true)}
NavigationLabel("Categories",false,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{up=navigation.top;down=navigation.entry;right=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}.onPreviewKeyEvent{
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
}){vm.openCategories()}
Spacer(Modifier.weight(1f))
// A second movie or TV library (e.g. 4K, Kids) is chosen here and remembered.
if(sectionChoices.size>1)TvButton((vm.section?.title ?: title)+" ⌄",Modifier.focusRequester(sectionFocus).focusProperties{up=navigation.top;right=FocusRequester.Cancel}.onPreviewKeyEvent{

View file

@ -48,6 +48,11 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var genre by mutableStateOf(""); private set
var unwatched by mutableStateOf(false); private set
var allTitles by mutableStateOf(false); private set
var categories by mutableStateOf(false); private set
var libraryJumpIndex by mutableIntStateOf(-1); private set
var libraryJumpRequest by mutableIntStateOf(0); private set
var libraryFocusRequest by mutableIntStateOf(0); private set
var libraryJumpLetter by mutableStateOf<String?>(null); private set
var detail by mutableStateOf<Title?>(null); private set
var children by mutableStateOf(emptyList<Title>()); private set
var detailRelated by mutableStateOf(emptyList<Title>()); private set
@ -96,6 +101,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var debugValidationFile:File?=null; private set
var watchedPercent by mutableStateOf(preferences.getInt("watchedPercent",80).coerceIn(50,100)); private set
var navigationSounds by mutableStateOf(preferences.getBoolean("navigationSounds",true)); private set
var themeMusic by mutableStateOf(preferences.getBoolean("themeMusic",false)); private set
var themeVolume by mutableIntStateOf(preferences.getInt("themeVolume",30).coerceIn(10,100)); private set
var volumeBoostDb by mutableIntStateOf(preferences.getInt("volumeBoostDb",0).coerceIn(0,12)); private set
var episodeQueue by mutableStateOf(emptyList<Title>());private set
var relatedShows by mutableStateOf(emptyList<Title>());private set
var transitioningEpisode by mutableStateOf(false);private set
@ -110,6 +118,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
private var searchJob: Job? = null
private val detailsCache = mutableMapOf<String,Title>()
private val sectionCache=mutableMapOf<String,SectionContent>()
private val characterOffsetCache=mutableMapOf<LibraryCharacterQuery,Map<String,Int>>()
private var sectionStale=false
private val featureSeed=kotlin.random.Random.nextInt()
private val previews=PreviewMetadata(viewModelScope){api.details(it.id)}
@ -203,7 +212,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
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 expectedSection=section;val expectedSort=sort;val expectedGenre=genre;val expectedUnwatched=unwatched;val expectedCategories=categories;val expectedAllTitles=allTitles
val freshSections=api.sections()
val freshHome=fetchHome(freshSections)
val sectionPage=expectedPage.kind in listOf("movies","tv")
@ -215,7 +224,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
// 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 p=api.library(s.id,sort=expectedSort,genre=expectedGenre,unwatched=expectedUnwatched,size=library.size.coerceAtLeast(100),type=plexLibraryType(s.type))
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()
@ -225,10 +234,10 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
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||
section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched||categories!=expectedCategories||allTitles!=expectedAllTitles||
playing!=null||busy||markingId!=null)return false
sections=freshSections;homeHubs=freshHome.hubs;homeFeatures=freshHome.features
sectionCache.clear();detailsCache.clear();previews.clear()
sectionCache.clear();characterOffsetCache.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}
@ -266,23 +275,23 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun beginAccountLink(){linkingAccount=true;linkAccount()}
fun cancelAccountLink(){authJob?.cancel();pin=null;servers=emptyList();accountToken=session?.accountToken.orEmpty();linkingAccount=false}
fun chooseServer(server: Server) = launchLoad {
sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
val s=api.connect(server,accountToken); application.secure.save(s);api.session=s;session=s;servers=emptyList();linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
}
fun manualConnect(address: String, token: String) = launchLoad {
sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
require(address.startsWith("https://")||address.startsWith("http://")){"Enter a complete http:// or https:// server address."}
require(token.isNotBlank()){ "Enter an access token." }
val s=api.validate(Session("",token.trim(),address.trim().trimEnd('/'),"Plex",""))
authJob?.cancel();application.secure.save(s);api.session=s;session=s;linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
}
fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();sections=emptyList();library=emptyList();sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()}
fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()}
fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) }
fun tab(kind: String){
if(pages.size==1&&page.kind==kind)return
// Search and Settings return to the browsing tab they were opened from.
if(kind in listOf("search","settings")&&pages.first().kind in listOf("home","movies","tv"))previousTab=pages.first().kind
cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv"))allTitles=false;pages=listOf(Page(kind));loadPage(true)
cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv")){allTitles=false;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null};pages=listOf(Page(kind));loadPage(true)
}
fun open(item: Title){detailsCache[item.id]=item;episodeSelections.remove(item.id);pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()}
/** Opens an episode's show, or a season's show. */
@ -297,7 +306,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun dismissActions(){contextItem=null;contextFromContinue=false}
fun removeFromContinueWatching(item:Title){
viewModelScope.launch {
try{api.removeFromContinueWatching(item);homeHubs=loadHome();sectionCache.clear()}
try{api.removeFromContinueWatching(item);homeHubs=loadHome();sectionCache.clear();characterOffsetCache.clear()}
catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update Continue Watching."){removeFromContinueWatching(item)}}
}
}
@ -310,7 +319,20 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
}
fun back(): Boolean {
if(playing!=null){stopPlayback();return true}
if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);loadPage();return true}
if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);if(pages.last().kind in listOf("movies","tv")&&focusId.startsWith("library:"))libraryFocusRequest++;loadPage();return true}
if(page.kind in listOf("movies","tv")&&allTitles){
if(categories&&genre.isNotBlank()){
val selected=genre
genre=""
focusId="category:$selected"
libraryJumpIndex=-1;libraryJumpLetter=null
refreshLibrary()
return true
}
if(categories){categories=false;allTitles=false;genre="";focusId="discovery-entry";libraryJumpIndex=-1;libraryJumpLetter=null;return true}
setAll(false)
return true
}
if(page.kind in listOf("search","settings")){tab(previousTab);return true}
if(page.kind!="home"){tab("home");return true}
return false
@ -359,12 +381,13 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
/** Shows [s] in its destination, from cache when possible, with default filters. */
private fun loadSection(s:Section?) {
loadJob?.cancel();section=s;sort="titleSort:asc";genre="";unwatched=false
categories=false;libraryJumpIndex=-1;libraryJumpLetter=null
if(s==null){discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList();return}
val cached=sectionCache[s.id]
if(cached!=null){discoverHubs=cached.hubs;genres=cached.genres;library=cached.library.items;total=cached.library.total;busy=false;return}
discoverHubs=emptyList();library=emptyList();total=0
discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList()
launchLoad({loadSection(s)}) {coroutineScope {
val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id)}
val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id,type=plexLibraryType(s.type))}
val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(s.type=="show")async{runCatching{api.recentSeasons(s.id)}.getOrDefault(emptyList())}else null
val raw=h.await();val genreList=g.await();val p=l.await();val newSeasons=seasons?.await().orEmpty()
val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+if(newSeasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",newSeasons))else emptyList()
@ -374,13 +397,59 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
}
fun chooseSection(s: Section){
if(s.id==section?.id)return
val keepCategories=categories
preferences.edit().putString("section.${s.type}",s.id).apply()
cancelAnticipation();focusId=if(allTitles)"library-entry"else "discovery-entry";loadSection(s)
if(keepCategories){allTitles=true;categories=true;focusId="categories-entry"}
}
fun setAll(value: Boolean){focusId=if(value)"library-entry"else "discovery-entry";allTitles=value}
fun filter(sortValue: String=sort,genreValue: String=genre,unwatchedValue: Boolean=unwatched){sort=sortValue;genre=genreValue;unwatched=unwatchedValue;refreshLibrary()}
private fun refreshLibrary()=launchLoad { val p=api.library(section?.id ?: return@launchLoad,0,sort,genre,unwatched);library=p.items;total=p.total }
fun more(){if(busy||library.size>=total)return;launchLoad {val p=api.library(section?.id ?: return@launchLoad,library.size,sort,genre,unwatched);library=(library+p.items).distinctBy {it.id};total=p.total}}
fun setAll(value: Boolean){focusId=if(value)"library-entry"else "discovery-entry";allTitles=value;categories=false;libraryJumpIndex=-1;libraryJumpLetter=null}
fun openCategories(){val hadGenre=genre.isNotBlank();allTitles=true;categories=true;genre="";focusId="categories-entry";libraryJumpIndex=-1;libraryJumpLetter=null;if(hadGenre)refreshLibrary()}
fun selectCategory(value:String){if(value.isBlank())return;categories=true;allTitles=true;genre=value;sort="titleSort:asc";focusId="category-grid";libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()}
fun filter(sortValue: String=sort,genreValue: String=genre,unwatchedValue: Boolean=unwatched){sort=sortValue;genre=genreValue;unwatched=unwatchedValue;libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()}
private fun refreshLibrary() {
val selectedSection=section ?: return
val requestedSort=sort;val requestedGenre=genre;val requestedUnwatched=unwatched
launchLoad {
val p=api.library(selectedSection.id,0,requestedSort,requestedGenre,requestedUnwatched,type=plexLibraryType(selectedSection.type))
if(section?.id!=selectedSection.id||sort!=requestedSort||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad
library=p.items;total=p.total
if(categories&&requestedGenre.isNotBlank()){
focusId=p.items.firstOrNull()?.let{"library:${it.id}"} ?: "category-grid"
libraryFocusRequest++
}
}
}
fun more(){
if(busy||library.size>=total)return
val selectedSection=section ?: return;val start=library.size
val requestedSort=sort;val requestedGenre=genre;val requestedUnwatched=unwatched
launchLoad {
val p=api.library(selectedSection.id,start,requestedSort,requestedGenre,requestedUnwatched,type=plexLibraryType(selectedSection.type))
if(section?.id!=selectedSection.id||sort!=requestedSort||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad
library=(library+p.items).distinctBy{it.id};total=p.total
}
}
fun jumpToLibraryLetter(letter:String){
if(busy||letter !in LibraryJumpLetters)return
val selectedSection=section ?: return
val requestedGenre=genre;val requestedUnwatched=unwatched;val requestedSort=sort;val requestedType=plexLibraryType(selectedSection.type)
val cacheKey=LibraryCharacterQuery(selectedSection.id,requestedGenre,requestedUnwatched,requestedType)
launchLoad({jumpToLibraryLetter(letter)}) {
val offsets=characterOffsetCache[cacheKey] ?: libraryCharacterOffsets(api.firstCharacters(selectedSection.id,requestedGenre,requestedUnwatched,requestedType)).also{characterOffsetCache[cacheKey]=it}
val offset=offsets[letter] ?: return@launchLoad
val loaded=if(requestedSort=="titleSort:asc"&&library.size>offset)null else api.library(
selectedSection.id,0,"titleSort:asc",requestedGenre,requestedUnwatched,
size=(offset+100).coerceAtLeast(100),type=requestedType,
)
if(section?.id!=selectedSection.id||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad
if(loaded!=null){library=loaded.items;total=loaded.total}
sort="titleSort:asc"
if(offset !in library.indices)return@launchLoad
focusId="library-rail"
libraryJumpIndex=offset;libraryJumpLetter=letter;libraryJumpRequest++
}
}
fun onLibraryGridFocused(){libraryJumpIndex=-1}
fun search(text: String){query=text;searchJob?.cancel();searchJob=viewModelScope.launch {delay(350);if(text.isBlank()){searchResults=SearchResults();return@launch};busy=true;error=null;try{searchResults=api.search(text)}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Search is unavailable."){search(text)}}finally{busy=false}}}
fun mark(item: Title) {
if(markingId!=null)return
@ -393,7 +462,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update this title."){mark(item)}}finally{markingId=null}
}
}
fun refreshWatched(item:Title){viewModelScope.launch{try{refreshWatchedItems(item)}catch(e:CancellationException){throw e}catch(_:Exception){sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()}}}
fun refreshWatched(item:Title){viewModelScope.launch{try{refreshWatchedItems(item)}catch(e:CancellationException){throw e}catch(_:Exception){sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()}}}
private suspend fun refreshWatchedItems(item:Title) {
val d=api.details(item.id)
val updated=mutableMapOf(d.id to d)
@ -421,7 +490,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
hubTitles=hubTitles.map(::refreshedTitle)
actorTitles=actorTitles.map(::refreshedTitle);detailRelated=detailRelated.map(::refreshedTitle)
homeFeatures=homeFeatures.map{it.copy(item=refreshedTitle(it.item))}.filterNot{it.item.fullyWatched}
sectionCache.clear()
sectionCache.clear();characterOffsetCache.clear()
}
fun play(item: Title,fromStart: Boolean=false):Unit=launchLoad({play(item,fromStart)}) {
debugMode=null;debugValidation=false;debugValidationFile=null
@ -458,7 +527,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
}
fun stopPlayback(){
val finished=playing
if(finished!=null)playbackReturn++;playing=null;sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
if(finished!=null)playbackReturn++;playing=null;sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
// A season or episode page shows the last episode played, with fresh progress in its row.
detail?.let{if(finished?.type=="episode"&&it.type in listOf("season","episode"))episodeSelections[it.id]=finished.id}
launchLoad {
@ -484,6 +553,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun chooseSubtitleStyle(value:SubtitleStyle){subtitleStyle=value;preferences.edit().putString("subtitleStyle",value.name).apply()}
fun chooseWatchedPercent(value:Int){watchedPercent=value.coerceIn(50,100);preferences.edit().putInt("watchedPercent",watchedPercent).apply()}
fun chooseNavigationSounds(value:Boolean){navigationSounds=value;preferences.edit().putBoolean("navigationSounds",value).apply()}
fun chooseThemeMusic(value:Boolean){themeMusic=value;preferences.edit().putBoolean("themeMusic",value).apply()}
fun chooseThemeVolume(value:Int){themeVolume=value.coerceIn(10,100);preferences.edit().putInt("themeVolume",themeVolume).apply()}
fun chooseVolumeBoostDb(value:Int){volumeBoostDb=value.coerceIn(0,12);preferences.edit().putInt("volumeBoostDb",volumeBoostDb).apply()}
fun checkUpdate(manual: Boolean=true){viewModelScope.launch {
if(downloading||!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch
updateStatus="Checking for updates…"

View file

@ -0,0 +1,134 @@
package tv.kaleido.app
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.unit.DpSize
import androidx.compose.material3.Text
internal data class PlexCharacterCount(val key: String, val title: String, val size: Int)
internal data class LibraryCharacterQuery(val section: String, val genre: String, val unwatched: Boolean, val type: String)
internal fun libraryFilterParameters(genre: String, unwatched: Boolean, type: String): Map<String, String> = buildMap {
if (genre.isNotBlank()) put("genre", genre)
if (unwatched) put("unwatched", "1")
if (type.isNotBlank()) put("type", type)
}
internal val LibraryJumpLetters = listOf("#") + ('A'..'Z').map(Char::toString)
/** Plex returns one ordered Directory per initial; summing its sizes yields each absolute grid index. */
internal fun libraryCharacterOffsets(characters: List<PlexCharacterCount>): Map<String, Int> {
val offsets = linkedMapOf<String, Int>()
var index = 0
characters.forEach { character ->
val label = when {
character.key.equals("%23", ignoreCase = true) || character.key == "#" || character.title == "#" -> "#"
else -> character.title.firstOrNull()?.uppercaseChar()?.toString()
?: character.key.firstOrNull()?.uppercaseChar()?.toString()
}
if (character.size > 0 && label != null && label in LibraryJumpLetters) offsets.putIfAbsent(label, index)
index += character.size.coerceAtLeast(0)
}
return offsets
}
internal fun plexLibraryType(type: String): String = when (type) {
"movie" -> "1"
"show" -> "2"
else -> ""
}
@Composable
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
internal fun LibraryJumpRail(
enabledLetters: Set<String>,
selectedLetter: String?,
entryFocus: FocusRequester,
returnToGrid: () -> Unit,
onLetter: (String) -> Unit,
) {
// This remote-operated alphabet is denser than touch controls. Expanded touch targets
// overlap adjacent letters and hide their accessibility labels on Android TV.
val configuration=LocalViewConfiguration.current
val compactTargets=remember(configuration){object:ViewConfiguration by configuration {
override val minimumTouchTargetSize=DpSize.Zero
}}
CompositionLocalProvider(LocalViewConfiguration provides compactTargets) {
Column(modifier = Modifier.width(34.dp).height(350.dp)) {
LibraryJumpLetters.forEach { letter ->
var focused by remember { mutableStateOf(false) }
val active = letter in enabledLetters
val selected = letter == selectedLetter
Box(
Modifier
.weight(1f)
.width(34.dp)
.semantics { contentDescription = letter }
.then(if (letter == "#") Modifier.focusRequester(entryFocus) else Modifier)
.focusProperties { right = FocusRequester.Cancel }
.onPreviewKeyEvent {
if (it.type == KeyEventType.KeyDown && it.key == Key.DirectionLeft) {
returnToGrid()
true
} else false
}
.onFocusChanged { focused = it.isFocused }
.navigationSound()
.background(
when {
focused -> Accent
selected -> Color.White.copy(alpha = .14f)
else -> Color.Transparent
},
RoundedCornerShape(3.dp),
)
.clickable { if (active) onLetter(letter) },
contentAlignment = Alignment.Center,
) {
Text(
letter,
color = when {
focused -> Ink
selected -> Color(0xFFBBBBBB)
active -> Color(0xFF999999)
else -> Muted.copy(alpha = .46f)
},
fontSize = 10.sp,
lineHeight = 12.sp,
fontWeight = if (focused || selected) FontWeight.SemiBold else FontWeight.Normal,
)
}
}
}
}
}

View file

@ -36,7 +36,8 @@ data class Title(
val genres: List<String>, val cast: List<String>, val media: List<Media>, val markers: List<Marker>,
val logo: String = "", val poster: String = "", val still: String = "",val chapters:List<Chapter> = emptyList(),
val audienceScore: AudienceScore? = null, val releaseDate: String = "",val audienceScores:List<AudienceScore> = emptyList(),
val castMembers:List<CastMember> = emptyList(),val subtype:String="",val extras:List<Title> = emptyList()
val castMembers:List<CastMember> = emptyList(),val subtype:String="",val extras:List<Title> = emptyList(),
val theme:String=""
) {
val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0)
val fullyWatched get() = isWatched()
@ -77,7 +78,8 @@ data class Title(
j.optJSONArray("Chapter").objects().mapIndexed{position,c->Chapter(c.optInt("index"),chapterTitle(c.optString("title"),position),c.optLong("startTimeOffset"),c.optLong("endTimeOffset"),c.optString("thumb"))},
AudienceScore.parse(j),j.optString("originallyAvailableAt"),AudienceScore.parseAll(j),
j.optJSONArray("Role").objects().map(CastMember::parse).filter{it.name.isNotBlank()}.distinctBy{it.id.ifBlank{it.name}},
j.optString("subtype"),j.optJSONObject("Extras")?.optJSONArray("Metadata").objects().map(::parse)
j.optString("subtype"),j.optJSONObject("Extras")?.optJSONArray("Metadata").objects().map(::parse),
j.optString("theme").ifBlank{j.optString("parentTheme")}.ifBlank{j.optString("grandparentTheme")}
)
private fun parseMedia(m:JSONObject):Media {
val parts=m.optJSONArray("Part").objects().map { p -> Part(p.optString("id"),p.optString("key"),p.optJSONArray("Stream").objects().map { s -> Stream(s.optString("id"),s.optInt("streamType"),s.optString("codec"),s.optString("language",s.optString("languageCode","Unknown")),s.optString("displayTitle",s.optString("title",s.optString("language","Unknown"))),s.optBoolean("selected"),s.optString("key"),s.optInt("channels"),s.optInt("index",-1)) },p.optString("indexes"),p.optLong("duration"),p.optLong("size")) }

View file

@ -54,9 +54,10 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
private val renderers=object:DefaultRenderersFactory(app) {
override fun buildAudioSink(context:android.content.Context,enableFloatOutput:Boolean,enableAudioOutputPlaybackParams:Boolean):androidx.media3.exoplayer.audio.AudioSink =
CompatibleAudioSink(androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context)
.setEnableFloatOutput(enableFloatOutput)
.setAudioProcessors(if(vm.volumeBoostDb>0)arrayOf(VolumeBoostProcessor(vm.volumeBoostDb){Log.i("KaleidoPlayback","BOOST processing PCM db=${vm.volumeBoostDb}")})else emptyArray())
.setEnableFloatOutput(enableFloatOutput&&vm.volumeBoostDb==0)
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
.build())
.build(),decodedOnly=vm.volumeBoostDb>0)
}.setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing()
val player=ExoPlayer.Builder(app,renderers).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply {
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),true)

View file

@ -75,13 +75,17 @@ 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, size:Int=100): LibraryPage = withContext(Dispatchers.Default){
suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false, size:Int=100, type:String=""): 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"
p.putAll(libraryFilterParameters(genre,unwatched,type))
val d=container("/library/sections/$section/all",p)
LibraryPage(d.optJSONArray("Metadata").objects().map(Title::parse),d.optInt("totalSize",d.optInt("size")))
}
internal suspend fun firstCharacters(section:String,genre:String="",unwatched:Boolean=false,type:String=""):List<PlexCharacterCount> = withContext(Dispatchers.Default){
container("/library/sections/$section/firstCharacter",libraryFilterParameters(genre,unwatched,type)).optJSONArray("Directory").objects().map {
PlexCharacterCount(it.optString("key"),it.optString("title"),it.optInt("size"))
}
}
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}}

View file

@ -58,10 +58,11 @@ import java.io.File
}
@Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) {
KaleidoTheme {
ThemeMusic(vm)
val stateHolder=rememberSaveableStateHolder()
val discoveryFocus=remember{DiscoveryNavigation()}
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
val screenKey=vm.page.kind+":"+vm.page.id+if(vm.page.kind in listOf("movies","tv")) ":${vm.allTitles}"else ""
val screenKey=vm.page.kind+":"+vm.page.id+if(vm.page.kind in listOf("movies","tv")) ":${vm.allTitles}:${vm.categories}:${vm.genre}"else ""
val entrance=remember{Animatable(1f)}
val density=LocalDensity.current
var previousDestination by remember{mutableStateOf(vm.page.kind)}
@ -87,7 +88,7 @@ import java.io.File
}
}
BackHandler(enabled=vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){
if(vm.linkingAccount)vm.cancelAccountLink()else if(vm.playing==null&&vm.pages.size==1&&vm.page.kind in listOf("movies","tv")&&vm.allTitles)vm.setAll(false)else vm.back()
if(vm.linkingAccount)vm.cancelAccountLink()else vm.back()
}
NavigationSounds(vm.navigationSounds&&!startup) {
Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{startup}) {

View file

@ -0,0 +1,82 @@
package tv.kaleido.app
import java.text.Normalizer
import java.util.Locale
private val searchGroupSpecs = listOf(
"movie" to "Movies",
"show" to "TV shows",
"season" to "Seasons",
"collection" to "Collections",
"episode" to "Episodes"
)
private val combiningMarks = Regex("\\p{M}+")
private val nonLettersOrDigits = Regex("[^\\p{L}\\p{N}]+")
private val whitespace = Regex("\\s+")
private data class RankedSearchResult<T>(val value: T, val index: Int, val score: Int)
private data class RankedSearchGroup<T>(
val label: String,
val results: List<T>,
val bestScore: Int,
val firstBestResult: Int
)
internal fun <T> rankSearchGroups(
titles: List<T>,
query: String,
typeOf: (T) -> String,
searchableTitles: (T) -> List<String>
): List<Pair<String, List<T>>> {
val normalizedQuery = normalizeSearchText(query)
if (normalizedQuery.isBlank()) {
return searchGroupSpecs
.map { (type, label) -> label to titles.filter { typeOf(it) == type } }
.filter { it.second.isNotEmpty() }
}
val ranked = titles.mapIndexed { index, title ->
RankedSearchResult(title, index, titleRelevance(normalizedQuery, searchableTitles(title)))
}
return searchGroupSpecs.mapNotNull { (type, label) ->
val matching = ranked.filter { typeOf(it.value) == type }
if (matching.isEmpty()) return@mapNotNull null
val bestScore = matching.maxOf { it.score }
val ordered = matching.sortedWith(compareByDescending<RankedSearchResult<T>> { it.score }.thenBy { it.index })
RankedSearchGroup(
label = label,
results = ordered.map { it.value },
bestScore = bestScore,
firstBestResult = matching.first { it.score == bestScore }.index
)
}
.sortedWith(compareByDescending<RankedSearchGroup<T>> { it.bestScore }.thenBy { it.firstBestResult })
.map { it.label to it.results }
}
private fun titleRelevance(query: String, titles: List<String>): Int {
if (query.isBlank()) return 0
val queryTokens = query.split(' ')
return titles.mapIndexedNotNull { index, title ->
val candidate = normalizeSearchText(title)
val matchScore = when {
candidate.isBlank() -> 0
candidate == query -> 4
candidate.startsWith(query) -> 3
candidate.split(' ').windowed(queryTokens.size).any { it == queryTokens } -> 2
candidate.contains(query) -> 1
else -> 0
}
if (matchScore == 0) null else matchScore * 10 - index
}.maxOrNull() ?: 0
}
private fun normalizeSearchText(value: String): String = Normalizer.normalize(value, Normalizer.Form.NFKD)
.replace(combiningMarks, "")
.lowercase(Locale.ROOT)
.replace(nonLettersOrDigits, " ")
.replace(whitespace, " ")
.trim()

View file

@ -46,11 +46,16 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
var autoplayDialog by remember { mutableStateOf(false) }
var subtitleSizeDialog by remember { mutableStateOf(false) }
var subtitleStyleDialog by remember { mutableStateOf(false) }
var themeVolumeDialog by remember { mutableStateOf(false) }
var volumeBoostDialog by remember { mutableStateOf(false) }
val remoteFocus = remember { FocusRequester() }
val autoplayFocus = remember { FocusRequester() }
val introFocus = remember { FocusRequester() }
val creditsFocus = remember { FocusRequester() }
val subtitleStyleFocus = remember { FocusRequester() }
val themeMusicFocus = remember { FocusRequester() }
val themeVolumeFocus = remember { FocusRequester() }
val volumeBoostFocus = remember { FocusRequester() }
val categoryFocus = remember { List(categories.size) { FocusRequester() } }
val entryFocus = remember { List(categories.size) { FocusRequester() } }
@ -59,6 +64,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
val signOutActionFocus = remember { FocusRequester() }
val updateFocus = remember { FocusRequester() }
val updateDownloadFocus = remember { FocusRequester() }
var dialogRestoreFocus by remember { mutableStateOf<FocusRequester?>(null) }
var settingsFocused by remember { mutableStateOf(false) }
val paused = remember { booleanArrayOf(false) }
@ -67,6 +73,16 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
delay(140)
runCatching { entryFocus[selectedCategory].requestFocus() }
}
val anyDialogOpen = confirmSignOut || qualityDialog || watchedDialog || remoteDialog || autoplayDialog ||
subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog || volumeBoostDialog
LaunchedEffect(anyDialogOpen, dialogRestoreFocus) {
if (!anyDialogOpen) {
dialogRestoreFocus?.let { requester ->
runCatching { requester.requestFocus() }
dialogRestoreFocus = null
}
}
}
LifecycleResumeEffect(Unit) {
if (paused[0]) {
vm.installerReturned()
@ -99,7 +115,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
modifier = Modifier.padding(top = 3.dp)
)
}
Eyebrow(categories[selectedCategory])
}
Spacer(Modifier.height(25.dp))
@ -135,7 +150,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
) {
when (selectedCategory) {
0 -> {
SettingsSectionTitle("Plex account", "Manage the server and account used by Kaleido.")
SettingsSectionDescription("Manage the server and account used by Kaleido.")
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text(
vm.session?.serverName.orEmpty().ifBlank { "Plex connection" },
@ -187,20 +202,20 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
"Sign out",
requester = signOutActionFocus,
leftTarget = categoryFocus[0],
onClick = { confirmSignOut = true }
onClick = { dialogRestoreFocus = signOutActionFocus; confirmSignOut = true }
)
}
}
1 -> {
SettingsSectionTitle("Playback", "Choose how Plex delivers video and when a title counts as watched.")
SettingsSectionDescription("Choose how Plex delivers video and when a title counts as watched.")
SettingsValueRow(
title = "Playback quality",
description = "On your home network. Original plays the source; a resolution asks Plex to convert.",
value = vm.streamQuality.label,
requester = entryFocus[1],
leftTarget = categoryFocus[1],
onClick = { qualityDialog = true }
onClick = { dialogRestoreFocus = entryFocus[1]; qualityDialog = true }
)
SettingsValueRow(
title = "Remote quality",
@ -208,7 +223,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
value = vm.remoteQuality.label,
requester = remoteFocus,
leftTarget = categoryFocus[1],
onClick = { remoteDialog = true }
onClick = { dialogRestoreFocus = remoteFocus; remoteDialog = true }
)
SettingsValueRow(
title = "Watched status",
@ -216,7 +231,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
value = "${vm.watchedPercent}%",
requester = watchedFocus,
leftTarget = categoryFocus[1],
onClick = { watchedDialog = true }
onClick = { dialogRestoreFocus = watchedFocus; watchedDialog = true }
)
SettingsValueRow(
title = "Autoplay next episode",
@ -224,7 +239,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
value = autoplayLabel(vm.autoplaySeconds),
requester = autoplayFocus,
leftTarget = categoryFocus[1],
onClick = { autoplayDialog = true }
onClick = { dialogRestoreFocus = autoplayFocus; autoplayDialog = true }
)
SettingsValueRow(
title = "Skip intros",
@ -242,6 +257,14 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
leftTarget = categoryFocus[1],
onClick = { vm.chooseAutoSkipCredits(!vm.autoSkipCredits) }
)
SettingsValueRow(
title = "Volume boost",
description = "Raise quiet titles. Higher boosts can distort loud peaks. Uses decoded audio instead of passthrough.",
value = volumeBoostLabel(vm.volumeBoostDb),
requester = volumeBoostFocus,
leftTarget = categoryFocus[1],
onClick = { dialogRestoreFocus = volumeBoostFocus; volumeBoostDialog = true }
)
Text(
"Completed titles keep their Plex watched status.",
color = Cinema.quiet,
@ -252,14 +275,14 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
}
2 -> {
SettingsSectionTitle("Subtitles", "Choose how text subtitles look. Image subtitles keep their own style.")
SettingsSectionDescription("Choose how text subtitles look. Image subtitles keep their own style.")
SettingsValueRow(
title = "Size",
description = "Also sizes subtitles Plex adds to converted video.",
value = vm.subtitleSize.label,
requester = entryFocus[2],
leftTarget = categoryFocus[2],
onClick = { subtitleSizeDialog = true }
onClick = { dialogRestoreFocus = entryFocus[2]; subtitleSizeDialog = true }
)
SettingsValueRow(
title = "Style",
@ -267,13 +290,13 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
value = vm.subtitleStyle.label,
requester = subtitleStyleFocus,
leftTarget = categoryFocus[2],
onClick = { subtitleStyleDialog = true }
onClick = { dialogRestoreFocus = subtitleStyleFocus; subtitleStyleDialog = true }
)
SubtitlePreview(vm.subtitleSize, vm.subtitleStyle)
}
3 -> {
SettingsSectionTitle("Interface", "Control the small cues Kaleido plays as you browse.")
SettingsSectionDescription("Choose the sounds Kaleido plays while you browse.")
SettingsValueRow(
title = "Navigation sounds",
description = "Play the TV's system tap when focus moves. Follows the TV sound-effects setting.",
@ -282,10 +305,26 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
leftTarget = categoryFocus[3],
onClick = { vm.chooseNavigationSounds(!vm.navigationSounds) }
)
SettingsValueRow(
title = "Theme music",
description = "Play Plex theme tracks on movie, series, season and episode pages when available.",
value = if (vm.themeMusic) "On" else "Off",
requester = themeMusicFocus,
leftTarget = categoryFocus[3],
onClick = { vm.chooseThemeMusic(!vm.themeMusic) }
)
SettingsValueRow(
title = "Theme music volume",
description = "Set the browsing music volume.",
value = "${vm.themeVolume}%",
requester = themeVolumeFocus,
leftTarget = categoryFocus[3],
onClick = { dialogRestoreFocus = themeVolumeFocus; themeVolumeDialog = true }
)
}
else -> {
SettingsSectionTitle("Software updates", "Install the latest updates published for Kaleido.")
SettingsSectionDescription("Install the latest updates published for Kaleido.")
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text("Kaleido ${BuildConfig.VERSION_NAME}", color = Accent, fontSize = 18.sp, lineHeight = 23.sp, fontWeight = FontWeight.SemiBold)
Text(vm.updateStatus, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
@ -392,9 +431,24 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
qualityDialog = false
}
}
if (themeVolumeDialog) {
val choices = (10..100 step 10).toList()
ChoiceDialog("Theme music volume", choices.map { "$it%" }, choices.indexOf(vm.themeVolume).coerceAtLeast(0), { themeVolumeDialog = false }) {
vm.chooseThemeVolume(choices[it])
themeVolumeDialog = false
}
}
if (volumeBoostDialog) {
val choices = listOf(0, 3, 6, 9, 12)
ChoiceDialog("Volume boost", choices.map(::volumeBoostLabel), choices.indexOf(vm.volumeBoostDb).coerceAtLeast(0), { volumeBoostDialog = false }) {
vm.chooseVolumeBoostDb(choices[it])
volumeBoostDialog = false
}
}
}
private fun autoplayLabel(seconds: Int) = if (seconds <= 0) "Off" else "After $seconds seconds"
private fun volumeBoostLabel(db: Int) = if (db == 0) "Off (+0 dB)" else "+$db dB"
/** A sample line in the chosen subtitle look, rendered by the player's own subtitle view. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@ -426,11 +480,8 @@ private object SettingsScroll:BringIntoViewSpec {
}
@Composable
private fun SettingsSectionTitle(title: String, subtitle: String) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(title, color = Accent, fontSize = 21.sp, lineHeight = 27.sp, fontWeight = FontWeight.SemiBold, letterSpacing = (-.3).sp)
Text(subtitle, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
}
private fun SettingsSectionDescription(description: String) {
Text(description, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
}
@Composable

View file

@ -0,0 +1,81 @@
package tv.kaleido.app
import androidx.compose.runtime.*
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.okhttp.OkHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import kotlinx.coroutines.CancellationException
/** Themes belong to title pages, never the foreground video or a background Activity. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable internal fun ThemeMusic(vm:KaleidoViewModel) {
val lifecycle=LocalLifecycleOwner.current.lifecycle
var resumed by remember { mutableStateOf(false) }
LifecycleResumeEffect(Unit) {
resumed=true
onPauseOrDispose { resumed=false }
}
val title=vm.detail?.takeIf { it.id==vm.page.id && vm.page.kind in listOf("details","group") }
val eligible=resumed && vm.themeMusic && vm.playing==null && !vm.linkingAccount && vm.servers.isEmpty() && vm.session!=null
val server=vm.session?.server
val parents=remember(server) { mutableMapOf<String,String>() }
val path by produceState("",eligible,title?.id,title?.theme,server) {
value=""
if(!eligible || title==null)return@produceState
val direct=title.theme
if(direct.isNotBlank()) { value=safeThemePath(direct);return@produceState }
val parent=when(title.type) { "season"->title.parentId; "episode"->title.grandparentId; else->"" }
if(parent.isBlank())return@produceState
try {
val theme=parents[parent] ?: vm.api.details(parent).theme.also { parents[parent]=it }
value=safeThemePath(theme)
} catch(e:CancellationException) { throw e } catch(_:Exception) { /* Missing themes stay silent. */ }
}
val source=path.takeIf { eligible && it.isNotBlank() }
val player=remember(source,server) {
source?.let {
val data=OkHttpDataSource.Factory(vm.api.http).setDefaultRequestProperties(vm.api.headers().filterKeys { key->key!="Accept" })
ExoPlayer.Builder(vm.application).setMediaSourceFactory(DefaultMediaSourceFactory(DefaultDataSource.Factory(vm.application,data))).build().apply {
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(),true)
setHandleAudioBecomingNoisy(true)
repeatMode=Player.REPEAT_MODE_ONE
volume=vm.themeVolume/100f
addListener(object:Player.Listener {
override fun onPlaybackStateChanged(state:Int) {
if(state==Player.STATE_READY)android.util.Log.i("KaleidoTheme","READY volume=${vm.themeVolume}%")
}
override fun onIsPlayingChanged(isPlaying:Boolean) {
if(isPlaying)android.util.Log.i("KaleidoTheme","PLAYING")
}
})
setMediaItem(MediaItem.fromUri(vm.api.url(it)))
prepare();playWhenReady=true
}
}
}
SideEffect { player?.volume=vm.themeVolume/100f }
DisposableEffect(player,lifecycle) {
// Pause synchronously: backgrounding must not depend on a later Compose frame.
val observer=LifecycleEventObserver { _,event->
if(event==Lifecycle.Event.ON_PAUSE)player?.pause()
else if(event==Lifecycle.Event.ON_RESUME && vm.themeMusic && vm.playing==null &&
vm.page.id==title?.id && vm.page.kind in listOf("details","group") && !vm.linkingAccount)player?.play()
}
lifecycle.addObserver(observer)
onDispose {
lifecycle.removeObserver(observer)
if(player!=null){player.release();android.util.Log.i("KaleidoTheme","STOP")}
}
}
}
internal fun safeThemePath(path:String):String = path.takeIf { it.startsWith('/') && !it.startsWith("//") }.orEmpty()

View file

@ -0,0 +1,29 @@
package tv.kaleido.app
import androidx.media3.common.C
import androidx.media3.common.audio.AudioProcessor.AudioFormat
import androidx.media3.common.audio.AudioProcessor.UnhandledAudioFormatException
import androidx.media3.common.audio.BaseAudioProcessor
import java.nio.ByteBuffer
import kotlin.math.pow
import kotlin.math.roundToInt
/** Applied after decoding, for every channel and delivery mode; passthrough is disabled when on. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
internal class VolumeBoostProcessor(db:Int,private val onProcessing:(()->Unit)?=null):BaseAudioProcessor() {
private val gain=boostGain(db)
private var reported=false
override fun onConfigure(inputAudioFormat:AudioFormat):AudioFormat {
if(inputAudioFormat.encoding!=C.ENCODING_PCM_16BIT)throw UnhandledAudioFormatException(inputAudioFormat)
return if(gain>1.0)inputAudioFormat else AudioFormat.NOT_SET
}
override fun queueInput(inputBuffer:ByteBuffer) {
if(!reported&&inputBuffer.hasRemaining()) { reported=true;onProcessing?.invoke() }
val output=replaceOutputBuffer(inputBuffer.remaining())
while(inputBuffer.remaining()>=2)output.putShort(boostSample(inputBuffer.short,gain))
output.flip()
}
}
internal fun boostGain(db:Int):Double=10.0.pow(db.coerceIn(0,12)/20.0)
internal fun boostSample(sample:Short,gain:Double):Short=(sample*gain).roundToInt().coerceIn(Short.MIN_VALUE.toInt(),Short.MAX_VALUE.toInt()).toShort()

View file

@ -0,0 +1,36 @@
package tv.kaleido.app
import org.junit.Assert.*
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
import androidx.media3.common.C
import androidx.media3.common.audio.AudioProcessor.AudioFormat
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
class AudioPreferencesTest {
@Test fun boostProcessesEveryChannelAndSaturatesWithoutWrapping() {
val processor=VolumeBoostProcessor(6)
processor.configure(AudioFormat(48000,2,C.ENCODING_PCM_16BIT))
val input=ByteBuffer.allocateDirect(12).order(ByteOrder.nativeOrder())
listOf(1000,-1000,30000,-30000,0,Short.MIN_VALUE.toInt()).forEach { input.putShort(it.toShort()) }
input.flip();processor.queueInput(input)
val output=processor.output.order(ByteOrder.nativeOrder())
val samples=generateSequence { if(output.remaining()>=2)output.short.toInt()else null }.toList()
assertEquals(listOf(1995,-1995,32767,-32768,0,-32768),samples)
assertFalse(input.hasRemaining())
}
@Test fun boostOffPreservesSamplesAndBoundsGain() {
assertEquals(1.0,boostGain(0),0.0)
assertEquals(1.0,boostGain(-30),0.0)
assertEquals(boostGain(12),boostGain(99),0.0)
assertEquals(1234.toShort(),boostSample(1234,boostGain(0)))
assertEquals((-1234).toShort(),boostSample(-1234,boostGain(0)))
}
@Test fun themesUseOnlyServerRelativePaths() {
assertEquals("/library/metadata/6115/theme/1",safeThemePath("/library/metadata/6115/theme/1"))
assertEquals("",safeThemePath("https://elsewhere.example/theme.mp3"))
assertEquals("",safeThemePath("//elsewhere.example/theme.mp3"))
assertEquals("",safeThemePath(""))
}
}

View file

@ -0,0 +1,33 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
class LibraryNavigationTest {
@Test fun firstCharacterCountsProduceAbsoluteTitleOffsets() {
val counts = listOf(
PlexCharacterCount("%23", "#", 3),
PlexCharacterCount("A", "A", 12),
PlexCharacterCount("B", "B", 0),
PlexCharacterCount("C", "C", 4),
)
assertEquals(mapOf("#" to 0, "A" to 3, "C" to 15), libraryCharacterOffsets(counts))
assertEquals(false, libraryCharacterOffsets(counts).containsKey("B"))
}
@Test fun genreUnwatchedAndMediaTypeArePartOfTheCharacterQuery() {
val all = LibraryCharacterQuery("1", "", false, plexLibraryType("movie"))
val action = LibraryCharacterQuery("1", "12", false, plexLibraryType("movie"))
val unwatched = LibraryCharacterQuery("1", "12", true, plexLibraryType("movie"))
val shows = LibraryCharacterQuery("2", "12", true, plexLibraryType("show"))
assertNotEquals(all, action)
assertNotEquals(action, unwatched)
assertNotEquals(unwatched, shows)
assertEquals(mapOf("genre" to "12", "unwatched" to "1", "type" to "2"), libraryFilterParameters("12", true, "2"))
assertEquals("1", plexLibraryType("movie"))
assertEquals("2", plexLibraryType("show"))
}
}

View file

@ -38,7 +38,7 @@ class PlaybackModelTest {
}
@Test fun searchGroupsFollowBrowsingOrder() {
val groups=searchGroups(listOf(title("episode","e"),title("show","s"),title("movie","m")))
val groups=searchGroups(listOf(title("episode","e"),title("show","s"),title("movie","m")),query="")
assertEquals(listOf("Movies","TV shows","Episodes"),groups.map{it.first})
}

View file

@ -0,0 +1,70 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Test
class SearchRankingTest {
private data class Result(val type: String, val title: String, val inheritedTitles: List<String> = emptyList())
@Test fun exactShowRanksAheadOfLooseMovieResult() {
val groups = rankSearchGroups(listOf(
Result("movie", "The SpongeBob Movie: Sponge on the Run"),
Result("show", "Silo")
), "Silo", { it.type }) { listOf(it.title) }
assertEquals("TV shows", groups.first().first)
}
@Test fun exactMovieRanksAheadOfLooselyMatchingShow() {
val groups = rankSearchGroups(
listOf(Result("show", "The Silo Series"), Result("movie", "Silo")),
"Silo",
{ it.type }
) { listOf(it.title) }
assertEquals("Movies", groups.first().first)
}
@Test fun titlePrefixRanksAheadOfLaterTokenMatch() {
val groups = rankSearchGroups(
listOf(Result("show", "The Silo Series"), Result("movie", "Silo: Lost in Space")),
"Silo",
{ it.type }
) { listOf(it.title) }
assertEquals("Movies", groups.first().first)
}
@Test fun normalizedExactTitleOutranksPrefix() {
val groups = rankSearchGroups(
listOf(Result("movie", "Silo: The Movie"), Result("show", "Sílo")),
"Silo",
{ it.type }
) { listOf(it.title) }
assertEquals("TV shows", groups.first().first)
}
@Test fun ownExactTitleOutranksAnInheritedShowTitle() {
val groups = rankSearchGroups(
listOf(
Result("episode", "The Long Day", listOf("Silo")),
Result("show", "Silo")
),
"Silo",
{ it.type }
) { listOf(it.title) + it.inheritedTitles }
assertEquals("TV shows", groups.first().first)
}
@Test fun tiedGroupsKeepPlexResultOrder() {
val groups = rankSearchGroups(
listOf(Result("show", "Silo"), Result("movie", "Silo")),
"Silo",
{ it.type }
) { listOf(it.title) }
assertEquals(listOf("TV shows", "Movies"), groups.map { it.first })
}
}