Initial Beta build
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m27s

This commit is contained in:
Elijah 2026-10-24 09:09:55 -07:00
commit 2b585badac
65 changed files with 3535 additions and 0 deletions

View file

@ -0,0 +1,92 @@
package tv.kaleido.app
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import kotlinx.coroutines.runBlocking
@RunWith(AndroidJUnit4::class)
class BrowsePolicyTest {
private fun title(id:String,type:String="movie")=Title.parse(JSONObject("""{"ratingKey":"$id","type":"$type","art":"/art/$id","title":"Title $id","originallyAvailableAt":"2026-10-01"}"""))
@Test fun partiallyWatchedShowUsesEpisodeCountsEvenWithViewCount() {
val show=Title.parse(JSONObject("""{"type":"show","viewCount":12,"leafCount":30,"viewedLeafCount":10}"""))
assertFalse(show.fullyWatched);assertEquals(20,show.remainingEpisodes)
assertEquals("20 episodes remaining",show.watchStatus)
assertTrue(show.copy(viewedLeafCount=30).fullyWatched)
assertFalse(show.copy(leafCount=0,viewedLeafCount=0).fullyWatched)
assertEquals("",show.copy(leafCount=0,viewedLeafCount=0).watchStatus)
}
@Test fun unwatchedMoviesHaveNoBadgeAndWatchedEpisodesHaveCheckmarks() {
assertEquals("",title("1").watchStatus)
assertEquals("Watched",title("1").copy(watched=true).watchStatus)
assertTrue(title("2","episode").copy(watched=true).fullyWatched)
}
@Test fun audienceScoresPreferRottenTomatoesAndExcludeCritics() {
val item=Title.parse(JSONObject("""{"audienceRating":8.1,"audienceRatingImage":"imdb://image.rating","rating":9.9,"Rating":[
{"type":"critic","image":"rottentomatoes://image.rating.ripe","value":9.9},
{"type":"audience","image":"thetvdb://image.rating","value":8.7},
{"type":"audience","image":"rottentomatoes://image.rating.upright","value":7.0}
]}"""))
assertEquals("Rotten Tomatoes",item.audienceScore?.source)
assertEquals("70%",item.audienceScore?.displayValue)
assertEquals(listOf("Rotten Tomatoes","IMDb"),item.audienceScores.map{it.source})
assertEquals(listOf("70%","8.1/10"),item.audienceScores.map{it.displayValue})
}
@Test fun imdbPrecedesTvdbAndMissingAudienceDoesNotUseCriticScore() {
val json=JSONObject("""{"Rating":[{"type":"audience","image":"thetvdb://image.rating","value":8.7},{"type":"audience","image":"imdb://image.rating","value":8.1}]}""")
assertEquals("IMDb 8.1/10",Title.parse(json).rating)
assertEquals("",Title.parse(JSONObject("""{"rating":9.5,"ratingImage":"rottentomatoes://image.rating.ripe"}""")).rating)
assertEquals("",Title.parse(JSONObject("""{"audienceRating":7.5,"audienceRatingImage":"themoviedb://image.rating"}""")).rating)
}
@Test fun malformedScoresCannotBecomeAnAudienceBadge() {
for(value in listOf("null","-1","11","\"unknown\""))assertNull(AudienceScore.parse(JSONObject("""{"audienceRating":$value,"audienceRatingImage":"imdb://image.rating"}""")))
assertNull(AudienceScore.parse(JSONObject("""{"audienceRating":9,"audienceRatingImage":"rottentomatoes://image.rating.ripe"}""")))
}
@Test fun watchedThresholdFollowsResumeProgressAndCanBeConfigured() {
val replay=title("replay").copy(watched=true,duration=100000,offset=15000)
assertFalse(replay.isWatched());assertEquals("",replay.watchStatus())
assertFalse(replay.copy(offset=79999).isWatched())
assertTrue(replay.copy(offset=80000).isWatched())
assertFalse(replay.copy(offset=80000).isWatched(90))
assertTrue(replay.copy(offset=80000).isWatched(75))
assertTrue(replay.copy(offset=0).isWatched())
assertFalse(title("unwatched").isWatched())
assertFalse(reachedWatchedThreshold(100,0,80))
}
@Test fun scoresPreserveAudiencePercentagesAndImdbTenPointScale() {
assertEquals("80%",AudienceScore("Rotten Tomatoes",8.0).displayValue)
assertEquals("0%",AudienceScore("Rotten Tomatoes",0.0).displayValue)
assertEquals("10.0/10",AudienceScore("IMDb",10.0).displayValue)
val tvdb=Title.parse(JSONObject("""{"audienceRating":8.7,"audienceRatingImage":"thetvdb://image.rating"}"""))
assertEquals("TVDB 8.7/10",tvdb.rating)
}
@Test fun playbackMarksOnceAtThresholdAndRetriesFailedWrites()=runBlocking {
var writes=0
val progress=WatchedProgress{writes++}
progress.report(79999,100000,80);assertEquals(0,writes)
progress.report(80000,100000,80);assertEquals(1,writes)
progress.report(95000,100000,80);progress.report(100000,100000,80);assertEquals(1,writes)
var attempts=0
val retry=WatchedProgress{attempts++;if(attempts==1)throw java.io.IOException("offline")}
assertTrue(runCatching{retry.report(80000,100000,80)}.isFailure)
retry.report(81000,100000,80);retry.report(90000,100000,80);assertEquals(2,attempts)
}
@Test fun heroInterleavesCategoriesAndExcludesContinueWatchingAndWatchedTitles() {
val recent=title("recent");val rated=title("rated","show");val suggested=title("suggested")
val continuing=title("continue");val watched=title("watched").copy(watched=true)
val episode=title("ep","episode").copy(grandparentId="ongoing")
val result=homeFeatures(listOf(recent,continuing,watched,title("ongoing","show")),listOf(rated),
listOf(Hub("movie.curated","Suggestions",listOf(suggested)),Hub("recentlyviewed","Watched",listOf(title("excluded")))),listOf(continuing,episode))
assertEquals(listOf("recent","rated","suggested"),result.map{it.item.id})
assertEquals(listOf("Recently released","Highly rated · Unwatched","Suggested for you"),result.map{it.reason})
}
@Test fun heroRemovesDuplicatesAndGracefullyHandlesEmptyCategories() {
val item=title("same")
assertEquals(1,homeFeatures(listOf(item),listOf(item),listOf(Hub("curated","",listOf(item))),emptyList()).size)
assertTrue(homeFeatures(emptyList(),emptyList(),emptyList(),emptyList()).isEmpty())
assertTrue(homeFeatures(listOf(item.copy(art="")),emptyList(),emptyList(),emptyList()).isEmpty())
}
}

View file

@ -0,0 +1,67 @@
package tv.kaleido.app
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.runBlocking
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/** Integration tests use the privately provisioned session. No fixture responses. */
@RunWith(AndroidJUnit4::class)
class LivePlexTest {
private val app get()=InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as KaleidoApplication
private val api get()=app.api.apply {session=app.secure.load()}
@Test fun serverIdentityAndEncryptedPersistence()=runBlocking {
val session=app.secure.load() ?: error("Provision a test session first")
val validated=api.validate(session)
assertTrue(validated.machineId.isNotBlank())
val stored=app.getSharedPreferences("kaleido",0).getString("session","").orEmpty()
assertFalse(stored.contains(session.serverToken))
assertFalse(stored.contains(session.server))
}
@Test fun liveLibraryPaginationFiltersSearchAndDetails()=runBlocking {
val section=api.sections().first{it.type=="movie"}
val first=api.library(section.id)
assertTrue(first.total>0);assertTrue(first.items.isNotEmpty())
if(first.total>100){val second=api.library(section.id,100);assertTrue(second.items.isNotEmpty());assertTrue(first.items.map{it.id}.intersect(second.items.map{it.id}.toSet()).isEmpty())}
val genres=api.genres(section.id);assertTrue(genres.isNotEmpty())
val filtered=api.library(section.id,genre=genres.first().first)
assertTrue(filtered.items.isNotEmpty());assertTrue(filtered.total<=first.total)
val title=first.items.first();val detail=api.details(title.id)
assertEquals(title.title,detail.title);assertTrue(detail.media.first().parts.first().key.startsWith("/library/parts/"))
assertTrue(api.search(title.title).any{it.id==title.id})
assertTrue(api.hubs().isNotEmpty());assertTrue(api.hubs(section.id).isNotEmpty())
}
@Test fun liveShowsSeasonsEpisodesAndMarkers()=runBlocking {
val section=api.sections().first{it.type=="show"}
val show=api.library(section.id).items.first()
val seasons=api.children(show.id);assertTrue(seasons.isNotEmpty())
val episodes=api.children(seasons.first().id);assertTrue(episodes.isNotEmpty())
val episode=api.details(episodes.first().id)
assertEquals("episode",episode.type);assertTrue(episode.media.first().parts.isNotEmpty())
assertTrue(api.allEpisodes(show.id).size>=episodes.size)
assertTrue(episode.markers.all{it.end>it.start})
}
@Test fun livePlexPinEndpoint()=runBlocking {
val pin=api.newPin();assertTrue(pin.id.isNotBlank());assertTrue(pin.code.isNotBlank());assertNull(api.pollPin(pin))
}
@Test fun liveGeneratedPreviewAndNewSeasons()=runBlocking {
val showSection=api.sections().first{it.type=="show"}
val seasons=api.recentSeasons(showSection.id)
assertTrue(seasons.isNotEmpty());assertTrue(seasons.all{it.type=="season"&&it.parentTitle.isNotBlank()})
val episode=api.details("7599") // Known live test episode with generated preview indexes.
assertTrue(episode.chapters.isNotEmpty())
val preview=api.previewPath(episode,90000) ?: error("No server preview path")
val request=okhttp3.Request.Builder().url(api.url(preview)).apply{api.headers().forEach{(k,v)->header(k,v)}}.build()
api.http.newCall(request).execute().use{response->
assertEquals(200,response.code);assertTrue(response.header("Content-Type").orEmpty().startsWith("image/"));assertTrue(response.body!!.bytes().size>100)
}
}
@Test fun liveDirectStreamCopiesSupportedVideo()=runBlocking {
val episode=api.details("7599") // HEVC test episode supported by this onn.
val decision=api.container("/video/:/transcode/universal/decision",api.transcodeParams(episode,"kaleido-remux-regression",1,90000,20000))
val streams=decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()}.flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}
assertEquals("copy",streams.first{it.optInt("streamType")==1}.optString("decision"))
}
}

View file

@ -0,0 +1,44 @@
package tv.kaleido.app
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.*
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PreviewMetadataTest {
private fun item(id:String)=Title.parse(JSONObject("""{"ratingKey":"$id","title":"$id","type":"movie"}"""))
@Test fun predictionStartsBeforeLandingAndVisiblePreviewSharesTheRequest()=runBlocking {
supervisorScope {
val started=CompletableDeferred<Unit>();val finish=CompletableDeferred<Unit>();var calls=0
val cache=PreviewMetadata(this){target->calls++;started.complete(Unit);finish.await();target.copy(summary="Full metadata")}
cache.anticipate(item("destination"));started.await()
assertEquals(1,calls) // Already loading before the visible preview asks for it.
val visible=async{cache.details(item("destination"))};yield();assertEquals(1,calls)
finish.complete(Unit);assertEquals("Full metadata",visible.await().summary)
assertEquals("Full metadata",cache.details(item("destination")).summary);assertEquals(1,calls)
}
}
@Test fun rapidNavigationReplacesQueuedPredictionsAndKeepsOnlyTheLatest()=runBlocking {
supervisorScope {
val started=CompletableDeferred<Unit>();val finish=CompletableDeferred<Unit>();val calls=mutableListOf<String>()
val cache=PreviewMetadata(this){target->calls.add(target.id);if(target.id=="a"){started.complete(Unit);finish.await()};target}
cache.anticipate(item("a"));started.await();cache.anticipate(item("b"));cache.anticipate(item("c"));finish.complete(Unit)
withTimeout(1000){while("c" !in calls)yield()}
assertEquals(listOf("a","c"),calls)
}
}
@Test fun cacheIsBoundedExpiresAndInvalidatesAcrossSessions()=runBlocking {
supervisorScope {
var now=0L;val calls=mutableListOf<String>()
val cache=PreviewMetadata(this,capacity=2,maxAgeMs=100,clock={now}){target->calls.add(target.id);target}
cache.details(item("a"));cache.details(item("b"));cache.details(item("a"));cache.details(item("c"))
assertEquals(listOf("a","b","c"),calls)
cache.details(item("b"));assertEquals(4,calls.size)
now=101;cache.details(item("b"));assertEquals(5,calls.size)
cache.clear();cache.details(item("b"));assertEquals(6,calls.size)
}
}
}

View file

@ -0,0 +1,13 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-feature android:name="android.software.leanback" android:required="true" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<application android:name=".KaleidoApplication" android:label="Kaleido" android:icon="@drawable/icon" android:banner="@drawable/banner" android:theme="@style/Theme.Kaleido" android:allowBackup="false" android:usesCleartextTraffic="true" android:supportsRtl="true">
<activity android:name=".MainActivity" android:exported="true" android:screenOrientation="landscape" android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|uiMode" android:launchMode="singleTop">
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LEANBACK_LAUNCHER" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
</activity>
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.files" android:exported="false" android:grantUriPermissions="true"><meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /></provider>
</application>
</manifest>

View file

@ -0,0 +1,6 @@
# App browsing paths supplement Compose's bundled library profiles.
HSPLtv/kaleido/app/MainActivity;->onCreate(Landroid/os/Bundle;)V
HPLtv/kaleido/app/FocusedBrowseKt**->**(**)**
HPLtv/kaleido/app/BrowseScreensKt**->**(**)**
HPLtv/kaleido/app/DiscoveryScreensKt**->**(**)**
HPLtv/kaleido/app/ThemeKt**->**(**)**

View file

@ -0,0 +1,66 @@
package tv.kaleido.app
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.json.JSONObject
import java.io.File
import java.security.MessageDigest
import java.util.concurrent.TimeUnit
data class Release(val version: String,val url: String,val checksumUrl: String?,val notes: String)
object Versions {
fun newer(candidate: String,current: String): Boolean {
fun parts(v:String)=v.removePrefix("v").split('.').map {it.toIntOrNull() ?: return emptyList<Int>()}
val a=parts(candidate);val b=parts(current);if(a.isEmpty()||b.isEmpty())return false
for(i in 0 until maxOf(a.size,b.size)){val d=a.getOrElse(i){0}.compareTo(b.getOrElse(i){0});if(d!=0)return d>0};return false
}
}
class AppUpdater(private val context: Context) {
companion object {const val REPOSITORY="https://git.elijahkuntz.com/Elijah/Kaleido";const val API="https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido/releases/latest"}
private val client=OkHttpClient.Builder().connectTimeout(15,TimeUnit.SECONDS).readTimeout(60,TimeUnit.SECONDS).followRedirects(false).build()
private fun checkedUrl(url: String): String {
val u=url.toHttpUrl();require(u.scheme=="https"&&u.host=="git.elijahkuntz.com"&&u.username.isEmpty()&&u.password.isEmpty()){ "The release asset address is not trusted." };return url
}
private fun fetch(url:String): String=client.newCall(Request.Builder().url(checkedUrl(url)).header("Accept","application/json").build()).execute().use{r -> if(r.code==404)return "";check(r.isSuccessful){"Release server returned ${r.code}."};r.body!!.string()}
suspend fun latest(): Release? = withContext(Dispatchers.IO) {
val raw=fetch(API)
if(raw.isBlank()) {
val manifest=fetch(REPOSITORY+"/raw/branch/main/distribution/latest.json")
if(manifest.isBlank())return@withContext null
val m=JSONObject(manifest)
if(!Versions.newer(m.getString("version"),BuildConfig.VERSION_NAME))return@withContext null
return@withContext Release(m.getString("version"),checkedUrl(m.getString("url")),checkedUrl(m.getString("checksumUrl")),m.optString("notes"))
}
val j=JSONObject(raw);if(j.optBoolean("draft")||j.optBoolean("prerelease")||!Versions.newer(j.optString("tag_name"),BuildConfig.VERSION_NAME))return@withContext null
val assets=j.optJSONArray("assets").objects();val apk=assets.firstOrNull{it.optString("name")=="Kaleido.apk"} ?: assets.firstOrNull{it.optString("name").endsWith(".apk")} ?: error("This release has no Android APK.")
val sha=assets.firstOrNull{it.optString("name")==apk.optString("name")+".sha256"}
Release(j.getString("tag_name").removePrefix("v"),checkedUrl(apk.getString("browser_download_url")),sha?.getString("browser_download_url")?.let(::checkedUrl),j.optString("body"))
}
suspend fun download(release: Release,onProgress: (Int)->Unit): File = withContext(Dispatchers.IO) {
val dir=File(context.cacheDir,"updates").apply{mkdirs()};val part=File(dir,"Kaleido.apk.part");val file=File(dir,"Kaleido.apk");part.delete();file.delete()
try {
client.newCall(Request.Builder().url(checkedUrl(release.url)).build()).execute().use {r ->
check(r.isSuccessful){"APK download failed (${r.code})."};val body=r.body ?: error("Empty APK response.");val length=body.contentLength();require(length<=200*1024*1024){"APK exceeds the download limit."}
var bytes=0L;var last=-1;body.byteStream().use {input->part.outputStream().use {out->val buffer=ByteArray(65536);while(true){val n=input.read(buffer);if(n<0)break;bytes+=n;require(bytes<=200*1024*1024){"APK exceeds the download limit."};out.write(buffer,0,n);val p=if(length>0)(bytes*100/length).toInt()else 0;if(p!=last){onProgress(p);last=p}}}}
}
release.checksumUrl?.let {u ->val expected=fetch(u).trim().split(Regex("\\s+")).first().lowercase();val hash=MessageDigest.getInstance("SHA-256");part.inputStream().use{input->val b=ByteArray(65536);while(true){val n=input.read(b);if(n<0)break;hash.update(b,0,n)}};val actual=hash.digest().joinToString(""){"%02x".format(it)};require(expected.matches(Regex("[0-9a-f]{64}"))&&expected==actual){"The APK checksum does not match. Download rejected."} }
val pm=context.packageManager
@Suppress("DEPRECATION")
val installed=pm.getPackageInfo(context.packageName,PackageManager.GET_SIGNING_CERTIFICATES)
@Suppress("DEPRECATION")
val archive=pm.getPackageArchiveInfo(part.path,PackageManager.GET_SIGNING_CERTIFICATES) ?: error("The download is not a valid APK.")
require(archive.packageName==context.packageName){"The update belongs to a different application."}
require(archive.longVersionCode>installed.longVersionCode){"The APK version is not newer than this installation."}
val original=installed.signingInfo?.apkContentsSigners?.map{it.toCharsString()}?.toSet()
val incoming=archive.signingInfo?.apkContentsSigners?.map{it.toCharsString()}?.toSet()
require(!original.isNullOrEmpty()&&original==incoming){"The APK signing certificate does not match Kaleido."}
check(part.renameTo(file)){"Could not finalize the update download."};file
} catch(e:Exception){part.delete();throw e}
}
}

View file

@ -0,0 +1,29 @@
package tv.kaleido.app
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/** Local vector badges; ratings and their provider identities always come from Plex. */
@Composable internal fun AudienceRatings(item:Title,modifier:Modifier=Modifier) {
val scores=item.audienceScores
if(scores.isNotEmpty())Row(modifier.clearAndSetSemantics{contentDescription=item.rating},
verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(12.dp)) {
scores.forEach{score->Row(verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(4.dp)) {
when(score.source) {
"Rotten Tomatoes"->Image(painterResource(if(score.value>=6)R.drawable.audience_popcorn else R.drawable.audience_popcorn_spilled),null,Modifier.size(18.dp))
"IMDb"->Image(painterResource(R.drawable.rating_imdb),null,Modifier.width(44.dp).height(24.dp))
else->Text("TVDB",color=Cinema.secondary,fontSize=9.sp)
}
Text(score.displayValue,color=Cinema.secondary,fontSize=10.sp,lineHeight=14.sp)
}}
}
}

View file

@ -0,0 +1,56 @@
package tv.kaleido.app
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable fun KaleidoMark(modifier:Modifier=Modifier) {
Image(painterResource(R.drawable.brand_mark),"Kaleido",modifier)
}
@Composable fun BoxScope.WatchBadge(item:Title,watchedPercent:Int=80) {
val watched=item.isWatched(watchedPercent)
val remaining=item.type in listOf("show","season")&&item.leafCount>0&&!watched
if(watched||remaining)Box(
Modifier.align(Alignment.BottomEnd).padding(7.dp).heightIn(min=22.dp).widthIn(min=22.dp)
.background(Color(0xED101615),CircleShape).padding(horizontal=6.dp,vertical=3.dp)
.semantics{contentDescription=item.watchStatus(watchedPercent)},contentAlignment=Alignment.Center
) {
if(watched)Icon(Icons.Filled.Check,null,tint=Color(0xFFB9E4CF),modifier=Modifier.size(15.dp))
else Text(item.remainingEpisodes.toString(),color=Color.White,fontSize=10.sp,lineHeight=14.sp,fontWeight=FontWeight.SemiBold)
}
}
@Composable fun StartupSplash(alpha:Float) {
val reveal=remember{Animatable(0f)}
LaunchedEffect(Unit){reveal.animateTo(1f,tween(1100,easing=FastOutSlowInEasing))}
Box(Modifier.fillMaxSize().graphicsLayer{this.alpha=alpha}.background(Ink),contentAlignment=Alignment.Center) {
Column(horizontalAlignment=Alignment.CenterHorizontally,modifier=Modifier.graphicsLayer{
val progress=reveal.value
this.alpha=progress.coerceAtMost(1f)
scaleX=.78f+.22f*progress;scaleY=scaleX
}) {
KaleidoMark(Modifier.size(102.dp).graphicsLayer{rotationZ=-30f*(1f-reveal.value)})
Text("KALEIDO",color=Accent,fontSize=24.sp,fontWeight=FontWeight.Medium,letterSpacing=6.sp,modifier=Modifier.padding(top=22.dp))
}
}
}

View file

@ -0,0 +1,62 @@
package tv.kaleido.app
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Shader
import android.graphics.drawable.BitmapDrawable
import android.content.Context
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.graphics.asImageBitmap
import coil.compose.AsyncImage
import coil.imageLoader
import coil.request.SuccessResult
import coil.memory.MemoryCache
import coil.request.ImageRequest
import coil.size.Size
import coil.transform.Transformation
/** Bake contrast into the cached bitmap on Coil's worker thread, not two screen-sized GPU passes per frame. */
private class BrowseContrast(val cinematic:Boolean):Transformation {
override val cacheKey="kaleido-browse-contrast-v2-$cinematic"
override suspend fun transform(input:Bitmap,size:Size):Bitmap {
val output=input.copy(Bitmap.Config.ARGB_8888,true)
val canvas=Canvas(output)
val paint=Paint(Paint.ANTI_ALIAS_FLAG)
paint.shader=LinearGradient(0f,0f,output.width.toFloat(),0f,intArrayOf(0xFF090909.toInt(),0xD9090909.toInt(),0x00090909),floatArrayOf(0f,.28f,.65f),Shader.TileMode.CLAMP)
canvas.drawRect(0f,0f,output.width.toFloat(),output.height.toFloat(),paint)
paint.shader=LinearGradient(0f,0f,0f,output.height.toFloat(),intArrayOf(0x1F000000,0x00090909,0xD6090909.toInt(),0xFF090909.toInt()),if(cinematic)floatArrayOf(0f,.55f,.85f,1f)else floatArrayOf(0f,.35f,.62f,1f),Shader.TileMode.CLAMP)
canvas.drawRect(0f,0f,output.width.toFloat(),output.height.toFloat(),paint)
return output
}
}
internal fun browseBackdropRequest(context:Context,api:PlexApi,path:String,cinematic:Boolean):ImageRequest? =
api.image(path,if(cinematic)1280 else 960,if(cinematic)720 else 540)?.let{url->
ImageRequest.Builder(context).data(url).apply{api.headers().forEach{(k,v)->addHeader(k,v)}}
.size(if(cinematic)1280 else 960,if(cinematic)720 else 540).allowHardware(false)
.transformations(BrowseContrast(cinematic)).crossfade(false).build()
}
@Composable internal fun BrowseBackdrop(api:PlexApi,path:String,modifier:Modifier,cinematic:Boolean=false,animate:Boolean=false) {
val context=LocalContext.current
var previous by remember{mutableStateOf<MemoryCache.Key?>(null)}
val request=remember(path,api.session?.server,cinematic,animate){browseBackdropRequest(context,api,path,cinematic)?.newBuilder()?.placeholderMemoryCacheKey(previous)?.build()}
if(animate) {
// Animate cache hits too; Coil intentionally skips its own crossfade for memory-cache results.
val bitmap by produceState<Bitmap?>(null,request){
if(request!=null){val result=context.imageLoader.execute(request);if(result is SuccessResult){previous=result.memoryCacheKey;value=(result.drawable as? BitmapDrawable)?.bitmap}}
}
Crossfade(bitmap,modifier=modifier,animationSpec=tween(220),label="heroArtwork"){loaded->
loaded?.let{Image(it.asImageBitmap(),null,contentScale=ContentScale.Crop,modifier=Modifier.fillMaxSize())}
}
}else AsyncImage(request,contentDescription=null,modifier=modifier,contentScale=ContentScale.Crop,onSuccess={previous=it.result.memoryCacheKey})
}

View file

@ -0,0 +1,193 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.lazy.grid.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.*
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.*
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
@Composable fun Brand() {
Row(verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
KaleidoMark(Modifier.size(29.dp))
Text("KALEIDO",color=Accent,fontSize=19.sp,lineHeight=24.sp,fontWeight=FontWeight.Bold,letterSpacing=1.4.sp)
}
}
@Composable fun TopBar(vm:KaleidoViewModel,navigation:DiscoveryNavigation?=null) {
val initialFocus by remember{derivedStateOf{vm.focusId.isBlank()}}
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
// Extend the scrim beyond the controls so it dissolves into the scene without a hard edge.
Box(Modifier.fillMaxWidth().height(62.dp).drawBehind {
val depth=if(immersive)size.height*1.8f else size.height
val colors=if(!immersive)listOf(Ink,Ink)else if(navigation?.scrolled==true)listOf(Color.Black.copy(alpha=.93f),Color.Black.copy(alpha=.66f),Color.Black.copy(alpha=.18f),Color.Transparent)else listOf(Color.Black.copy(alpha=.64f),Color.Black.copy(alpha=.22f),Color.Transparent)
drawRect(Brush.verticalGradient(colors,endY=depth),size=Size(size.width,depth))
}.padding(horizontal=Cinema.gutter)) {
Box(Modifier.align(Alignment.CenterStart)){Brand()}
Row(Modifier.align(Alignment.Center).onPreviewKeyEvent{
if(navigation!=null&&it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){navigation.enter?.invoke();true}else false
}.focusProperties{if(navigation!=null)down=navigation.entry},horizontalArrangement=Arrangement.spacedBy(16.dp),verticalAlignment=Alignment.CenterVertically) {
listOf("home" to "Home","movies" to "Movies","tv" to "TV Shows").forEach{(kind,label)->
NavigationLabel(label,vm.page.kind==kind,modifier=if(navigation!=null&&vm.page.kind==kind)Modifier.focusRequester(navigation.top)else Modifier,initialFocus=vm.page.kind==kind&&initialFocus,onFocused={if(vm.page.kind!=kind)vm.tab(kind)}){if(vm.page.kind!=kind)vm.tab(kind)}
}
}
Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(9.dp)) {
IconControl(Icons.Outlined.Search,"Search",selected=vm.page.kind=="search"){vm.tab("search")}
Box {
IconControl(Icons.Outlined.Settings,"Settings",selected=vm.page.kind=="settings"){vm.tab("settings")}
if(vm.update!=null)Box(Modifier.size(4.dp).align(Alignment.TopEnd).padding(top=2.dp).background(Accent,RoundedCornerShape(2.dp)))
}
}
}
}
@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null) {
Column {
Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading(title,subtitle)}
LazyRow(contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=5.dp,bottom=5.dp),horizontalArrangement=Arrangement.spacedBy(if(landscape)13.dp else 12.dp),modifier=Modifier.focusRestorer()) {
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,onMove={anticipateTileMove(vm,items,index,it,0)})}
}
}
}
private fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
val target=when(direction){
Key.DirectionLeft->if(columns==0||index%columns>0)index-1 else -1
Key.DirectionRight->if(columns==0||index%columns<columns-1)index+1 else -1
Key.DirectionUp->if(columns>0)index-columns else -1
Key.DirectionDown->if(columns>0)index+columns else -1
else->-1
}
items.getOrNull(target)?.let{vm.anticipate(it,backdrop=false)}
}
@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,onMove:(Key)->Unit={}) {
var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()}
val scale by animateFloatAsState(if(focused)1.035f else 1f,tween(180),label="artworkFocus")
LaunchedEffect(Unit){if(vm.focusId==focusKey){delay(220);runCatching{requester.requestFocus()}}}
Column((if(fillWidth)Modifier.fillMaxWidth()else Modifier.width(if(landscape)216.dp else 132.dp)).onPreviewKeyEvent{if(it.type==KeyEventType.KeyDown)onMove(it.key);false}.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey}.clickable{vm.open(item)}) {
Box(Modifier.fillMaxWidth().aspectRatio(if(landscape)16f/9f else 2f/3f).graphicsLayer{shadowElevation=if(focused)12.dp.toPx()else 0f;shape=RoundedCornerShape(Cinema.radius)}.clip(RoundedCornerShape(Cinema.radius))) {
val artwork=if(landscape&&item.type=="episode")item.thumb.ifBlank{item.art}else if(landscape)item.art.ifBlank{item.thumb}else item.thumb
Artwork(vm.api,artwork,Modifier.fillMaxSize(),if(landscape)720 else 450,if(landscape)405 else 675)
if(item.offset>0)Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().padding(start=7.dp,end=7.dp,bottom=6.dp).height(2.dp).background(Color.Black.copy(alpha=.45f),RoundedCornerShape(1.dp))) {
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.015f)).fillMaxHeight().background(Accent,RoundedCornerShape(1.dp)))
}
WatchBadge(item,vm.watchedPercent)
if(focused)Box(Modifier.fillMaxSize().border(1.5.dp,Accent,RoundedCornerShape(Cinema.radius)))
}
Text(if(landscape)item.displayTitle else item.title,color=if(focused)Accent else Cinema.secondary,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp))
Text(if(landscape)item.subtitle else item.year.ifBlank{item.subtitle},color=Muted,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=1.dp))
}
}
@Composable fun LibraryScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation) {
if(!vm.allTitles){DiscoveryScreen(vm,home=false,navigation=navigation);return}
val name=if(vm.page.kind=="movies")"Movies"else "TV Shows"
var sortMenu by remember{mutableStateOf(false)}
var genreMenu by remember{mutableStateOf(false)}
var sectionMenu by remember{mutableStateOf(false)}
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 · A–Z",vm.allTitles,initialFocus=vm.focusId=="library-entry"){vm.setAll(true)}
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.section==null&&!vm.busy)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")+" ⌄"){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")+" ⌄"){sortMenu=true}
}
val grid=rememberLazyGridState()
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()}}
}
}
}
if(sortMenu)ChoiceDialog("Sort by",sortLabels.map{it.second},sortLabels.indexOfFirst{it.first==vm.sort},{sortMenu=false}){vm.filter(sortValue=sortLabels[it].first);sortMenu=false}
if(genreMenu)ChoiceDialog("Genres",listOf("All genres")+vm.genres.map{it.second},vm.genres.indexOfFirst{it.first==vm.genre}+1,{genreMenu=false}){vm.filter(genreValue=if(it==0)""else vm.genres[it-1].first);genreMenu=false}
if(sectionMenu){val options=vm.sections.filter{it.type==vm.section?.type};ChoiceDialog("Libraries",options.map{it.title},options.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(options[it]);sectionMenu=false}}
}
@Composable fun DetailsScreen(vm:KaleidoViewModel) {
val item=vm.detail ?: return
LazyColumn(contentPadding=PaddingValues(bottom=32.dp),verticalArrangement=Arrangement.spacedBy(15.dp),modifier=Modifier.fillMaxSize()) {
item(key="details") {
Box(Modifier.fillMaxWidth().height(if(item.type in listOf("movie","episode"))432.dp else 304.dp)) {
Artwork(vm.api,item.art,Modifier.fillMaxSize(),1920,1080)
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.83f),Ink.copy(alpha=.05f)))))
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Color.Black.copy(alpha=.12f),.5f to Color.Transparent,1f to Ink)))
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=18.dp)){vm.back()}
Column(Modifier.align(Alignment.CenterStart).padding(start=Cinema.gutter,top=30.dp).width(490.dp)) {
if(item.type=="episode")Text(item.grandparentTitle,color=Cinema.secondary,fontSize=12.sp,lineHeight=17.sp,fontWeight=FontWeight.Medium)
Text(item.title,color=Accent,fontSize=34.sp,lineHeight=37.sp,fontWeight=FontWeight.Bold,letterSpacing=(-1).sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(bottom=9.dp))
Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.subtitle,item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Muted,fontSize=10.5.sp,lineHeight=16.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(item,Modifier.padding(start=12.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.5.sp,lineHeight=19.sp,maxLines=if(item.type in listOf("movie","episode"))4 else 3,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=11.dp,bottom=18.dp))
if(item.type!="collection")Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
ActionButton(if(item.offset>0)"Resume · ${item.offset/60000} min"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,primary=true,initialFocus=true){vm.play(item)}
if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay){vm.play(item,true)}
if(item.type in listOf("movie","episode"))IconControl(if(item.isWatched(vm.watchedPercent))Icons.Outlined.CheckCircle else Icons.Outlined.Check,"Mark ${if(item.isWatched(vm.watchedPercent))"unwatched"else "watched"}",selected=item.isWatched(vm.watchedPercent)){vm.mark(item)}
}
if(item.media.isNotEmpty())Text(item.media.first().let{m->listOf(m.resolution.uppercase(),m.videoCodec.uppercase(),m.audioCodec.uppercase()).joinToString(" · ")},color=Muted,fontSize=9.sp,lineHeight=13.sp,modifier=Modifier.padding(top=16.dp))
if(item.cast.isNotEmpty())Text(item.cast.take(5).joinToString(" · "),color=Cinema.quiet,fontSize=10.sp,lineHeight=15.sp,maxLines=2,modifier=Modifier.padding(top=8.dp))
}
}
}
if(vm.children.isNotEmpty())item{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")}
}
}
@Composable fun SearchScreen(vm:KaleidoViewModel) {
Column(Modifier.fillMaxSize().padding(horizontal=Cinema.gutter)) {
Row(Modifier.fillMaxWidth().padding(top=12.dp,bottom=18.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(25.dp)) {
Text("Search",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)
val requester=remember{FocusRequester()}
LaunchedEffect(Unit){delay(150);requester.requestFocus()}
OutlinedTextField(vm.query,{vm.search(it)},placeholder={Text("Movies, shows, episodes",fontSize=12.sp)},leadingIcon={Icon(Icons.Outlined.Search,null,Modifier.size(19.dp))},singleLine=true,modifier=Modifier.weight(1f).height(49.dp).focusRequester(requester),shape=RoundedCornerShape(6.dp),textStyle=androidx.compose.ui.text.TextStyle(fontSize=13.sp),colors=OutlinedTextFieldDefaults.colors(unfocusedBorderColor=Color.White.copy(alpha=.15f),focusedBorderColor=Accent))
Text(if(vm.query.isBlank())"Your collection"else "${vm.searchResults.size} results",color=Muted,fontSize=11.sp)
}
if(vm.query.isBlank())Text("Find something worth watching.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(top=8.dp))
LazyVerticalGrid(GridCells.Fixed(3),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),contentPadding=PaddingValues(top=8.dp,bottom=30.dp)) {
itemsIndexed(vm.searchResults,key={_,it->it.id}){index,item->MediaTile(vm,item,"search:${item.id}",landscape=true,fillWidth=true,onMove={anticipateTileMove(vm,vm.searchResults,index,it,3)})}
}
}
}

View file

@ -0,0 +1,98 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.ChevronRight
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.compose.AsyncImagePainter
import coil.request.ImageRequest
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class DiscoveryNavigation {
val entry=FocusRequester()
val section=FocusRequester()
val top=FocusRequester()
var scrolled by mutableStateOf(false)
var enter:(()->Unit)?=null
}
/** Preserve server-supplied recommendations, but give each destination an editorial purpose. */
internal fun editorialHubs(source:List<Hub>,destination:String):List<Hub> {
val available=source.filterNot{it.title.equals("On Deck",true)&&source.any{h->h.title.contains("Continue",true)}}
fun rank(hub:Hub):Int=when(destination) {
"movies"->when {
hub.id.contains("recentlyreleased")->0
hub.id.contains("topunwatched")->1
hub.id.contains("recentlyadded")->2
hub.id.contains("genre")->3
hub.id.contains("curated")->4
hub.id.contains("inprogress")->5
hub.id.contains("recentlyviewed")->9
else->6
}
"tv"->when {
hub.id.contains("inprogress")->0
hub.id.contains("newseasons")->1
hub.id.contains("recentlyaired")->2
hub.id.contains("startwatching")->3
hub.id.contains("toprated")->3
hub.id.contains("recentlyadded")->4
hub.id.contains("rediscover")->5
hub.id.contains("recentlyviewed")->9
else->6
}
else->0
}
return available.sortedBy(::rank).mapNotNull {hub->
// Plex often returns the exact same episode set in both of these TV hubs.
if(destination=="tv"&&hub.id.contains("recentlyadded")&&available.any{it.id.contains("recentlyaired")&&it.items.map{t->t.id}==hub.items.map{t->t.id}})null
else hub.copy(title=when {
destination=="tv"&&hub.id.contains("inprogress")->"Next episodes"
destination=="tv"&&hub.id.contains("recentlyaired")->"New episodes"
destination=="movies"&&hub.id.contains("recentlyreleased")->"Recently released"
destination=="movies"&&hub.id.contains("topunwatched")->"Movies to discover"
else->hub.title
})
}
}
/** Plex's original transparent title treatment; fallback remains real title text. */
@Composable internal fun TitleIdentity(api:PlexApi,item:Title,modifier:Modifier=Modifier,small:Boolean=false) {
val context=LocalContext.current
var loaded by remember(item.logo){mutableStateOf(false)}
val request=remember(item.logo,api.session?.server){item.logo.takeIf{it.startsWith("/")}?.let{path->ImageRequest.Builder(context).data(api.url(path)).apply{api.headers().forEach{(k,v)->addHeader(k,v)}}.crossfade(120).size(if(small)500 else 600,180).build()}}
Box(modifier.semantics{contentDescription=item.displayTitle},contentAlignment=Alignment.BottomStart) {
if(!loaded)Text(item.displayTitle,color=Accent,fontSize=if(small)14.sp else 43.sp,lineHeight=if(small)17.sp else 46.sp,fontWeight=FontWeight.Bold,letterSpacing=if(small)(-.2).sp else (-1).sp,maxLines=2,overflow=TextOverflow.Ellipsis)
if(request!=null)AsyncImage(request,contentDescription=null,contentScale=ContentScale.Fit,alignment=Alignment.BottomStart,modifier=Modifier.fillMaxSize(),onState={loaded=it is AsyncImagePainter.State.Success})
}
}

View file

@ -0,0 +1,267 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.Animatable
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.material3.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.ChevronRight
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.*
import androidx.compose.ui.text.font.FontWeight
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.launch
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.first
import androidx.compose.runtime.saveable.rememberSaveable
@Composable fun HomeScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation)=DiscoveryScreen(vm,true,navigation)
private object BrowseScroll:BringIntoViewSpec {
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float)=0f
}
private suspend fun LazyListState.animateBrowseTo(index:Int) {
val visible=layoutInfo.visibleItemsInfo.firstOrNull{it.index==index}
if(visible!=null)animateScrollBy(visible.offset.toFloat(),tween(220))else animateScrollToItem(index)
}
/** The preview never scrolls. Only the bounded catalog below it moves. */
@Composable fun DiscoveryScreen(vm:KaleidoViewModel,home:Boolean,navigation:DiscoveryNavigation) {
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 list=rememberLazyListState(initialFirstVisibleItemIndex=restore?.let{it.first+if(home)1 else 0} ?: 0)
val rowStates=remember(hubs){List(hubs.size){row->LazyListState(firstVisibleItemIndex=if(restore?.first==row)restore.second else 0)}}
val requesters=remember(hubs){mutableMapOf<Pair<Int,Int>,FocusRequester>()}
val columns=remember(hubs){mutableMapOf<Int,Int>()}
val navigationJob=remember{arrayOfNulls<Job>(1)}
val scope=rememberCoroutineScope()
val density=LocalDensity.current
val hovered=remember{mutableStateOf<Title?>(null)}
val sectionEntry by remember{derivedStateOf{vm.focusId=="discovery-entry"}}
val features=vm.homeFeatures
var featureIndex by rememberSaveable{mutableIntStateOf(0)}
val nextFeature=features.getOrNull(featureIndex % features.size.coerceAtLeast(1))
var selectedFeature by remember{mutableStateOf(nextFeature)}
val heroFade=remember{Animatable(1f)}
LaunchedEffect(nextFeature?.item?.id){
if(home)nextFeature?.item?.let{vm.anticipate(it,cinematic=true)}
if(home&&selectedFeature!=null&&nextFeature!=null)heroFade.animateTo(0f,tween(100))
selectedFeature=nextFeature
heroFade.animateTo(1f,tween(180))
}
val feature=selectedFeature?.item
val activeFeature=rememberUpdatedState(feature)
var heroActive by remember{mutableStateOf(restore==null)}
var rotating by remember{mutableStateOf(true)}
LaunchedEffect(home,features,heroActive,rotating,featureIndex){
if(home&&heroActive&&rotating&&features.size>1){delay(12000);featureIndex=(featureIndex+1)%features.size}
}
val heroFocus=remember{FocusRequester()}
val rowOffset=if(home)1 else 0
suspend fun moveToRow(row:Int,column:Int)=coroutineScope {
val state=rowStates.getOrNull(row) ?: return@coroutineScope
val scrolling=launch{list.animateBrowseTo(row+rowOffset)}
state.scrollToItem(column)
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()}
scrolling.join()
}
suspend fun moveToHero()=coroutineScope {
val scrolling=launch{list.animateBrowseTo(0)}
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==0}}.first{it}
withFrameNanos{};runCatching{heroFocus.requestFocus()};scrolling.join()
}
LaunchedEffect(home,features.isNotEmpty()){if(home&&vm.focusId=="home-feature"){list.scrollToItem(0);withFrameNanos{};runCatching{heroFocus.requestFocus()}}}
DisposableEffect(navigation,list,hubs){
navigation.scrolled=false
navigation.enter={(if(home)activeFeature.value else hubs.firstOrNull()?.items?.firstOrNull())?.let{vm.anticipate(it,cinematic=home)};navigationJob[0]?.cancel();navigationJob[0]=scope.launch{list.animateBrowseTo(0);rowStates.firstOrNull()?.scrollToItem(0);withFrameNanos{};runCatching{(if(home)heroFocus else navigation.section).requestFocus()}}}
onDispose{navigation.enter=null}
}
val title=when(destination){"movies"->"Movies";"tv"->"TV Shows";else->"Home"}
BoxWithConstraints(Modifier.fillMaxSize()) {
val heroHeight=maxHeight*.80f-62.dp
if(home)HomeBackdrop(vm.api,hovered,feature,heroActive)
else FocusedPreviewCanvas(vm,hovered,hubs.firstOrNull()?.items?.firstOrNull(),destination)
Column(Modifier.fillMaxSize().padding(top=62.dp)) {
if(!home) {
Row(Modifier.fillMaxWidth().height(39.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) {
Text(title,color=Accent,fontSize=19.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(end=20.dp))
if(!home) {
NavigationLabel("Discover",true,modifier=Modifier.focusRequester(navigation.section).focusProperties{up=navigation.top;down=navigation.entry},initialFocus=sectionEntry){}
NavigationLabel("Library · A–Z",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry}){vm.setAll(true)}
}
}
Spacer(Modifier.fillMaxWidth().height(if(destination=="movies")137.dp else 119.dp))
}
CompositionLocalProvider(LocalBringIntoViewSpec provides BrowseScroll) {
LazyColumn(state=list,modifier=Modifier.fillMaxWidth().weight(1f),verticalArrangement=Arrangement.spacedBy(15.dp),contentPadding=PaddingValues(bottom=22.dp)) {
if(home)item(key="home-feature") {
Box(Modifier.fillMaxWidth().height(heroHeight)) {
feature?.let{item->
val metadata by produceState(item,item.id){value=item;value=vm.previewDetails(item)}
Column(Modifier.align(Alignment.BottomStart).padding(start=Cinema.gutter,bottom=35.dp).width(350.dp)) {
Column(Modifier.graphicsLayer{alpha=heroFade.value}) {
Eyebrow(selectedFeature?.reason.orEmpty())
Spacer(Modifier.height(9.dp))
TitleIdentity(vm.api,item,Modifier.width(264.dp).height(80.dp))
Row(Modifier.fillMaxWidth().padding(top=8.dp,bottom=8.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.year,item.genres.firstOrNull().orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=10.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(metadata,Modifier.padding(start=10.dp))
}
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
}.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)}
if(features.size>1)IconControl(Icons.Outlined.ChevronRight,"Next featured title",modifier=Modifier.focusProperties{up=navigation.top},onFocused={rotating=false}){featureIndex=(featureIndex+1)%features.size}
}
}
Row(Modifier.align(Alignment.BottomCenter).padding(bottom=8.dp),horizontalArrangement=Arrangement.spacedBy(5.dp)) {
features.forEachIndexed{i,_->Box(Modifier.size(if(i==featureIndex)12.dp else 3.dp,3.dp).background(Accent.copy(alpha=if(i==featureIndex).9f else .35f),RoundedCornerShape(2.dp)))}
}
}
}
}
itemsIndexed(hubs,key={_,h->h.id},contentType={_,h->if(h.items.firstOrNull()?.type=="episode")"episodes"else "titles"}) {row,hub->
val poster=hub.items.firstOrNull()?.type in listOf("movie","show","season")&&!hub.title.contains("Continue",true)&&(destination=="movies"||destination=="tv"||row==1)
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)) {
itemsIndexed(hub.items,key={_,t->t.id},contentType={_,_->poster}) {column,item->
val requester=requesters.getOrPut(row to column){FocusRequester()}
BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)navigation.entry else null,requester,
Modifier.onPreviewKeyEvent{event->
if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionLeft,Key.DirectionRight)) {
val target=column+if(event.key==Key.DirectionLeft)-1 else 1
if(target in hub.items.indices) {
vm.anticipate(hub.items[target],cinematic=home)
navigationJob[0]?.cancel()
val state=rowStates[row]
val visible=state.layoutInfo.visibleItemsInfo.any{it.index==target}
if(visible)runCatching{requesters.getOrPut(row to target){FocusRequester()}.requestFocus()}
navigationJob[0]=scope.launch {
val anchor=(target-1).coerceAtLeast(0)
if(visible) {
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))
}else{state.scrollToItem(anchor);withFrameNanos{};runCatching{requesters.getOrPut(row to target){FocusRequester()}.requestFocus()}}
}
}
true
}else if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionUp,Key.DirectionDown)) {
if(event.key==Key.DirectionUp&&row==0) {
if(home)feature?.let{vm.anticipate(it,cinematic=true)}
navigationJob[0]?.cancel()
navigationJob[0]=scope.launch{if(home)moveToHero()else{withFrameNanos{};runCatching{navigation.section.requestFocus()}}}
}
else {
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)
vm.anticipate(hubs[target].items[col],cinematic=home)
navigationJob[0]=scope.launch{moveToRow(target,col)}
}
}
true
}else false
},onHovered={columns[row]=column;hovered.value=it;heroActive=false})
}
}
}
}
}
}
}
if(hubs.isEmpty()&&vm.busy)CircularProgressIndicator(color=Accent,strokeWidth=2.dp,modifier=Modifier.size(25.dp).align(Alignment.Center))
if(!home&&hubs.isEmpty()&&!vm.busy)Column(Modifier.align(Alignment.Center),horizontalAlignment=Alignment.CenterHorizontally){
Text(if(vm.section==null)"No $title library on this server"else "No recommendations available",color=Accent,fontSize=18.sp)
Spacer(Modifier.height(14.dp));TvButton("Open library",onClick={vm.setAll(true)});Spacer(Modifier.height(8.dp));TvButton("Try again",onClick={vm.retry()})
}
}
}
/** Focus changes invalidate this small preview scope, never the catalog hierarchy. */
@Composable private fun HomeBackdrop(api:PlexApi,hovered:State<Title?>,feature:Title?,heroActive:Boolean) {
var displayed by remember{mutableStateOf<Title?>(null)}
val current=if(heroActive)feature else hovered.value ?: feature
LaunchedEffect(current?.id){if(!heroActive)delay(90);displayed=current}
(displayed ?: feature)?.let{BrowseBackdrop(api,it.art.ifBlank{it.thumb},Modifier.fillMaxSize(),cinematic=true,animate=heroActive)}
}
@Composable private fun FocusedPreviewCanvas(vm:KaleidoViewModel,hovered:State<Title?>,fallback:Title?,destination:String) {
var displayed by remember{mutableStateOf<Title?>(null)}
val current=hovered.value
LaunchedEffect(current?.id){delay(120);displayed=current}
val feature=displayed ?: fallback
val metadata by produceState(feature,feature?.id){value=feature;feature?.let{value=vm.previewDetails(it)}}
Box(Modifier.fillMaxSize()) {
feature?.let{item->
BrowseBackdrop(vm.api,item.art,Modifier.fillMaxSize())
Column(Modifier.padding(start=Cinema.gutter,top=106.dp).width(350.dp).clearAndSetSemantics{contentDescription=listOf(item.displayTitle,metadata?.rating.orEmpty(),item.summary).filter{it.isNotBlank()}.joinToString(". ")}) {
TitleIdentity(vm.api,item,Modifier.width(if(destination=="tv")230.dp else 260.dp).height(if(destination=="tv")43.dp else 53.dp))
Row(Modifier.fillMaxWidth().padding(top=7.dp,bottom=5.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else item.year,item.genres.firstOrNull().orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),fontSize=10.sp,lineHeight=14.sp,color=Cinema.secondary,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(metadata ?: item,Modifier.padding(start=10.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=11.5.sp,lineHeight=16.sp,maxLines=2,overflow=TextOverflow.Ellipsis)
}
}
}
}
@Composable private fun BrowseCard(vm:KaleidoViewModel,item:Title,focusKey:String,poster:Boolean,wideEpisode:Boolean,entry:FocusRequester?,requester:FocusRequester,modifier:Modifier,onHovered:(Title)->Unit) {
var focused by remember{mutableStateOf(false)}
val width=if(poster)120.dp else if(wideEpisode)264.dp else 214.dp
val image=if(poster)item.poster.ifBlank{item.thumb}else if(item.type=="episode")item.still.ifBlank{item.thumb}.ifBlank{item.art}else item.art.ifBlank{item.thumb}
LaunchedEffect(Unit){if(vm.focusId==focusKey){withFrameNanos{};runCatching{requester.requestFocus()};onHovered(item)}}
Column(modifier.width(width).then(if(entry!=null)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).onFocusChanged{
focused=it.isFocused
if(it.isFocused){vm.focusId=focusKey;onHovered(item)}
}.clickable{vm.open(item)}.clearAndSetSemantics{
contentDescription=listOf(item.displayTitle,item.subtitle,item.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(". ")
this.focused=focused;role=Role.Button
onClick{vm.open(item);true}
}) {
Box(Modifier.fillMaxWidth().aspectRatio(if(poster)2f/3f else 16f/9f).clip(RoundedCornerShape(4.dp))) {
Artwork(vm.api,image,Modifier.fillMaxSize(),if(poster)300 else 480,if(poster)450 else 270,animate=false)
if(item.offset>0&&!poster)Box(Modifier.align(Alignment.BottomCenter).padding(6.dp).fillMaxWidth().height(2.dp).background(Color.Black.copy(alpha=.65f))) {
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.01f)).fillMaxHeight().background(Accent))
}
WatchBadge(item,vm.watchedPercent)
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Color.White,RoundedCornerShape(4.dp)))
}
Text(item.displayTitle,color=if(focused)Accent else Cinema.secondary,fontSize=10.5.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=5.dp).height(16.dp))
if(!poster)Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else if(item.offset>0)"${((item.duration-item.offset)/60000).coerceAtLeast(0)} min left"else item.year,color=Muted,fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.height(14.dp))
}
}

View file

@ -0,0 +1,28 @@
package tv.kaleido.app
data class HomeFeature(val item:Title,val reason:String)
/** Interleave discovery categories; Continue Watching has its own rail. */
internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,continuing:List<Title>):List<HomeFeature> {
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")},
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")}
)
val seen=mutableSetOf<String>()
return buildList {
val queues=buckets.map{it.toMutableList()}
while(size<12&&queues.any{it.isNotEmpty()})for(queue in queues){
while(queue.isNotEmpty()) {
val feature=queue.removeAt(0)
if(seen.add(feature.item.id)){add(feature);break}
}
if(size>=12)break
}
}
}

View file

@ -0,0 +1,17 @@
package tv.kaleido.app
import android.app.Application
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.disk.DiskCache
import coil.memory.MemoryCache
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.Dispatchers
class KaleidoApplication: Application(), ImageLoaderFactory {
val scope = CoroutineScope(SupervisorJob()+Dispatchers.IO)
val secure by lazy { SecureSession(this) }
val api by lazy { PlexApi(secure.clientId).apply { session=secure.load() } }
override fun newImageLoader() = ImageLoader.Builder(this).okHttpClient(api.http).memoryCache { MemoryCache.Builder(this).maxSizePercent(.12).build() }.diskCache { DiskCache.Builder().directory(cacheDir.resolve("artwork")).maxSizeBytes(250L*1024*1024).build() }.crossfade(250).build()
}

View file

@ -0,0 +1,272 @@
package tv.kaleido.app
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import org.json.JSONObject
import coil.imageLoader
import coil.request.Disposable
import java.util.concurrent.Executors
import kotlinx.coroutines.asCoroutineDispatcher
data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="")
private data class SectionContent(val hubs:List<Hub>,val genres:List<Pair<String,String>>,val library:LibraryPage)
class KaleidoViewModel(app: Application): AndroidViewModel(app) {
val application = app as KaleidoApplication
val api = application.api
val preferences = app.getSharedPreferences("preferences",0)
val updater = AppUpdater(app)
var session by mutableStateOf(api.session); private set
var pages by mutableStateOf(listOf(Page())); private set
val page get()=pages.last()
var busy by mutableStateOf(false); private set
var error by mutableStateOf<String?>(null); private set
var sections by mutableStateOf(emptyList<Section>()); private set
var homeHubs by mutableStateOf(emptyList<Hub>()); private set
var homeFeatures by mutableStateOf(emptyList<HomeFeature>()); private set
var discoverHubs by mutableStateOf(emptyList<Hub>()); private set
var library by mutableStateOf(emptyList<Title>()); private set
var total by mutableStateOf(0); private set
var genres by mutableStateOf(emptyList<Pair<String,String>>()); private set
var section by mutableStateOf<Section?>(null); private set
var sort by mutableStateOf("titleSort:asc"); private set
var genre by mutableStateOf(""); private set
var unwatched by mutableStateOf(false); private set
var allTitles by mutableStateOf(false); private set
var detail by mutableStateOf<Title?>(null); private set
var children by mutableStateOf(emptyList<Title>()); private set
var searchResults by mutableStateOf(emptyList<Title>()); private set
var query by mutableStateOf(""); private set
var pin by mutableStateOf<Pin?>(null); private set
var servers by mutableStateOf(emptyList<Server>()); private set
var linkingAccount by mutableStateOf(false);private set
var accountToken = session?.accountToken.orEmpty()
var playing by mutableStateOf<Title?>(null); private set
var startFromZero by mutableStateOf(false); private set
var focusId by mutableStateOf("")
var update by mutableStateOf<Release?>(null); private set
var updateStatus by mutableStateOf(""); private set
var downloadedApk by mutableStateOf<File?>(null); private set
var downloading by mutableStateOf(false); private set
var playbackMode by mutableStateOf(preferences.getInt("playbackModeV2",1)); private set
var watchedPercent by mutableStateOf(preferences.getInt("watchedPercent",80).coerceIn(50,100)); 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
private var episodeContextJob:Job?=null
private var episodeTransitionJob:Job?=null
var quality by mutableStateOf(preferences.getInt("quality",20000)); private set
private var loadJob: Job? = null
private var initializeJob:Job?=null
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 val previews=PreviewMetadata(viewModelScope){api.details(it.id)}
private var predictedArtwork:Disposable?=null
private var predictedArtworkKey=""
private val artworkPrefetchDispatcher=Executors.newSingleThreadExecutor{task->
Thread({android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);task.run()},"KaleidoArtworkPrefetch").apply{isDaemon=true}
}.asCoroutineDispatcher()
init {
// Development provisioning is private app data, never an APK resource or build constant.
if(BuildConfig.DEBUG) {
val seed=File(app.filesDir,"bootstrap.json")
if(seed.exists()) {
runCatching { val j=JSONObject(seed.readText()); val s=Session("",j.getString("token"),j.getString("server"),"Plex",""); application.secure.save(s);api.session=s;session=s }
seed.delete()
}
}
if(session!=null) initialize() else linkAccount()
checkUpdate(false)
}
private fun launchLoad(block: suspend () -> Unit) {
val generation=++loadGeneration
loadJob?.cancel()
loadJob=viewModelScope.launch {
busy=true;error=null
try { block() } catch(e: CancellationException){throw e} catch(e: Exception){error=e.message ?: "Something went wrong. Please try again."} finally {if(generation==loadGeneration)busy=false}
}
}
fun dismissError(){error=null}
fun initialize() {
if(initializeJob?.isActive==true)return
initializeJob=viewModelScope.launch {
busy=true;error=null
try {
val validated=api.validate(session ?: return@launch)
api.session=validated;session=validated;application.secure.save(validated)
sections=api.sections();homeHubs=loadHome()
if(page.kind in listOf("movies","tv"))loadPage(true)
}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message ?: "Cannot load this server."}
finally{if(loadJob?.isActive!=true)busy=false}
}
}
private suspend fun loadHome(): List<Hub> = 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 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) }
}
suspend fun previewDetails(item:Title):Title {
return try{previews.details(item)}catch(e:CancellationException){throw e}catch(_:Exception){item}
}
fun anticipate(item:Title,cinematic:Boolean=false,backdrop:Boolean=true) {
previews.anticipate(item)
val path=item.art.ifBlank{item.thumb}
val key=if(backdrop)"$cinematic:$path"else ""
if(key!=predictedArtworkKey){
predictedArtwork?.dispose();predictedArtwork=null;predictedArtworkKey=key
if(backdrop)browseBackdropRequest(application,api,path,cinematic)?.let{predictedArtwork=application.imageLoader.enqueue(it.newBuilder().dispatcher(artworkPrefetchDispatcher).build())}
}
}
private fun cancelAnticipation(){previews.cancelPrediction();predictedArtwork?.dispose();predictedArtwork=null;predictedArtworkKey=""}
override fun onCleared(){cancelAnticipation();artworkPrefetchDispatcher.close();super.onCleared()}
fun linkAccount() {
authJob?.cancel();error=null;pin=null
authJob=viewModelScope.launch {
try {
pin=api.newPin()
repeat(180) {
delay(2000)
val token=api.pollPin(pin ?: return@launch)
if(token!=null){accountToken=token;pin=null;servers=api.servers(token);if(servers.size==1)chooseServer(servers.first());return@launch}
}
error="This code has expired. Get a new code to continue."
} catch(e:CancellationException){throw e} catch(e:Exception){error=e.message ?: "Cannot contact Plex."}
}
}
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()
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()
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 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;cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv"))allTitles=false;pages=listOf(Page(kind));loadPage(true)}
fun open(item: Title){detailsCache[item.id]=item;pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()}
fun back(): Boolean {
if(playing!=null){stopPlayback();return true}
if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);loadPage();return true}
if(page.kind!="home"){tab("home");return true}
return false
}
fun retry(){if(session==null)linkAccount() else if(sections.isEmpty())initialize() else loadPage()}
private fun loadPage(resetLibrary: Boolean=false) {
when(page.kind){
"home" -> if(homeHubs.isEmpty())launchLoad { homeHubs=loadHome() }
"movies","tv" -> {
if(sections.isEmpty()){initialize();return}
val type=if(page.kind=="movies")"movie"else "show"
if(!resetLibrary&&section?.type==type&&library.isNotEmpty()&&discoverHubs.isNotEmpty())return
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]
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
launchLoad {coroutineScope {
val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id)}
val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(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()
sectionCache[s.id]=SectionContent(rows,genreList,p)
discoverHubs=rows;genres=genreList;library=p.items;total=p.total
}}
}
"details","group" -> { detail=detailsCache[page.id];children=emptyList();launchLoad { val id=page.id;val d=detailsCache[id]?.let{previews.details(it)} ?: api.details(id);detail=d;detailsCache[id]=d;previews.remember(d);if(d.type in listOf("show","season","collection"))children=api.children(id) } }
"search" -> {busy=false;error=null}
"settings" -> {busy=false;error=null}
}
}
fun chooseSection(s: Section){section=s;genre="";sort="titleSort:asc";launchLoad {genres=api.genres(s.id);discoverHubs=api.hubs(s.id);val p=api.library(s.id);library=p.items;total=p.total}}
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 search(text: String){query=text;searchJob?.cancel();searchJob=viewModelScope.launch {delay(350);if(text.isBlank()){searchResults=emptyList();return@launch};busy=true;error=null;try{searchResults=api.search(text)}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message}finally{busy=false}}}
fun mark(item: Title)=launchLoad {
api.watched(item,!item.isWatched(watchedPercent));refreshWatchedItems(item)
}
fun refreshWatched(item:Title){viewModelScope.launch{try{refreshWatchedItems(item)}catch(e:CancellationException){throw e}catch(_:Exception){sectionCache.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)
if(d.type=="episode")for(id in listOf(d.parentId,d.grandparentId).filter{it.isNotBlank()}) {
try{updated[id]=api.details(id)}catch(e:CancellationException){throw e}catch(_:Exception){detailsCache.remove(id)}
}
previews.clear();updated.values.forEach{previews.remember(it)};detailsCache.putAll(updated);detail=detail?.let{updated[it.id] ?: it}
fun refreshed(hubs:List<Hub>)=hubs.map{h->h.copy(items=h.items.map{updated[it.id] ?: it})}
homeHubs=refreshed(homeHubs);discoverHubs=refreshed(discoverHubs)
library=library.map{updated[it.id] ?: it};children=children.map{updated[it.id] ?: it}
searchResults=searchResults.map{updated[it.id] ?: it}
homeFeatures=homeFeatures.map{it.copy(item=updated[it.item.id] ?: it.item)}.filterNot{it.item.fullyWatched}
sectionCache.clear()
}
fun play(item: Title,fromStart: Boolean=false)=launchLoad {
val playable=if(item.type=="show" || item.type=="season") {
val episodes=api.allEpisodes(item.id);episodes.firstOrNull {it.offset>0&&!it.watched} ?: episodes.firstOrNull {!it.watched} ?: episodes.firstOrNull() ?: throw PlexException("No playable episodes are available.")
} else item
val d=api.details(playable.id);require(d.media.firstOrNull()?.parts?.isNotEmpty()==true){"No playable media file is available."};startFromZero=fromStart;playing=d
}
fun loadEpisodeContext(item:Title) {
if(item.type!="episode")return
if(episodeQueue.any{it.id==item.id})return
episodeContextJob?.cancel();episodeQueue=emptyList();relatedShows=emptyList()
episodeContextJob=viewModelScope.launch {
coroutineScope {
val episodes=async{runCatching{api.allEpisodes(item.grandparentId)}.getOrDefault(emptyList())}
val related=async{runCatching{api.relatedShows(item.grandparentId)}.getOrDefault(emptyList())}
episodeQueue=episodes.await().sortedWith(compareBy<Title>{it.parentIndex}.thenBy{it.index})
relatedShows=related.await()
}
}
}
fun followingEpisode(item:Title):Title? {val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>=0)episodeQueue.getOrNull(i+1)else null}
fun nextEpisode(item: Title) {
if(episodeTransitionJob?.isActive==true)return
episodeTransitionJob=viewModelScope.launch {
transitioningEpisode=true
try {
val episodes=if(episodeQueue.any{it.id==item.id})episodeQueue else api.allEpisodes(item.grandparentId).sortedWith(compareBy<Title>{it.parentIndex}.thenBy{it.index})
val i=episodes.indexOfFirst{it.id==item.id};val next=if(i>=0)episodes.getOrNull(i+1)else null
if(next!=null){val metadata=api.details(next.id);if(playing?.id==item.id){startFromZero=true;playing=metadata}}
else if(playing?.id==item.id)stopPlayback()
}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message ?: "The next episode could not be loaded."}finally{transitioningEpisode=false}
}
}
fun stopPlayback(){playing=null;sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();launchLoad {homeHubs=loadHome();detail?.let {if(it.type in listOf("movie","episode"))detail=api.details(it.id)}}}
fun choosePlaybackMode(value: Int){playbackMode=value;preferences.edit().putInt("playbackModeV2",value).apply()}
fun chooseWatchedPercent(value:Int){watchedPercent=value.coerceIn(50,100);preferences.edit().putInt("watchedPercent",watchedPercent).apply()}
fun chooseQuality(value: Int){quality=value;preferences.edit().putInt("quality",value).apply()}
fun checkUpdate(manual: Boolean=true){viewModelScope.launch {
if(!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch
updateStatus="Checking for updates…"
try{update=updater.latest();preferences.edit().putLong("lastUpdateCheck",System.currentTimeMillis()).apply();updateStatus=if(update==null)"Kaleido is up to date." else "Version ${update!!.version} is available."}catch(e:Exception){updateStatus="Update check failed. ${e.message}"}
}}
fun downloadUpdate(){val release=update ?: return; if(downloading)return;viewModelScope.launch {downloading=true;try {downloadedApk=updater.download(release){progress -> updateStatus="Downloading update · $progress%"};updateStatus="Update verified. Ready to install."}catch(e:Exception){updateStatus=e.message ?: "Download failed."}finally{downloading=false}}}
fun clearDownload(){downloadedApk=null}
fun debugPlay(id: String,offset: Long,mode: Int){if(!BuildConfig.DEBUG)return;launchLoad {playing=null;delay(150);playbackMode=mode;playing=api.details(id).copy(offset=offset);startFromZero=false}}
}

View file

@ -0,0 +1,43 @@
package tv.kaleido.app
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.content.FileProvider
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import java.io.File
class MainActivity: ComponentActivity() {
private val model: KaleidoViewModel by viewModels()
private var pendingApk: File? = null
private val unknownSources=registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if(packageManager.canRequestPackageInstalls()) pendingApk?.let(::installApk)
}
fun installApk(file: File) {
pendingApk=file
if(!packageManager.canRequestPackageInstalls()) {
unknownSources.launch(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,Uri.parse("package:$packageName")));return
}
val uri=FileProvider.getUriForFile(this,"$packageName.files",file)
@Suppress("DEPRECATION")
startActivity(Intent(Intent.ACTION_INSTALL_PACKAGE).setDataAndType(uri,"application/vnd.android.package-archive").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
pendingApk=null;model.clearDownload()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window,false)
WindowInsetsControllerCompat(window,window.decorView).apply{hide(WindowInsetsCompat.Type.systemBars());systemBarsBehavior=WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE}
setContent { KaleidoApp(model,::installApk) }
debugPlayback(intent)
}
override fun onNewIntent(intent: Intent) {super.onNewIntent(intent);setIntent(intent);debugPlayback(intent)}
private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG)intent.getStringExtra("testTitleId")?.let{model.debugPlay(it,intent.getLongExtra("testOffset",90000),intent.getIntExtra("testMode",0))}}
override fun onStart() { super.onStart(); model.checkUpdate(false) }
}

View file

@ -0,0 +1,84 @@
package tv.kaleido.app
import org.json.JSONArray
import org.json.JSONObject
fun JSONArray?.objects(): List<JSONObject> = if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) }
data class Section(val id: String, val title: String, val type: String)
data class Stream(val id: String, val type: Int, val codec: String, val language: String, val title: String, val selected: Boolean, val key: String, val channels: Int, val index: Int)
data class Part(val id: String, val key: String, val streams: List<Stream>,val indexes:String="")
data class Media(val id: String, val container: String, val videoCodec: String, val audioCodec: String, val resolution: String, val width: Int, val height: Int, val bitrate: Int, val parts: List<Part>)
data class Marker(val type: String, val start: Long, val end: Long)
data class Chapter(val index:Int,val title:String,val start:Long,val end:Long,val thumb:String)
data class Title(
val id: String, val key: String, val type: String, val title: String, val summary: String,
val thumb: String, val art: String, val year: String, val duration: Long, val offset: Long,
val watched: Boolean, val rating: String, val contentRating: String, val parentTitle: String,
val grandparentTitle: String, val parentId: String, val grandparentId: String,
val index: Int, val parentIndex: Int, val leafCount: Int, val viewedLeafCount: Int,
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 remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0)
val fullyWatched get() = isWatched()
fun isWatched(percent:Int=80):Boolean = if(type in listOf("show","season")) leafCount>0&&remainingEpisodes==0
else if(offset>0&&duration>0)watched&&reachedWatchedThreshold(offset,duration,percent)else watched
val watchStatus get() = watchStatus()
fun watchStatus(percent:Int=80):String = when {
isWatched(percent) -> "Watched"
type in listOf("show","season")&&leafCount>0 -> "$remainingEpisodes episodes remaining"
else -> ""
}
val displayTitle get() = if (type == "episode") grandparentTitle.ifBlank { title } else title
val subtitle get() = when(type) { "episode" -> "S${parentIndex} · E${index} $title"; "season" -> "$leafCount episodes"; "show" -> "${year} · $leafCount episodes"; else -> listOf(year, if(duration>0) "${duration/60000} min" else "", genres.firstOrNull().orEmpty()).filter { it.isNotBlank() }.joinToString(" · ") }
val progress get() = if(duration>0) (offset.toFloat()/duration).coerceIn(0f,1f) else 0f
companion object {
fun parse(j: JSONObject): Title = Title(
j.optString("ratingKey",j.optString("key")), j.optString("key"), j.optString("type"), j.optString("title"), j.optString("summary"),
j.optString("thumb",j.optString("parentThumb",j.optString("grandparentThumb"))), j.optString("art",j.optString("grandparentArt")), j.optString("year"),j.optLong("duration"),j.optLong("viewOffset"),
j.optInt("viewCount")>0,AudienceScore.parseAll(j).joinToString(" · "){it.label},j.optString("contentRating"),j.optString("parentTitle"),j.optString("grandparentTitle"),j.optString("parentRatingKey"),j.optString("grandparentRatingKey"),
j.optInt("index"),j.optInt("parentIndex"),j.optInt("leafCount"),j.optInt("viewedLeafCount"),j.optJSONArray("Genre").objects().map { it.optString("tag") },j.optJSONArray("Role").objects().take(10).map { it.optString("tag") },
j.optJSONArray("Media").objects().map { m -> Media(m.optString("id"),m.optString("container"),m.optString("videoCodec"),m.optString("audioCodec"),m.optString("videoResolution"),m.optInt("width"),m.optInt("height"),m.optInt("bitrate"),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")) }) },
j.optJSONArray("Marker").objects().map { Marker(it.optString("type"),it.optLong("startTimeOffset"),it.optLong("endTimeOffset")) },
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="clearLogo"}?.optString("url").orEmpty(),
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="coverPoster"}?.optString("url").orEmpty(),
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="snapshot"}?.optString("url").orEmpty(),
j.optJSONArray("Chapter").objects().map{Chapter(it.optInt("index"),it.optString("title","Chapter ${it.optInt("index")+1}"),it.optLong("startTimeOffset"),it.optLong("endTimeOffset"),it.optString("thumb"))},
AudienceScore.parse(j),j.optString("originallyAvailableAt"),AudienceScore.parseAll(j)
)
}
}
/** Plex normalizes external ratings to 0–10. Never substitute the critic `rating` field. */
data class AudienceScore(val source:String,val value:Double) {
val displayValue get() = if(source=="Rotten Tomatoes")"${kotlin.math.round(value*10).toInt()}%"else "${String.format(java.util.Locale.US,"%.1f",value)}/10"
val label get() = "$source ${if(source=="Rotten Tomatoes")"audience "else ""}$displayValue"
companion object {
fun parse(j:JSONObject):AudienceScore? = parseAll(j).firstOrNull()
fun parseAll(j:JSONObject):List<AudienceScore> {
fun score(image:String,value:Double):AudienceScore? {
val source=when {
image.startsWith("rottentomatoes://")&&(image.endsWith("upright")||image.endsWith("spilled")) -> "Rotten Tomatoes"
image.startsWith("imdb://") -> "IMDb"
image.startsWith("thetvdb://")||image.startsWith("tvdb://") -> "TVDB"
else -> return null
}
return if(value.isFinite()&&value in 0.0..10.0)AudienceScore(source,value)else null
}
val scores=j.optJSONArray("Rating").objects().filter{it.optString("type")=="audience"}
.mapNotNull{score(it.optString("image"),it.optDouble("value"))}+
listOfNotNull(score(j.optString("audienceRatingImage"),j.optDouble("audienceRating")))
val ordered=scores.distinctBy{it.source}.sortedBy{listOf("Rotten Tomatoes","IMDb","TVDB").indexOf(it.source)}
return ordered.filter{it.source in listOf("Rotten Tomatoes","IMDb")}.ifEmpty{ordered.take(1)}
}
}
}
internal fun reachedWatchedThreshold(position:Long,duration:Long,percent:Int):Boolean =
duration>0&&position.toDouble()/duration>=percent.coerceIn(50,100)/100.0
data class Hub(val id: String, val title: String, val items: List<Title>)
data class LibraryPage(val items: List<Title>,val total: Int)
data class Server(val id: String, val name: String, val token: String, val connections: List<String>)
data class Session(val accountToken: String, val serverToken: String, val server: String, val serverName: String, val machineId: String)
data class Pin(val id: String,val code: String)

View file

@ -0,0 +1,160 @@
package tv.kaleido.app
import android.view.ViewGroup
import android.view.WindowManager
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.media3.common.*
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.okhttp.OkHttpDataSource
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.exoplayer.trackselection.DefaultTrackSelector
import androidx.media3.session.MediaSession
import androidx.media3.ui.PlayerView
import androidx.media3.common.TrackSelectionOverride
import android.util.Log
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.util.UUID
data class TimelineReport(val position: Long,val state: String,val duration: Long,val final: Boolean=false)
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
private val app=vm.application
val api=vm.api
val scope=CoroutineScope(SupervisorJob()+Dispatchers.Main.immediate)
val selector=DefaultTrackSelector(app)
private val sourceFactory=DefaultMediaSourceFactory(DefaultDataSource.Factory(app,OkHttpDataSource.Factory(api.http).setDefaultRequestProperties(api.headers().filterKeys{it!="Accept"})))
val player=ExoPlayer.Builder(app,DefaultRenderersFactory(app).setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing()).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply {
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),true)
setHandleAudioBecomingNoisy(true)
}
val mediaSession=MediaSession.Builder(app,player).setId("kaleido-${UUID.randomUUID()}").build()
var mode by mutableIntStateOf(vm.playbackMode);private set
var loading by mutableStateOf(true);private set
var error by mutableStateOf<String?>(null);private set
var position by mutableLongStateOf(if(vm.startFromZero)0 else item.offset);private set
var duration by mutableLongStateOf(item.duration);private set
var bufferedPosition by mutableLongStateOf(position);private set
var scrubPosition by mutableStateOf<Long?>(null);private set
var playbackRate by mutableFloatStateOf(1f);private set
private var seekJob:Job?=null
var isPlaying by mutableStateOf(false);private set
var ended by mutableStateOf(false);private set
var tracks by mutableStateOf(Tracks.EMPTY);private set
var activeSubtitle by mutableStateOf(item.media.first().parts.first().streams.firstOrNull{it.type==3&&it.selected}?.id ?: "0");private set
var activeAudio by mutableStateOf(item.media.first().parts.first().streams.firstOrNull{it.type==2&&it.selected}?.id.orEmpty());private set
private var streamSession=UUID.randomUUID().toString()
private var streamStart=0L
private var preparing=false
private var closed=false
private val reports=Channel<TimelineReport>(Channel.UNLIMITED)
private val reportJob=app.scope.launch {
val watched=WatchedProgress{api.watched(item,true);withContext(Dispatchers.Main){vm.refreshWatched(item)}}
for(r in reports) {
runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")}
runCatching{watched.report(r.position,r.duration,vm.watchedPercent)}
.onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")}
if(r.final){if(mode>0)runCatching{api.stopTranscode(streamSession)};break}
}
}
init {
player.addListener(object: Player.Listener {
override fun onPlaybackStateChanged(state: Int) {
loading=state==Player.STATE_BUFFERING;ended=state==Player.STATE_ENDED
if(state==Player.STATE_READY) {preparing=false;error=null;Log.i("KaleidoPlayback","READY item=${item.id} mode=$mode position=${player.currentPosition} video=${player.videoFormat?.codecs} size=${player.videoSize.width}x${player.videoSize.height}")}
if(ended) {position=duration;report("stopped");Log.i("KaleidoPlayback","ENDED")}
}
override fun onIsPlayingChanged(value: Boolean){isPlaying=value;if(!preparing&&!closed)report(if(value)"playing"else "paused")}
override fun onTracksChanged(value: Tracks){tracks=value;Log.i("KaleidoPlayback","TRACKS audio=${value.groups.count{it.type==C.TRACK_TYPE_AUDIO}} text=${value.groups.count{it.type==C.TRACK_TYPE_TEXT}}")}
override fun onPlayerError(e: PlaybackException) {
Log.w("KaleidoPlayback","ERROR code=${e.errorCodeName} mode=$mode")
if(mode<2){scope.launch{prepare(mode+1,position)}}else{loading=false;error="Playback failed (${e.errorCodeName}). Check the server transcoder, network connection, and media availability."}
}
})
scope.launch {prepare(mode,position)}
scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=player.bufferedPosition.coerceIn(0,duration);val d=player.duration;if(d>0)duration=if(mode>0)item.duration else d};if(++ticks%40==0&&!preparing&&!ended)report(if(isPlaying)"playing"else "paused")}}
}
private fun currentPosition() = player.currentPosition.coerceIn(0,duration.coerceAtLeast(0))
private fun report(state: String,final: Boolean=false){reports.trySend(TimelineReport(position,state,duration,final))}
suspend fun prepare(newMode: Int,offset: Long,resume:Boolean=true) {
if(closed)return
preparing=true;loading=true;error=null;ended=false;player.stop()
try {
if(mode>0)runCatching{api.stopTranscode(streamSession)}
mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=if(mode>0)offset else 0L
val media=item.media.first();val part=media.parts.first()
val builder=MediaItem.Builder().setMediaId(item.id).setMediaMetadata(MediaMetadata.Builder().setTitle(item.title).setArtist(item.grandparentTitle).build())
if(mode==0) {
builder.setUri(api.url(part.key))
builder.setSubtitleConfigurations(part.streams.filter{it.type==3&&it.key.isNotBlank()&&it.codec in listOf("srt","webvtt","vtt","ass","ssa")}.map {s ->
MediaItem.SubtitleConfiguration.Builder(android.net.Uri.parse(api.url(s.key))).setId(s.id).setLabel(s.title).setLanguage(s.language).setMimeType(when(s.codec){"srt"->MimeTypes.APPLICATION_SUBRIP;"ass","ssa"->MimeTypes.TEXT_SSA;else->MimeTypes.TEXT_VTT}).setSelectionFlags(if(s.id==activeSubtitle)C.SELECTION_FLAG_DEFAULT else 0).build()
})
} else {
val p=api.transcodeParams(item,streamSession,mode,offset,vm.quality)
val decision=api.container("/video/:/transcode/universal/decision",p)
if(decision.optInt("generalDecisionCode")>=2000)throw PlexException(decision.optString("generalDecisionText","Server cannot convert this media."))
builder.setUri(api.url("/video/:/transcode/universal/start.m3u8",p)).setMimeType(MimeTypes.APPLICATION_M3U8)
}
// Plex HLS exposes the original absolute timeline, including a seek-start offset.
player.setMediaItem(builder.build(),offset);player.prepare();player.playWhenReady=resume;player.setPlaybackSpeed(playbackRate)
Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset")
}catch(e:CancellationException){throw e}catch(e:Exception){if(newMode<2)prepare(newMode+1,offset)else{preparing=false;loading=false;error=e.message ?: "The server could not start playback."}}
}
fun seekTo(target:Long){val clamped=target.coerceIn(0,duration);if(mode>0&&clamped<streamStart){val resume=player.playWhenReady;scope.launch{prepare(mode,clamped,resume)}}else{player.seekTo(clamped);position=clamped;report(if(isPlaying)"playing"else "paused")}}
fun toggle(){if(player.isPlaying)player.pause()else{if(ended)seekTo(0);player.play()}}
fun retry(){scope.launch{prepare(mode,position)}}
fun changeMode(value:Int){val resume=player.playWhenReady;vm.choosePlaybackMode(value);scope.launch{prepare(value,position,resume)}}
fun changeQuality(value:Int){val resume=player.playWhenReady;vm.chooseQuality(value);if(mode>0)scope.launch{prepare(mode,position,resume)}}
fun changeSpeed(value:Float){playbackRate=value;player.setPlaybackSpeed(value)}
fun scrubBy(delta:Long){scrubPosition=((scrubPosition ?: position)+delta).coerceIn(0,duration);seekJob?.cancel();seekJob=scope.launch{delay(650);commitScrub()}}
fun commitScrub(){val target=scrubPosition ?: return;scrubPosition=null;seekTo(target)}
fun pause(){player.pause();position=currentPosition();report("paused")}
fun select(type:Int,groupIndex:Int,trackIndex:Int) {
val group=tracks.groups[groupIndex];selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,false).setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup,listOf(trackIndex))).build()
}
fun selectServerStream(stream:Stream?,type:Int) {
scope.launch {
try {
val part=item.media.first().parts.first()
if(type==C.TRACK_TYPE_TEXT){activeSubtitle=stream?.id ?: "0";api.selectStreams(part,subtitle=activeSubtitle)}else{activeAudio=stream?.id.orEmpty();api.selectStreams(part,audio=activeAudio)}
if(mode>0){prepare(mode,position,player.playWhenReady);return@launch}
if(stream==null){selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return@launch}
val groups=tracks.groups.withIndex().filter{it.value.type==type}
val matching=groups.flatMap{g->(0 until g.value.length).map{g.index to it}}.firstOrNull{(g,t)->tracks.groups[g].getTrackFormat(t).id==stream.id}
val matchingExternal=if(type==C.TRACK_TYPE_TEXT&&stream.key.isNotBlank())matching else null
val streamIndex=part.streams.filter{it.type==(if(type==C.TRACK_TYPE_AUDIO)2 else 3)&&it.key.isBlank()}.indexOfFirst{it.id==stream.id}
val candidates=groups.flatMap{g->(0 until g.value.length).map{g.index to it}}
val match=matchingExternal ?: matching ?: candidates.getOrNull(streamIndex)
if(match!=null)select(type,match.first,match.second)
else prepare(2,position) // Image subtitles and unsupported embedded tracks are burned by Plex.
}catch(e:Exception){error=e.message ?: "Could not change the selected track."}
}
}
fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();report("stopped",true);reports.close();mediaSession.release();player.release()}
}
fun clockTime(ms:Long):String {val s=(ms.coerceAtLeast(0)/1000);return if(s>=3600)"%d:%02d:%02d".format(s/3600,s/60%60,s%60)else "%d:%02d".format(s/60,s%60)}

View file

@ -0,0 +1,82 @@
package tv.kaleido.app
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
@Composable internal fun PlaybackOptions(vm:KaleidoViewModel,controller:PlaybackController,item:Title,menu:Int,open:(Int)->Unit,close:()->Unit) {
val modes=listOf("Original file","Direct stream","Transcode")
val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f)
val dismiss={if(menu==3)close()else open(3)}
when(menu) {
3->TrackPanel("Playback options",listOf("Mode · ${modes[controller.mode]}","Audio language","Subtitles","Speed · ${controller.playbackRate}×","Transcode quality", "Chapters"),0,dismiss){index->open(when(index){0->4;1->1;2->2;3->5;4->6;else->7})}
4->TrackPanel("Playback mode",modes,controller.mode,dismiss){controller.changeMode(it);close()}
5->TrackPanel("Playback speed",speeds.map{"${it}×"},speeds.indexOf(controller.playbackRate),dismiss){controller.changeSpeed(speeds[it]);close()}
6->TrackPanel("Transcode quality",listOf("1080p · 20 Mbps","4K · 80 Mbps"),if(vm.quality>20000)1 else 0,dismiss){controller.changeQuality(if(it==0)20000 else 80000);close()}
7->TrackPanel("Chapters",item.chapters.map{"${it.title} · ${clockTime(it.start)}"},item.chapters.indexOfLast{it.start<=controller.position},dismiss){controller.seekTo(item.chapters[it].start);close()}
}
}
@Composable internal fun PostPlayScreen(vm:KaleidoViewModel,item:Title,dismiss:()->Unit,next:()->Unit) {
val upcoming=vm.followingEpisode(item)
var autoplay by remember{mutableStateOf(true)}
var seconds by remember{mutableIntStateOf(5)}
LaunchedEffect(autoplay,upcoming?.id) {
if(autoplay&&upcoming!=null){seconds=5;android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}");repeat(5){delay(1000);seconds--};android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()}
}
val season=vm.episodeQueue.filter{it.parentId==item.parentId}
LazyColumn(Modifier.fillMaxSize().background(Color.Black.copy(alpha=.93f)),contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=29.dp),verticalArrangement=Arrangement.spacedBy(15.dp)) {
item {
Text(if(upcoming!=null)"Up next"else "More to watch",color=Accent,fontSize=25.sp,fontWeight=FontWeight.SemiBold)
Row(Modifier.padding(top=13.dp),horizontalArrangement=Arrangement.spacedBy(20.dp),verticalAlignment=Alignment.CenterVertically) {
if(upcoming!=null)Artwork(vm.api,upcoming.still.ifBlank{upcoming.thumb},Modifier.width(205.dp).aspectRatio(16f/9f).clip(RoundedCornerShape(5.dp)),480,270,animate=false)
Column(Modifier.weight(1f)) {
Text(upcoming?.displayTitle ?: item.displayTitle,color=Accent,fontSize=21.sp,fontWeight=FontWeight.SemiBold)
Text(upcoming?.let{"S${it.parentIndex} · E${it.index} ${it.title}"} ?: "You've reached the end of this series.",color=Cinema.secondary,fontSize=12.sp,modifier=Modifier.padding(top=5.dp,bottom=15.dp))
Row(horizontalArrangement=Arrangement.spacedBy(10.dp),verticalAlignment=Alignment.CenterVertically) {
if(upcoming!=null)ActionButton(if(vm.transitioningEpisode)"Loading…"else if(autoplay)"Play in $seconds"else "Play now",Icons.Filled.PlayArrow,modifier=Modifier.onFocusChanged{if(it.isFocused&&BuildConfig.DEBUG)android.util.Log.i("KaleidoPlayback","POSTPLAY focus=play")},primary=true,initialFocus=true){autoplay=false;next()}
if(upcoming!=null)TvButton(if(autoplay)"Cancel autoplay"else "Autoplay off"){autoplay=!autoplay;android.util.Log.i("KaleidoPlayback","AUTOPLAY ${if(autoplay)"enabled"else "cancelled"} item=${item.id}")}
TvButton("Back to video"){autoplay=false;dismiss()}
}
}
}
}
if(season.isNotEmpty())item {PostPlayRail(vm,"Episodes in this season",season){autoplay=false;vm.play(it,true)}}
if(vm.relatedShows.isNotEmpty())item {PostPlayRail(vm,"Related shows",vm.relatedShows){autoplay=false;vm.stopPlayback();vm.open(it)}}
}
}
@Composable private fun PostPlayRail(vm:KaleidoViewModel,label:String,titles:List<Title>,choose:(Title)->Unit) {
Column {
Text(label,color=Accent,fontSize=16.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=8.dp))
LazyRow(horizontalArrangement=Arrangement.spacedBy(12.dp)) {
items(titles,key={it.id}){title->
var focused by remember{mutableStateOf(false)}
Column(Modifier.width(167.dp).onFocusChanged{focused=it.isFocused}.semantics{contentDescription=title.displayTitle+" "+title.subtitle}.clickable{choose(title)}) {
Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).clip(RoundedCornerShape(4.dp))) {
Artwork(vm.api,if(title.type=="episode")title.still.ifBlank{title.thumb}else title.art.ifBlank{title.thumb},Modifier.fillMaxSize(),384,216,animate=false)
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(4.dp)))
}
Text(if(title.type=="episode")"${title.index}. ${title.title}"else title.title,color=if(focused)Accent else Cinema.secondary,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=4.dp))
}
}
}
}
}

View file

@ -0,0 +1,215 @@
package tv.kaleido.app
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalActivity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.core.tween
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.outlined.*
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.automirrored.outlined.VolumeUp
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.*
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.*
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.media3.common.C
import androidx.media3.ui.PlayerView
import android.view.ViewGroup
import android.view.WindowManager
import kotlinx.coroutines.delay
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable fun PlaybackScreen(vm:KaleidoViewModel,item:Title) {
val controller=remember{PlaybackController(vm,item)}
val activity=LocalActivity.current as MainActivity
val owner=LocalLifecycleOwner.current
var controls by remember{mutableStateOf(true)}
var interaction by remember{mutableLongStateOf(0)}
var trackMenu by remember{mutableIntStateOf(0)}
var postPlay by remember{mutableStateOf(false)}
var seekFocus by remember{mutableStateOf(false)}
var restoreMenuFocus by remember{mutableIntStateOf(0)}
val rootFocus=remember{FocusRequester()}
val timelineFocus=remember{FocusRequester()}
val playFocus=remember{FocusRequester()}
val audioFocus=remember{FocusRequester()}
val subtitleFocus=remember{FocusRequester()}
val optionsFocus=remember{FocusRequester()}
fun interacted(){interaction=System.currentTimeMillis()}
fun closeTracks(){restoreMenuFocus=trackMenu;trackMenu=0;interacted()}
LaunchedEffect(item.id){vm.loadEpisodeContext(item)}
LaunchedEffect(controller.ended){if(controller.ended&&item.type=="episode"){android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=ended");postPlay=true}}
DisposableEffect(controller) {
activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
val observer=LifecycleEventObserver{_,event->if(event==Lifecycle.Event.ON_STOP)controller.pause()}
owner.lifecycle.addObserver(observer)
onDispose{owner.lifecycle.removeObserver(observer);activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);controller.close()}
}
LaunchedEffect(controls,interaction,controller.isPlaying,trackMenu) {
if(controls&&controller.isPlaying&&trackMenu==0){delay(5000);controls=false}
}
LaunchedEffect(controls) {if(!controls){delay(210);runCatching{rootFocus.requestFocus()}}}
LaunchedEffect(seekFocus,controls) {if(seekFocus&&controls){delay(220);runCatching{timelineFocus.requestFocus()};seekFocus=false}}
LaunchedEffect(restoreMenuFocus,trackMenu) {if(restoreMenuFocus!=0&&trackMenu==0){delay(16);runCatching{(when(restoreMenuFocus){1->audioFocus;2->subtitleFocus;else->optionsFocus}).requestFocus()};restoreMenuFocus=0}}
fun goBack(){if(postPlay)postPlay=false else if(trackMenu!=0)closeTracks()else if(controls)controls=false else vm.stopPlayback()}
BackHandler(onBack=::goBack)
val visible=controls&&!postPlay
Box(Modifier.fillMaxSize().background(Color.Black).focusRequester(rootFocus).onPreviewKeyEvent{event->
if(event.key==Key.Back){if(event.type==KeyEventType.KeyDown)goBack();true}
else if(event.type!=KeyEventType.KeyDown||postPlay)false else {
interacted()
when(event.nativeKeyEvent.keyCode) {
android.view.KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE->{controller.toggle();controls=true;true}
android.view.KeyEvent.KEYCODE_MEDIA_PLAY->{controller.player.play();controls=true;true}
android.view.KeyEvent.KEYCODE_MEDIA_PAUSE->{controller.pause();controls=true;true}
android.view.KeyEvent.KEYCODE_MEDIA_FAST_FORWARD->{controller.seekTo(controller.position+30000);controls=true;seekFocus=true;true}
android.view.KeyEvent.KEYCODE_MEDIA_REWIND->{controller.seekTo(controller.position-10000);controls=true;seekFocus=true;true}
android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER->{if(!visible){controls=true;true}else false}
android.view.KeyEvent.KEYCODE_DPAD_LEFT,android.view.KeyEvent.KEYCODE_DPAD_RIGHT->{if(!visible){controller.scrubBy(if(event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_LEFT)-10000 else 10000);controls=true;seekFocus=true;true}else false}
android.view.KeyEvent.KEYCODE_DPAD_UP,android.view.KeyEvent.KEYCODE_DPAD_DOWN->{if(!visible){controls=true;seekFocus=event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_UP;true}else false}
else->false
}
}
}.focusable()) {
AndroidView(factory={context->PlayerView(context).apply {
setEnableComposeSurfaceSyncWorkaround(true)
player=controller.player
useController=false
isFocusable=false
descendantFocusability=ViewGroup.FOCUS_BLOCK_DESCENDANTS
setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER)
setKeepContentOnPlayerReset(true)
}},modifier=Modifier.fillMaxSize(),onRelease={it.player=null})
if(controller.loading)CircularProgressIndicator(color=Accent,strokeWidth=2.dp,modifier=Modifier.align(Alignment.Center).size(30.dp))
AnimatedVisibility(visible=visible,enter=fadeIn(tween(190))+slideInVertically(tween(190)){it/8},exit=fadeOut(tween(190))+slideOutVertically(tween(190)){it/10},modifier=Modifier.align(Alignment.BottomCenter)) {
Column(Modifier.fillMaxWidth().background(Brush.verticalGradient(0f to Color.Transparent,.42f to Color.Black.copy(alpha=.46f),1f to Color.Black.copy(alpha=.79f))).padding(start=Cinema.gutter,end=Cinema.gutter,top=31.dp,bottom=16.dp)) {
Row(Modifier.fillMaxWidth().padding(bottom=7.dp),verticalAlignment=Alignment.Bottom) {
Text(item.displayTitle,color=Accent,fontSize=18.sp,lineHeight=23.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f))
Spacer(Modifier.width(18.dp))
Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else listOf("Original","Direct stream","Transcoding")[controller.mode],color=Color.White.copy(alpha=.62f),fontSize=10.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=350.dp))
}
SeekTimeline(controller,item,Modifier.fillMaxWidth().focusRequester(timelineFocus).focusProperties{down=playFocus},::interacted)
Box(Modifier.fillMaxWidth().height(40.dp)) {
Row(Modifier.align(Alignment.CenterStart),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Exit playback",size=30.dp,iconSize=18.dp,onFocused=::interacted){vm.stopPlayback()}
Text(clockTime(controller.position),color=Color.White.copy(alpha=.78f),fontSize=10.sp,lineHeight=14.sp)
}
Row(Modifier.align(Alignment.Center),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(16.dp)) {
IconControl(Icons.Outlined.Replay10,"Back 10 seconds",size=32.dp,iconSize=22.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.seekTo(controller.position-10000);interacted()}
IconControl(if(controller.isPlaying)Icons.Filled.Pause else Icons.Filled.PlayArrow,if(controller.isPlaying)"Pause"else "Play",size=38.dp,iconSize=28.dp,requester=playFocus,initialFocus=controls&&!seekFocus,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.toggle();controls=true;interacted()}
IconControl(Icons.Outlined.Forward30,"Forward 30 seconds",size=32.dp,iconSize=22.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.seekTo(controller.position+30000);interacted()}
}
Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) {
Text("−"+clockTime(controller.duration-controller.position),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,modifier=Modifier.padding(end=8.dp))
if(item.type=="episode")IconControl(Icons.Outlined.SkipNext,"Next episode",size=30.dp,iconSize=21.dp,onFocused=::interacted){vm.nextEpisode(item)}
IconControl(Icons.AutoMirrored.Outlined.VolumeUp,"Audio tracks",size=30.dp,iconSize=21.dp,requester=audioFocus,selected=trackMenu==1,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=1;interacted()}
IconControl(Icons.Outlined.Subtitles,"Subtitles",size=30.dp,iconSize=21.dp,requester=subtitleFocus,selected=trackMenu==2,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=2;interacted()}
IconControl(Icons.Outlined.Settings,"Playback options",size=30.dp,iconSize=21.dp,requester=optionsFocus,selected=trackMenu>=3,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=3;interacted()}
}
}
}
}
val marker=item.markers.firstOrNull{controller.position>=it.start&&controller.position<it.end&&it.type in listOf("intro","credits")}
if(marker!=null&&!postPlay)Box(Modifier.align(Alignment.BottomEnd).padding(end=Cinema.gutter,bottom=if(visible)130.dp else 45.dp)) {
ActionButton(if(marker.type=="intro")"Skip intro"else "Skip credits",Icons.Outlined.ChevronRight,modifier=Modifier.background(Color.Black.copy(alpha=.9f),RoundedCornerShape(5.dp)).border(1.dp,Color.White.copy(alpha=.75f),RoundedCornerShape(5.dp))){if(marker.type=="credits"&&item.type=="episode"){controller.pause();android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=skip-credits");postPlay=true}else controller.seekTo(marker.end);interacted()}
}
if(postPlay)PostPlayScreen(vm,item,{postPlay=false;controls=true},{vm.nextEpisode(item)})
controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})}
if(trackMenu in 1..2) {
val type=if(trackMenu==1)C.TRACK_TYPE_AUDIO else C.TRACK_TYPE_TEXT
val streams=item.media.firstOrNull()?.parts?.firstOrNull()?.streams.orEmpty().filter{it.type==(if(trackMenu==1)2 else 3)}
val options=(if(trackMenu==2)listOf("Off")else emptyList())+streams.map{it.title}
val selected=streams.indexOfFirst{it.id==(if(trackMenu==1)controller.activeAudio else controller.activeSubtitle)}+if(trackMenu==2)1 else 0
TrackPanel(if(trackMenu==1)"Audio"else "Subtitles",options,selected,::closeTracks){index->
val stream=if(trackMenu==2)streams.getOrNull(index-1)else streams.getOrNull(index)
if(options.isNotEmpty())controller.selectServerStream(stream,type)
closeTracks()
}
}
if(trackMenu>=3)PlaybackOptions(vm,controller,item,trackMenu,{trackMenu=it;interacted()},::closeTracks)
}
}
@Composable private fun SeekTimeline(controller:PlaybackController,item:Title,modifier:Modifier,onInteraction:()->Unit) {
var focused by remember{mutableStateOf(false)}
val displayed=controller.scrubPosition ?: controller.position
val progress=if(controller.duration>0)(displayed.toFloat()/controller.duration).coerceIn(0f,1f)else 0f
val buffered=if(controller.duration>0)(controller.bufferedPosition.toFloat()/controller.duration).coerceIn(0f,1f)else 0f
BoxWithConstraints(modifier.height(18.dp).onFocusChanged{focused=it.isFocused;if(it.isFocused)onInteraction()else controller.commitScrub()}.onPreviewKeyEvent{event->
if(event.type!=KeyEventType.KeyDown)false else when(event.key) {
Key.DirectionLeft,Key.DirectionRight->{val delta=if(event.nativeKeyEvent.repeatCount>5)30000L else 10000L;controller.scrubBy(if(event.key==Key.DirectionLeft)-delta else delta);onInteraction();true}
Key.DirectionCenter,Key.Enter->{if(controller.scrubPosition!=null)controller.commitScrub()else controller.toggle();onInteraction();true}
else->false
}
}.semantics{contentDescription="Playback timeline";stateDescription=clockTime(displayed)+"; buffered "+clockTime(controller.bufferedPosition);progressBarRangeInfo=ProgressBarRangeInfo(progress,0f..1f)}.focusable()) {
Canvas(Modifier.fillMaxSize()) {
val y=size.height/2
val thickness=if(focused)3.dp.toPx()else 2.dp.toPx()
drawLine(Color.White.copy(alpha=.24f),Offset(0f,y),Offset(size.width,y),thickness,StrokeCap.Round)
drawLine(Color.White.copy(alpha=.48f),Offset(0f,y),Offset(size.width*buffered,y),thickness,StrokeCap.Round)
drawLine(Accent,Offset(0f,y),Offset(size.width*progress,y),thickness,StrokeCap.Round)
drawCircle(Accent,if(focused)4.dp.toPx()else 2.dp.toPx(),Offset(size.width*progress,y))
}
if(focused) {
val path=controller.api.previewPath(item,displayed)
Column(Modifier.offset(x=(maxWidth-146.dp)*progress,y=(-109).dp).wrapContentSize(Alignment.TopStart,unbounded=true).width(146.dp).height(104.dp).clip(RoundedCornerShape(6.dp)).background(Color(0xF0202020)).border(1.dp,Color.White.copy(alpha=.4f),RoundedCornerShape(6.dp)).semantics{contentDescription="Scrub preview"}.padding(3.dp),horizontalAlignment=Alignment.CenterHorizontally) {
if(path!=null)Artwork(controller.api,path,Modifier.fillMaxWidth().aspectRatio(16f/9f),320,180,animate=false)
else Text("No preview available",color=Muted,fontSize=10.sp,modifier=Modifier.padding(12.dp))
Text(clockTime(displayed),color=Accent,fontSize=10.sp,lineHeight=14.sp)
}
}
}
}
@Composable internal fun TrackPanel(title:String,options:List<String>,selected:Int,dismiss:()->Unit,choose:(Int)->Unit) {
val density=LocalDensity.current
val offset=with(density){IntOffset(-44.dp.roundToPx(),-108.dp.roundToPx())}
Popup(alignment=Alignment.BottomEnd,offset=offset,onDismissRequest=dismiss,properties=PopupProperties(focusable=true)) {
Column(Modifier.width(280.dp).heightIn(max=330.dp).clip(RoundedCornerShape(10.dp)).background(Color(0xF5222222)).padding(13.dp).onPreviewKeyEvent{if(it.key==Key.Back){if(it.type==KeyEventType.KeyDown)dismiss();true}else if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionLeft){dismiss();true}else false}) {
Text(title,color=Accent,fontSize=15.sp,lineHeight=20.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=9.dp,top=5.dp,bottom=10.dp))
if(options.isEmpty())Text("No tracks available",color=Muted,fontSize=12.sp,modifier=Modifier.padding(10.dp))
LazyColumn(verticalArrangement=Arrangement.spacedBy(2.dp)) {
items(options.size){index->TrackOption(options[index],index==selected,index==selected||selected<0&&index==0){choose(index)}}
}
}
}
}
@Composable private fun TrackOption(label:String,selected:Boolean,initialFocus:Boolean,onClick:()->Unit) {
var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()}
LaunchedEffect(initialFocus){if(initialFocus){delay(80);runCatching{requester.requestFocus()}}}
Row(Modifier.fillMaxWidth().heightIn(min=35.dp).focusRequester(requester).onFocusChanged{focused=it.isFocused}.clip(RoundedCornerShape(5.dp)).background(if(focused)Color.White.copy(alpha=.14f)else Color.Transparent).clickable(onClick=onClick).padding(horizontal=9.dp,vertical=8.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(9.dp)) {
if(selected)Icon(Icons.Outlined.Check,null,tint=Accent,modifier=Modifier.size(15.dp))else Spacer(Modifier.width(15.dp))
Text(label,color=if(focused||selected)Accent else Muted,fontSize=12.sp,lineHeight=16.sp,maxLines=2,overflow=TextOverflow.Ellipsis)
}
}

View file

@ -0,0 +1,112 @@
package tv.kaleido.app
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit
class PlexException(message: String, val status: Int = 0): IOException(message)
class PlexApi(val clientId: String) {
val http = OkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).readTimeout(30,TimeUnit.SECONDS).addNetworkInterceptor { chain ->
val original=chain.call().request().url;val current=chain.request().url
val request=if(original.host!=current.host || original.port!=current.port || original.scheme=="https"&&current.scheme!="https")chain.request().newBuilder().removeHeader("X-Plex-Token").build()else chain.request()
chain.proceed(request)
}.build()
var session: Session? = null
fun headers(token: String? = session?.serverToken) = buildMap {
put("Accept","application/json");put("X-Plex-Product","Kaleido");put("X-Plex-Version",BuildConfig.VERSION_NAME)
put("X-Plex-Client-Identifier",clientId);put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV");put("X-Plex-Device-Name","Kaleido TV")
if(!token.isNullOrBlank()) put("X-Plex-Token",token)
}
suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map<String,String> = emptyMap()): String = withContext(Dispatchers.IO) {
val req=Request.Builder().url(url).apply { headers(token).forEach { (k,v) -> header(k,v) }; if(method!="GET") method(method,FormBody.Builder().apply { form.forEach { (k,v)->add(k,v) } }.build()) }.build()
http.newCall(req).execute().use { r -> if(!r.isSuccessful) throw PlexException(when(r.code){401,403->"Plex rejected this session. Sign in again or check server access.";404->"This item is no longer available.";else->"Plex could not complete the request (${r.code})."},r.code); r.body?.string() ?: "{}" }
}
fun url(path: String, params: Map<String,String> = emptyMap()): String {
val s=session ?: throw PlexException("Choose a Plex server first.")
require(!path.startsWith("http")) { "Expected a server-relative Plex path" }
return (s.server.trimEnd('/')+"/"+path.trimStart('/')).toHttpUrl().newBuilder().apply { params.forEach { (k,v)->addQueryParameter(k,v) } }.build().toString()
}
suspend fun container(path: String, params: Map<String,String> = emptyMap()): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params)).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()}
suspend fun validate(s: Session): Session {
val j=JSONObject(request(s.server.trimEnd('/')+"/",s.serverToken)).getJSONObject("MediaContainer")
if(j.optString("machineIdentifier").isBlank()) throw PlexException("This address is not a Plex Media Server.")
return s.copy(serverName=j.optString("friendlyName","Plex"),machineId=j.optString("machineIdentifier"))
}
suspend fun newPin(): Pin {
val j=JSONObject(request("https://plex.tv/api/v2/pins",null,"POST",mapOf("strong" to "false")))
return Pin(j.getString("id"),j.getString("code"))
}
suspend fun pollPin(pin: Pin): String? = JSONObject(request("https://plex.tv/api/v2/pins/${pin.id}",null)).optString("authToken").takeIf { it.isNotBlank() && it!="null" }
suspend fun servers(token: String): List<Server> = JSONArray(request("https://plex.tv/api/v2/resources?includeHttps=1&includeRelay=1",token)).objects().filter { it.optString("provides").split(',').contains("server") }.map { j ->
val c=j.optJSONArray("connections").objects().sortedWith(compareByDescending<JSONObject> { it.optBoolean("local") }.thenByDescending { it.optString("protocol")=="https" }.thenBy { it.optBoolean("relay") })
Server(j.optString("clientIdentifier"),j.optString("name"),j.optString("accessToken",token),c.map { it.optString("uri") }.filter { it.startsWith("https://") || it.startsWith("http://") })
}
suspend fun connect(server: Server, account: String): Session = coroutineScope {
// Try TLS connections first; local HTTP remains available for servers without TLS.
var last: Throwable? = null
for (group in server.connections.partition { it.startsWith("https://") }.toList()) {
val results=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } }.awaitAll()
results.firstOrNull { it.isSuccess }?.getOrNull()?.let { return@coroutineScope it }
last=results.lastOrNull()?.exceptionOrNull() ?: last
}
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")) }
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){
container("/library/sections/$section/all",mapOf("type" to "3","sort" to "addedAt:desc","X-Plex-Container-Size" to "18")).optJSONArray("Metadata").objects().map{j->
Title.parse(j).let{it.copy(title=listOf(it.parentTitle,it.title).filter{v->v.isNotBlank()}.joinToString(" · "))}
}
}
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)
if(genre.isNotBlank())p["genre"]=genre
if(unwatched)p["unwatched"]="1"
val d=container("/library/sections/$section/all",p)
LibraryPage(d.optJSONArray("Metadata").objects().map(Title::parse),d.optInt("totalSize",d.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 = 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> = container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="show"}.distinctBy{it.id}
fun previewPath(item:Title,time:Long):String? {
val part=item.media.firstOrNull()?.parts?.firstOrNull()
if(part!=null&&part.indexes.split(',').contains("sd"))return "/library/parts/${part.id}/indexes/sd/${time.coerceAtLeast(0)/5000*5000}"
return item.chapters.lastOrNull{it.start<=time}?.thumb?.takeIf{it.isNotBlank()}
}
suspend fun children(id: String): List<Title> = container("/library/metadata/$id/children").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun allEpisodes(id: String): List<Title> = container("/library/metadata/$id/allLeaves").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun collections(section: String): List<Title> = container("/library/sections/$section/collections").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun search(query: String): List<Title> = container("/hubs/search",mapOf("query" to query,"limit" to "60","includeCollections" to "1")).optJSONArray("Hub").objects().flatMap { it.optJSONArray("Metadata").objects().map(Title::parse) }.filter { it.type in listOf("movie","show","episode","collection") }.distinctBy { it.id }
suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) }
suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String) {
container("/:/timeline",mapOf("ratingKey" to item.id,"key" to item.key,"state" to state,"time" to position.coerceAtLeast(0).toString(),"duration" to duration.coerceAtLeast(0).toString(),"identifier" to "com.plexapp.plugins.library","session" to sessionId))
}
suspend fun selectStreams(part: Part, audio: String? = null, subtitle: String? = null) {
request(url("/library/parts/${part.id}",buildMap { put("allParts","1");audio?.let {put("audioStreamID",it)};subtitle?.let {put("subtitleStreamID",it)} }),method="PUT")
}
fun image(path: String, width: Int = 600, height: Int = 900): String? = if(path.isBlank() || session==null) null else url("/photo/:/transcode",mapOf("url" to path,"width" to width.toString(),"height" to height.toString(),"minSize" to "1","upscale" to "0"))
fun transcodeParams(item: Title, sessionId: String, mode: Int, offset: Long, quality: Int): Map<String,String> = buildMap {
put("path",item.key);put("mediaIndex","0");put("partIndex","0");put("protocol","hls");put("session",sessionId);put("offset",(offset/1000.0).toString())
put("directPlay","0");put("directStream",if(mode==1) "1" else "0");put("directStreamAudio","1");put("directStreamVideo",if(mode==1) "1" else "0")
val original=item.media.firstOrNull()
put("maxVideoBitrate",if(mode==1)maxOf(original?.bitrate ?: 0,100000).toString()else quality.toString())
put("videoResolution",if(mode==1&&original!=null&&original.width>0)"${original.width}x${original.height}"else if(quality>20000)"3840x2160"else "1920x1080")
put("videoQuality","100");put("audioBoost","100");put("subtitleSize","100");put("location","lan");put("hasMDE","1");put("fastSeek","1")
put("X-Plex-Client-Identifier",clientId);put("X-Plex-Product","Kaleido");put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV")
// Augment the existing target. Separate targets make Plex prefer H.264 conversion even for HEVC it could copy.
val hevcAvailable=android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS).codecInfos.any{!it.isEncoder&&it.supportedTypes.any{type->type.equals("video/hevc",true)}}
put("X-Plex-Client-Profile-Extra",if(mode==1&&hevcAvailable)"append-transcode-target-codec(type=videoProfile&context=streaming&protocol=hls&videoCodec=hevc)"else "")
}
suspend fun stopTranscode(sessionId: String) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId)) }
}

View file

@ -0,0 +1,47 @@
package tv.kaleido.app
import kotlinx.coroutines.*
/** Share in-flight work with the visible preview and retain only a small LRU of full metadata. */
internal class PreviewMetadata(private val scope:CoroutineScope,private val capacity:Int=64,private val maxAgeMs:Long=30_000,
private val clock:()->Long={System.nanoTime()/1_000_000},private val load:suspend (Title)->Title) {
private val cache=linkedMapOf<String,Pair<Long,Title>>()
private val requests=mutableMapOf<String,Deferred<Title>>()
private var generation=0
private var pending:Title?=null
private var worker:Job?=null
suspend fun details(item:Title):Title {
cached(item.id)?.let{return it}
val request=requests[item.id] ?: scope.async(start=CoroutineStart.LAZY) {
val epoch=generation
load(item).also{if(epoch==generation)remember(it)}
}.also{task->
requests[item.id]=task
task.invokeOnCompletion{if(requests[item.id]===task)requests.remove(item.id)}
}
return request.await()
}
fun anticipate(item:Title) {
if(cached(item.id)!=null){pending=null;return}
pending=item
if(worker?.isActive==true)return
worker=scope.launch {
// One speculative metadata request at a time; bursts replace the queued destination.
while(isActive){
val target=pending ?: break;pending=null
try{details(target)}catch(e:CancellationException){throw e}catch(_:Exception){/* Visible preview can retry. */}
}
}
}
fun remember(item:Title) {
cache.remove(item.id);cache[item.id]=clock() to item
while(cache.size>capacity)cache.remove(cache.keys.first())
}
private fun cached(id:String):Title? {
val entry=cache.remove(id) ?: return null
if(clock()-entry.first>maxAgeMs)return null
cache[id]=entry;return entry.second
}
fun cancelPrediction(){pending=null}
fun clear(){generation++;cancelPrediction();worker?.cancel();worker=null;requests.values.toList().forEach{it.cancel()};requests.clear();cache.clear()}
}

View file

@ -0,0 +1,148 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import androidx.activity.compose.BackHandler
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.lazy.grid.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage
import coil.request.ImageRequest
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.flow.first
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.input.key.onPreviewKeyEvent
import java.io.File
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true) {
val context=LocalContext.current
val model=remember(path,api.session?.server,width,height,animate){api.image(path,width,height)?.let {u -> ImageRequest.Builder(context).data(u).apply {api.headers().forEach{(k,v)->addHeader(k,v)}}.crossfade(if(animate)180 else 0).build()}}
AsyncImage(model=model,contentDescription=null,contentScale=ContentScale.Crop,modifier=modifier.background(Panel))
}
@Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) {
KaleidoTheme {
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 entrance=remember{Animatable(1f)}
val density=LocalDensity.current
var previousDestination by remember{mutableStateOf(vm.page.kind)}
var direction by remember{mutableFloatStateOf(1f)}
LaunchedEffect(screenKey){
val order=listOf("home","movies","tv","search","settings")
direction=if(order.indexOf(vm.page.kind)<order.indexOf(previousDestination))-1f else 1f
previousDestination=vm.page.kind
entrance.snapTo(0f);entrance.animateTo(1f,tween(280))
}
// A restored Activity after process eviction still needs the cold-start cover.
var startup by remember{mutableStateOf(true)}
val splash=remember{Animatable(1f)}
LaunchedEffect(Unit){
if(startup){
delay(1600)
withTimeoutOrNull(600){snapshotFlow{!vm.busy}.first{it}}
splash.animateTo(0f,tween(240));startup=false
}
}
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()
}
Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{startup}) {
if(vm.servers.isNotEmpty()) ServerPicker(vm) else if(vm.session==null||vm.linkingAccount) SignIn(vm) else {
Column(Modifier.fillMaxSize().graphicsLayer{
alpha=.18f+.82f*entrance.value
translationX=with(density){28.dp.toPx()}*direction*(1f-entrance.value)
}) {
if(!immersive&&vm.page.kind !in listOf("details","group")) TopBar(vm)
stateHolder.SaveableStateProvider(screenKey) {
when(vm.page.kind){
"home"->HomeScreen(vm,discoveryFocus)
"movies","tv"->LibraryScreen(vm,discoveryFocus)
"details","group"->DetailsScreen(vm)
"search"->SearchScreen(vm)
"settings"->SettingsScreen(vm,install)
}
}
}
if(immersive)TopBar(vm,discoveryFocus)
}
if(vm.busy) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopCenter),color=Accent,trackColor=Color.Transparent)
if(vm.error!=null) ErrorDialog(vm.error!!,{vm.dismissError()},{vm.retry()})
vm.playing?.let {item-> androidx.compose.runtime.key(item.id) {PlaybackScreen(vm,item)} }
if(startup)StartupSplash(splash.value)
}
}
}
val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Title: Z–A","addedAt:desc" to "Recently added","year:desc" to "Newest release","year:asc" to "Oldest release","audienceRating:desc" to "Audience rating","duration:asc" to "Shortest first")
@Composable fun SignIn(vm: KaleidoViewModel) {
var manual by rememberSaveable{mutableStateOf(false)}
Box(Modifier.fillMaxSize().background(Brush.radialGradient(listOf(Color(0xFF252525),Ink)))) {
Row(Modifier.align(Alignment.Center).padding(52.dp),horizontalArrangement=Arrangement.spacedBy(65.dp),verticalAlignment=Alignment.CenterVertically) {
Column(Modifier.width(410.dp)) {Brand();Spacer(Modifier.height(35.dp));Eyebrow("A new view of your collection");Text("Your stories.\nBeautifully at home.",color=Color.White,fontSize=43.sp,lineHeight=46.sp,fontWeight=FontWeight.Black,letterSpacing=(-1.5).sp,modifier=Modifier.padding(vertical=18.dp));Text("Link your Plex account to bring your movies, shows, and everything in between to the big screen.",color=Muted,fontSize=15.sp,lineHeight=23.sp)}
Column(Modifier.width(300.dp).clip(RoundedCornerShape(22.dp)).background(Color.White.copy(alpha=.055f)).border(1.dp,Color.White.copy(alpha=.1f),RoundedCornerShape(22.dp)).padding(27.dp),horizontalAlignment=Alignment.CenterHorizontally) {
if(!manual){Text("Sign in to Plex",color=Color.White,fontSize=23.sp,fontWeight=FontWeight.Bold);Text("On your phone or computer, visit",color=Muted,fontSize=12.sp,modifier=Modifier.padding(top=17.dp));Text("plex.tv/link",color=Accent,fontSize=22.sp,fontWeight=FontWeight.Bold,modifier=Modifier.padding(vertical=9.dp));Text(vm.pin?.code?.uppercase() ?: "····",color=Color.White,fontSize=43.sp,fontWeight=FontWeight.Bold,letterSpacing=8.sp,modifier=Modifier.padding(vertical=12.dp));Text("Enter this code. This TV connects automatically.",color=Muted,fontSize=11.sp);Spacer(Modifier.height(24.dp));TvButton("Get a new code",initialFocus=true,onClick={vm.linkAccount()});Spacer(Modifier.height(12.dp));TvButton("Connect manually",onClick={manual=true})}
else ManualForm(vm){manual=false}
}
}
}
}
@Composable fun ManualForm(vm: KaleidoViewModel,back: ()->Unit) {
var address by rememberSaveable{mutableStateOf("")};var token by rememberSaveable{mutableStateOf("")}
Text("Connect to a server",color=Color.White,fontSize=21.sp,fontWeight=FontWeight.Bold)
Spacer(Modifier.height(14.dp));OutlinedTextField(address,{address=it},label={Text("Server URL")},singleLine=true,modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(10.dp));OutlinedTextField(token,{token=it},label={Text("Access token")},singleLine=true,visualTransformation=PasswordVisualTransformation(),modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(18.dp));TvButton("Connect",primary=true,onClick={vm.manualConnect(address,token)});Spacer(Modifier.height(10.dp));TvButton("Use Plex account",onClick=back)
}
@Composable fun ServerPicker(vm: KaleidoViewModel) {
Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})}}
}
@Composable fun SettingsScreen(vm: KaleidoViewModel,install: (File)->Unit) {
var confirmSignOut by remember{mutableStateOf(false)};var modeDialog by remember{mutableStateOf(false)};var qualityDialog by remember{mutableStateOf(false)};var watchedDialog by remember{mutableStateOf(false)}
LaunchedEffect(vm.downloadedApk){vm.downloadedApk?.let(install)}
LazyColumn(contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=17.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) {
item {Text("Settings",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)}
item{SettingsPanel("Plex connection") {Text(vm.session?.serverName.orEmpty(),color=Color.White,fontSize=20.sp,fontWeight=FontWeight.Bold);Text(if(vm.accountToken.isBlank())"Server connection · Link your Plex account to discover your servers"else "Plex account linked · Session encrypted with Android Keystore",color=Muted,fontSize=12.sp);Spacer(Modifier.height(14.dp));Row(horizontalArrangement=Arrangement.spacedBy(10.dp)){TvButton("Sign in with Plex",initialFocus=true,onClick={vm.beginAccountLink()});if(vm.accountToken.isNotBlank())TvButton("Choose server",onClick={vm.switchServer()});TvButton("Sign out",onClick={confirmSignOut=true})}}}
item{SettingsPanel("Playback") {Row(horizontalArrangement=Arrangement.spacedBy(12.dp)){TvButton("Mode: "+listOf("Original","Direct stream","Transcode")[vm.playbackMode],onClick={modeDialog=true});TvButton("Transcode quality: "+if(vm.quality>20000)"4K · 80 Mbps"else "1080p · 20 Mbps",onClick={qualityDialog=true})};Text("Direct stream is the default. Playback mode, audio, subtitles, speed, and quality can also be changed in the player.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(top=12.dp))}}
item{SettingsPanel("Watched status") {
TvButton("Mark watched at ${vm.watchedPercent}%",onClick={watchedDialog=true})
Text("A resumed title gets its checkmark at this playback percentage. Completed titles keep their Plex watched status.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
}}
item{SettingsPanel("Software updates") {Text("Kaleido ${BuildConfig.VERSION_NAME}",color=Color.White,fontSize=20.sp,fontWeight=FontWeight.Bold);Text(vm.updateStatus,color=Muted,fontSize=12.sp,modifier=Modifier.padding(vertical=8.dp));Text("Updates are checked automatically every six hours while Kaleido is in use.",color=Muted,fontSize=12.sp);Spacer(Modifier.height(14.dp));Row(horizontalArrangement=Arrangement.spacedBy(10.dp)){TvButton("Check for updates",onClick={vm.checkUpdate()});if(vm.update!=null&&!vm.downloading)TvButton("Download & install ${vm.update!!.version}",primary=true,onClick={vm.downloadUpdate()})};vm.update?.let{if(it.notes.isNotBlank())Text(it.notes.take(1800),color=Muted,fontSize=11.sp,modifier=Modifier.padding(top=12.dp))};Text("git.elijahkuntz.com/Elijah/Kaleido",color=Accent,fontSize=10.sp,modifier=Modifier.padding(top=14.dp))}}
}
if(confirmSignOut)ChoiceDialog("Sign out of Plex?",listOf("Keep watching","Sign out"),0,{confirmSignOut=false}){if(it==1)vm.signOut();confirmSignOut=false}
if(watchedDialog) {
val thresholds=listOf(50,60,70,75,80,85,90,95,100)
ChoiceDialog("Mark watched after",thresholds.map{"$it%"},thresholds.indexOf(vm.watchedPercent),{watchedDialog=false}){vm.chooseWatchedPercent(thresholds[it]);watchedDialog=false}
}
if(modeDialog)ChoiceDialog("Playback mode",listOf("Automatic · Original quality","Direct stream · Remux when possible","Transcode · Compatibility mode"),vm.playbackMode,{modeDialog=false}){vm.choosePlaybackMode(it);modeDialog=false}
if(qualityDialog)ChoiceDialog("Transcode quality",listOf("1080p · 20 Mbps","4K · 80 Mbps"),if(vm.quality>20000)1 else 0,{qualityDialog=false}){vm.chooseQuality(if(it==0)20000 else 80000);qualityDialog=false}
}
@Composable fun SettingsPanel(title: String,content: @Composable ColumnScope.()->Unit) {Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(9.dp)).background(Panel.copy(alpha=.65f)).padding(18.dp)){Eyebrow(title);Spacer(Modifier.height(11.dp));content()}}
@Composable fun EmptyState(title: String,message: String){Column(Modifier.padding(52.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){Text(title,color=Color.White,fontSize=26.sp,fontWeight=FontWeight.Bold);Text(message,color=Muted,fontSize=14.sp)}}
@Composable fun ErrorDialog(message: String,dismiss: ()->Unit,retry: ()->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(23.dp)){Text("Something needs attention",color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold);Text(message,color=Muted,fontSize=12.sp,lineHeight=19.sp,modifier=Modifier.padding(vertical=17.dp));Row(horizontalArrangement=Arrangement.spacedBy(9.dp)){TvButton("Try again",primary=true,initialFocus=true,onClick={dismiss();retry()});TvButton("Dismiss",onClick=dismiss)}}}}
@Composable fun ChoiceDialog(title: String,options: List<String>,selected: Int,dismiss: ()->Unit,choose: (Int)->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(360.dp).heightIn(max=390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(21.dp)){Text(title,color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=14.dp));LazyColumn(verticalArrangement=Arrangement.spacedBy(4.dp)){items(options.size){i->TvButton(options[i],Modifier.fillMaxWidth(),selected=i==selected,initialFocus=i==selected||selected<0&&i==0,onClick={choose(i)})}}}}}

View file

@ -0,0 +1,36 @@
package tv.kaleido.app
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import org.json.JSONObject
import java.security.KeyStore
import java.util.UUID
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
class SecureSession(private val context: Context) {
private val prefs = context.getSharedPreferences("kaleido", Context.MODE_PRIVATE)
val clientId: String = prefs.getString("clientId",null) ?: UUID.randomUUID().toString().also { prefs.edit().putString("clientId",it).apply() }
private fun key(): SecretKey {
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
return ks.getKey("kaleido-session",null) as? SecretKey ?: KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,"AndroidKeyStore").apply {
init(KeyGenParameterSpec.Builder("kaleido-session",KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
}.generateKey()
}
fun save(s: Session) {
val json = JSONObject().put("account",s.accountToken).put("token",s.serverToken).put("server",s.server).put("name",s.serverName).put("id",s.machineId).toString()
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE,key()) }
prefs.edit().putString("session",Base64.encodeToString(cipher.iv+cipher.doFinal(json.toByteArray()),Base64.NO_WRAP)).commit()
}
fun load(): Session? = runCatching {
val bytes = Base64.decode(prefs.getString("session",null) ?: return null,Base64.NO_WRAP)
val cipher=Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.DECRYPT_MODE,key(),GCMParameterSpec(128,bytes.copyOfRange(0,12))) }
val j=JSONObject(String(cipher.doFinal(bytes.copyOfRange(12,bytes.size))))
Session(j.getString("account"),j.getString("token"),j.getString("server"),j.getString("name"),j.getString("id"))
}.getOrNull()
fun clear() { prefs.edit().remove("session").commit() }
}

View file

@ -0,0 +1,99 @@
package tv.kaleido.app
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
val Ink=Color(0xFF090909)
val Panel=Color(0xFF1B1B1B)
val Muted=Color(0xFFA5A5A5)
val Accent=Color(0xFFF1F1F1)
val Warm=Color(0xFFD1D1D1)
object Cinema {
val gutter=44.dp
val radius=6.dp
val secondary=Color(0xFFC7C7C7)
val quiet=Color(0xFF737373)
}
@Composable fun KaleidoTheme(content: @Composable ()->Unit) {
MaterialTheme(colorScheme=darkColorScheme(primary=Accent,onPrimary=Ink,background=Ink,surface=Panel,onSurface=Accent,secondary=Warm,outline=Color(0xFF474747)),typography=Typography(bodyLarge=TextStyle(fontSize=13.sp)),content=content)
}
@Composable fun TvButton(label: String,modifier: Modifier=Modifier,selected: Boolean=false,primary: Boolean=false,initialFocus: Boolean=false,onClick: ()->Unit) {
var focused by remember { mutableStateOf(false) };val requester=remember {FocusRequester()}
val bg by animateColorAsState(if(focused) Accent else if(primary)Color(0xFFDEDEDE) else if(selected)Color.White.copy(alpha=.16f)else Color.White.copy(alpha=.08f),tween(150),label="buttonBackground")
val fg=if(focused||primary) Ink else Accent
val scale by animateFloatAsState(if(focused)1.025f else 1f,tween(160),label="buttonScale")
LaunchedEffect(initialFocus){if(initialFocus){withFrameNanos{};runCatching{requester.requestFocus()}}}
Box(modifier.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).onFocusChanged{focused=it.isFocused}.clip(RoundedCornerShape(Cinema.radius)).background(bg).clickable(onClick=onClick).padding(horizontal=13.dp,vertical=8.dp)) {
Text(label,color=fg,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1)
}
}
@Composable fun SectionHeading(title: String, subtitle: String?=null) {
Column(Modifier.padding(bottom=8.dp)) {Text(title,color=Accent,fontSize=18.sp,lineHeight=23.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.35).sp);if(subtitle!=null)Text(subtitle,color=Muted,fontSize=10.sp,lineHeight=14.sp,modifier=Modifier.padding(top=2.dp))}
}
@Composable fun Eyebrow(text: String) {Text(text.uppercase(),color=Muted,fontSize=9.sp,lineHeight=13.sp,fontWeight=FontWeight.Medium,letterSpacing=1.4.sp)}
@Composable fun ActionButton(label:String,icon:ImageVector,modifier:Modifier=Modifier,primary:Boolean=false,initialFocus:Boolean=false,onClick:()->Unit) {
var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()}
val scale by animateFloatAsState(if(focused)1.025f else 1f,tween(160),label="actionScale")
val background by animateColorAsState(if(focused||primary)Accent else Color.White.copy(alpha=.12f),tween(160),label="actionSurface")
val foreground=if(focused||primary)Ink else Accent
LaunchedEffect(initialFocus){if(initialFocus){withFrameNanos{};runCatching{requester.requestFocus()}}}
Row(modifier.height(34.dp).graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).onFocusChanged{focused=it.isFocused}.clip(RoundedCornerShape(5.dp)).background(background).clickable(onClick=onClick).padding(horizontal=14.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
Icon(icon,null,tint=foreground,modifier=Modifier.size(17.dp))
Text(label,color=foreground,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.SemiBold)
}
}
@Composable fun IconControl(icon:ImageVector,label:String,modifier:Modifier=Modifier,size:Dp=36.dp,iconSize:Dp=20.dp,requester:FocusRequester?=null,initialFocus:Boolean=false,selected:Boolean=false,onFocused:()->Unit={},onClick:()->Unit) {
var focused by remember{mutableStateOf(false)}
val ownRequester=remember{FocusRequester()}
val focus=requester ?: ownRequester
val bg by animateColorAsState(if(focused)Accent else if(selected)Color.White.copy(alpha=.16f)else Color.Transparent,tween(140),label="iconBackground")
val scale by animateFloatAsState(if(focused)1.08f else 1f,tween(160),label="iconFocus")
LaunchedEffect(initialFocus){if(initialFocus){withFrameNanos{};runCatching{focus.requestFocus()}}}
Box(modifier.size(size).graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(focus).onFocusChanged{focused=it.isFocused;if(it.isFocused)onFocused()}.clip(CircleShape).background(bg).semantics{contentDescription=label}.clickable(onClick=onClick),contentAlignment=Alignment.Center) {
Icon(icon,null,tint=if(focused)Ink else Accent,modifier=Modifier.size(iconSize))
}
}
@Composable fun NavigationLabel(label:String,selected:Boolean,modifier:Modifier=Modifier,initialFocus:Boolean=false,onFocused:()->Unit={},onClick:()->Unit) {
var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()}
val bg by animateColorAsState(if(focused)Color.White.copy(alpha=.14f) else Color.Transparent,tween(150),label="navigationBackground")
val scale by animateFloatAsState(if(focused)1.035f else 1f,tween(160),label="navigationFocus")
LaunchedEffect(initialFocus){if(initialFocus){delay(140);runCatching{requester.requestFocus()}}}
Column(modifier.height(34.dp).graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).onFocusChanged{focused=it.isFocused;if(it.isFocused)onFocused()}.clip(RoundedCornerShape(5.dp)).background(bg).clickable(onClick=onClick).padding(horizontal=13.dp),horizontalAlignment=Alignment.CenterHorizontally,verticalArrangement=Arrangement.Center) {
Text(label,color=if(focused||selected)Accent else Muted,fontSize=13.sp,lineHeight=18.sp,fontWeight=if(selected||focused)FontWeight.SemiBold else FontWeight.Medium)
if(selected||focused)Box(Modifier.padding(top=3.dp).width(16.dp).height(1.5.dp).background(Accent.copy(alpha=if(focused)1f else .6f),RoundedCornerShape(1.dp)))
}
}

View file

@ -0,0 +1,9 @@
package tv.kaleido.app
/** One successful scrobble per playback session. A failed request is retried on the next report. */
internal class WatchedProgress(private val mark:suspend ()->Unit) {
private var sent=false
suspend fun report(position:Long,duration:Long,percent:Int) {
if(!sent&&reachedWatchedThreshold(position,duration,percent)){mark();sent=true}
}
}

View file

@ -0,0 +1 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"><path android:fillColor="#FFF0C8" android:pathData="M4.2,10C1,9.2 1.2,5 4.4,4.5C3.8,1.7 7.5,0.3 9.2,2.8C10.6,-0.3 14.7,0.7 14.8,3.6C18.3,1.5 21.5,4.4 19.8,7C23,8 22.7,11.4 19.5,12H4.2Z"/><path android:fillColor="#E9C76E" android:pathData="M6,5C4,4 3,7 5,8C4,6 6,6 6,5M11,4C9,3 8,5 9,7C9,5 11,6 11,4M16,6C14,5 13,8 15,9C14,7 17,8 16,6"/><path android:fillColor="#F1E8DD" android:pathData="M4,10H20L18,23H6Z"/><path android:fillColor="#DE4141" android:pathData="M4,10H7L8,23H6ZM10.5,10H13.5L13,23H11ZM17,10H20L18,23H16Z"/><path android:fillColor="#FFF6E8" android:pathData="M3.7,9.5H20.3V11H3.7Z"/></vector>

View file

@ -0,0 +1 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"><group android:rotation="-55" android:pivotX="12" android:pivotY="12" android:scaleX="0.84" android:scaleY="0.84" android:translateX="1.5" android:translateY="1.5"><path android:fillColor="#FFF0C8" android:pathData="M4.2,10C1,9.2 1.2,5 4.4,4.5C3.8,1.7 7.5,0.3 9.2,2.8C10.6,-0.3 14.7,0.7 14.8,3.6C18.3,1.5 21.5,4.4 19.8,7C23,8 22.7,11.4 19.5,12H4.2Z"/><path android:fillColor="#E9C76E" android:pathData="M6,5C4,4 3,7 5,8C4,6 6,6 6,5M11,4C9,3 8,5 9,7C9,5 11,6 11,4M16,6C14,5 13,8 15,9C14,7 17,8 16,6"/><path android:fillColor="#F1E8DD" android:pathData="M4,10H20L18,23H6Z"/><path android:fillColor="#DE4141" android:pathData="M4,10H7L8,23H6ZM10.5,10H13.5L13,23H11ZM17,10H20L18,23H16Z"/><path android:fillColor="#FFF6E8" android:pathData="M3.7,9.5H20.3V11H3.7Z"/></group><path android:fillColor="#FFF0C8" android:pathData="M3,16a1.5,1.5 0,1 0,0.01,0M2,21a1.4,1.4 0,1 0,0.01,0"/></vector>

View file

@ -0,0 +1 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="320dp" android:height="180dp" android:viewportWidth="320" android:viewportHeight="180"><path android:fillColor="#090909" android:pathData="M0,0h320v180h-320z"/><group android:translateX="108.8" android:translateY="38.8" android:scaleX="1.6" android:scaleY="1.6"><path android:fillColor="#C3E8D3" android:pathData="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path android:fillColor="#71B9B0" android:pathData="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path android:fillColor="#3D7C7B" android:pathData="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path android:fillColor="#D0A977" android:pathData="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path android:fillColor="#E9D8AE" android:pathData="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path android:fillColor="#EEF2DD" android:pathData="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></group></vector>

View file

@ -0,0 +1 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="64dp" android:height="64dp" android:viewportWidth="64" android:viewportHeight="64"><path android:fillColor="#C3E8D3" android:pathData="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path android:fillColor="#71B9B0" android:pathData="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path android:fillColor="#3D7C7B" android:pathData="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path android:fillColor="#D0A977" android:pathData="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path android:fillColor="#E9D8AE" android:pathData="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path android:fillColor="#EEF2DD" android:pathData="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></vector>

View file

@ -0,0 +1 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"><path android:fillColor="#090909" android:pathData="M0,0h108v108h-108z"/><group android:translateX="22" android:translateY="22"><path android:fillColor="#C3E8D3" android:pathData="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path android:fillColor="#71B9B0" android:pathData="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path android:fillColor="#3D7C7B" android:pathData="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path android:fillColor="#D0A977" android:pathData="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path android:fillColor="#E9D8AE" android:pathData="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path android:fillColor="#EEF2DD" android:pathData="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></group></vector>

View file

@ -0,0 +1 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="45dp" android:height="25dp" android:viewportWidth="900" android:viewportHeight="500"><path android:fillColor="#F5C518" android:pathData="M197,122.7v255.4h-66.2V122.7h66.2ZM338.4,122.7l-15.3,119.4-9.4-64.9c-2.8-20.8-5.4-39-8-54.5h-85.9v255.4h58.1l.3-168.6,24.4,168.6h41.4l23.3-172.3v172.3h58.1V122.7h-86.7ZM447.7,378.1V122.7h49.4c32.1,0,50.6,1.5,61.9,4.5,11.3,3,19.9,7.8,25.7,14.5,6,6.7,9.7,14.2,11.1,22.4,1.4,8.3,2.4,24.5,2.4,48.7v89.6c0,22.9-1.2,38.3-3.5,45.9-2.1,7.7-5.9,13.7-11.3,18.1-5.3,4.5-12,7.4-19.8,9.2-7.9,1.7-19.8,2.6-35.7,2.6h-80.4ZM513.9,166.4v167.6c9.5,0,15.4-1.9,17.6-5.7,2.2-3.8,3.4-14.2,3.4-31.3v-98.9c0-11.5-.4-18.9-1.1-22.2-.7-3.3-2.5-5.7-5.1-7.2-2.6-1.6-7.6-2.3-14.7-2.3ZM684.7,122.7v83.1c5.3-6.1,11.3-10.6,17.7-13.6,6.6-3.1,16.3-4.6,23.9-4.6s16.4,1.4,22.9,4.1c6.4,2.7,11.3,6.6,14.7,11.5,3.3,5,5.4,9.8,6.1,14.5.7,4.7,1,14.7,1,30.2v71.7c0,15.2-1,26.6-3.1,34.2-2,7.4-6.8,14-14.5,19.4-7.6,5.6-16.7,8.3-27.1,8.3s-17.2-1.6-23.8-4.8c-6.6-3.4-12.5-8.2-17.8-14.7l-4.2,16.2h-59.7V122.7h63.9ZM707.1,250.7c0-10.8-.7-17.8-2.1-21.2-1.4-3.2-6.8-5-10.9-5s-6.4,1.5-7.7,4.3c-1.1,3-1.7,10.2-1.7,21.8v67.5c0,11.3.7,18.4,2,21.5,1.4,3.2,4,4.7,7.9,4.7s9.4-1.6,10.7-4.8c1.2-3.2,1.9-11.1,1.9-23.4v-65.5Z"/></vector>

View file

@ -0,0 +1 @@
<resources><style name="Theme.Kaleido" parent="android:style/Theme.Material.NoActionBar"><item name="android:fontFamily">sans</item><item name="android:windowActionModeOverlay">true</item><item name="android:windowBackground">#090909</item><item name="android:colorAccent">#F1F1F1</item><item name="android:windowLightStatusBar">false</item><item name="android:windowFullscreen">true</item></style></resources>

View file

@ -0,0 +1 @@
<data-extraction-rules><cloud-backup><exclude domain="root" path="."/><exclude domain="sharedpref" path="."/><exclude domain="database" path="."/><exclude domain="file" path="."/></cloud-backup><device-transfer><exclude domain="root" path="."/><exclude domain="sharedpref" path="."/><exclude domain="database" path="."/><exclude domain="file" path="."/></device-transfer></data-extraction-rules>

View file

@ -0,0 +1 @@
<paths><cache-path name="updates" path="updates/" /></paths>

View file

@ -0,0 +1,13 @@
package tv.kaleido.app
import org.junit.Assert.*
import org.junit.Test
class VersionsTest {
@Test fun releaseVersionOrdering() {
assertTrue(Versions.newer("v0.10.0","0.9.9"))
assertTrue(Versions.newer("1.0.1","1.0.0"))
assertFalse(Versions.newer("v1.0.0","1.0.0"))
assertFalse(Versions.newer("0.9.0","1.0.0"))
assertFalse(Versions.newer("1.0.1-beta","1.0.0"))
assertFalse(Versions.newer("invalid","1.0.0"))
}
}