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,44 @@
name: Validate and publish Kaleido
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
jobs:
android:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
timeout-minutes: 40
steps:
- uses: https://data.forgejo.org/actions/checkout@v4.4.0
- name: Install Android toolchain
run: |
set -eu
apt-get update
apt-get install -y --no-install-recommends openjdk-17-jdk-headless unzip curl python3 ca-certificates
mkdir -p .tools/sdk/cmdline-tools
curl -fsSL https://dl.google.com/android/repository/commandlinetools-linux-13114758_latest.zip -o .tools/cmdline.zip
unzip -q .tools/cmdline.zip -d .tools/sdk/cmdline-tools
mv .tools/sdk/cmdline-tools/cmdline-tools .tools/sdk/cmdline-tools/latest
curl -fsSL https://services.gradle.org/distributions/gradle-8.13-bin.zip -o .tools/gradle.zip
unzip -q .tools/gradle.zip -d .tools
yes | .tools/sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root="$PWD/.tools/sdk" --licenses >/dev/null
.tools/sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root="$PWD/.tools/sdk" 'platforms;android-36' 'build-tools;35.0.0'
keytool -genkeypair -keystore .tools/kaleido-signing.jks -storepass kaleido-local -keypass kaleido-local -alias kaleido -keyalg RSA -keysize 2048 -validity 1 -dname 'CN=Ephemeral CI validation' -noprompt
- name: Compile, test, lint, and verify the signed distribution
run: |
set -eu
export ANDROID_HOME="$PWD/.tools/sdk"
export GRADLE_USER_HOME="$PWD/.gradle"
.tools/gradle-8.13/bin/gradle --no-daemon assembleDebug testDebugUnitTest lintDebug
if test -f distribution/Kaleido.apk; then
(cd distribution && sha256sum -c Kaleido.apk.sha256)
.tools/sdk/build-tools/35.0.0/apksigner verify --verbose --print-certs distribution/Kaleido.apk
fi
- name: Publish signed tag release
if: startsWith(github.ref, 'refs/tags/v')
env:
KALEIDO_RELEASE_TOKEN: ${{ github.token }}
RELEASE_REF: ${{ github.ref }}
run: python3 scripts/publish_release.py

17
.gitignore vendored Normal file
View file

@ -0,0 +1,17 @@
.env
.env.*
!.env.example
.tools/
.gradle/
.kotlin/
__pycache__/
local.properties
**/build/
output/
evidence/private/
*.keystore
*.jks
.idea/
*.iml
/Home screen.jpg
/Individual library.jpg

91
AGENTS.md Normal file
View file

@ -0,0 +1,91 @@
# Kaleido
## Working rules
- Ask clarifying questions before proceeding when more information is needed. Otherwise make reasonable decisions and complete the authorized work.
- This is a real native Android TV Plex client: Kotlin, Jetpack Compose, Media3/ExoPlayer. Preserve working Plex functionality; do not substitute mock content or prototype playback.
- The authorized test device is the onn at **192.168.50.195:5555**, package **tv.kaleido.app**, activity **.MainActivity**. Always specify the ADB serial. Do not modify its launcher, accessibility services, other apps, or other devices.
- `.env` contains `PLEX_SERVER_URL` and `PLEX_TOKEN` for local testing. Never print, commit, or embed credentials in source, resources, APKs, or logs. Keep `.env`, signing keys, toolchains, and private evidence ignored.
- Use the existing encrypted session. `scripts/device.py seed` provisions an installed **debug** build only when needed; the app encrypts and deletes its bootstrap file. Never clear app data or sign out just to reset a test.
## UI and architecture
- **Home:** large cinematic hero with playback/information actions and integrated landscape Continue Watching. Do not replace it with the compact section preview.
- **Movies:** compact preview/backdrop follows focused posters; recent releases and movie recommendations lead. **TV:** episode-first layout with wider next-episode thumbnails, new seasons and new episodes. Keep these destinations visibly distinct.
- Both sections retain a dedicated, filtered/sorted **A–Z poster grid**. Primary tabs activate on focus. Use neutral near-black chrome, artwork-led color, restrained controls and stable card bounds. Inspect actual TV screenshots and D-pad behavior after UI changes.
- `KaleidoViewModel.kt`: navigation, async loading and section caches. `PlexApi.kt` / `Models.kt`: Plex transport and parsing. `FocusedBrowse.kt`, `BrowseBackdrop.kt`, `BrowseScreens.kt`, `Theme.kt`: browsing/focus/design. `Playback.kt`: controller, negotiation and progress. `PlayerControls.kt` / `PlaybackExtras.kt`: controls, options and post-play. `SecureSession.kt`: Android Keystore persistence. `AppUpdater.kt`: repository updates.
## Build and device setup
Run from the repository root in PowerShell. `Build.ps1` configures the local JDK 17, Gradle 8.13 and SDK under `.tools/`; do not replace the toolchain unnecessarily. Builds/ADB may require sandbox escalation.
```powershell
$KaleidoAdb = 'C:\Users\Elijah\Desktop\platform-tools\adb.exe'
$KaleidoDevice = '192.168.50.195:5555'
$KaleidoPython = 'C:\Users\Elijah\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe'
$env:PYTHONIOENCODING = 'utf-8'
& $KaleidoAdb -s $KaleidoDevice get-state
.\Build.ps1 -Test # Debug APK, unit tests, lint
.\Build.ps1 -Release -Test # Optimized release APK, unit tests, lint
& $KaleidoAdb -s $KaleidoDevice install -r app/build/outputs/apk/debug/app-debug.apk
```
Install `app/build/outputs/apk/release/app-release.apk` instead for performance/final visual review. Debug and release share the private local signing key, so `install -r` preserves data.
## Testing suite
Use `& $KaleidoPython` before the Python commands below. Run only checks relevant to the change; **never run competing device/UI tests in parallel**. Live playback tests change real Plex progress and can change playback preferences. Restore a useful final state, normally the release build on Home.
| Command | Purpose / required build |
| --- | --- |
| `scripts/verify_ui.py browse` | Home/Movies/TV, A–Z, focus restoration, live Plex PIN and cancellation; debug or release |
| `scripts/verify_ui.py player` | Actual playback, scrub preview, track/options menus, speed/mode, hide/show/exit; **debug** |
| `scripts/repro_runtime.py sections` | Cold-start tab-switch blank-page regression; debug or release |
| `scripts/repro_runtime.py browse` | Horizontal bounds and frame pacing; **optimized release with profile compilation** |
| `scripts/repro_runtime.py controls` | One-press Back, OK reveal, timed hide and exit; **debug** |
| `scripts/repro_runtime.py episode` | Next-episode replacement/crash regression; **debug** |
| `scripts/repro_runtime.py postplay` | Natural ending → five-second countdown → next episode READY; **debug** |
| `scripts/repro_runtime.py credits` | Visible Skip credits, season/related rows and cancellable countdown; **debug** |
| `scripts/device.py screenshot <name>` | Capture to ignored `evidence/private/`; also supports `hierarchy`, `logs`, `launch`, `key` |
| `scripts/profile_browse.py` | Targeted atrace investigation when navigation performance regresses |
Live Android integration tests (currently six) cover secure persistence, library APIs, episodes, PIN, preview JPEGs/new seasons and supported HEVC remux negotiation:
```powershell
.\Build.ps1 -Test
& .tools/gradle-8.13/bin/gradle.bat --no-daemon assembleDebugAndroidTest
& $KaleidoAdb -s $KaleidoDevice install -r app/build/outputs/apk/debug/app-debug.apk
& $KaleidoAdb -s $KaleidoDevice install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
& $KaleidoAdb -s $KaleidoDevice shell am instrument -w tv.kaleido.app.test/androidx.test.runner.AndroidJUnitRunner
```
These require the private test session. Playback test intents (`testTitleId`, `testOffset`, `testMode`) are **ignored in release builds**. Fixture IDs are server-specific: Silo show `6115`, episodes `7599` → `8594`; movie `9776` is 2 Fast 2 Furious. Revalidate fixtures if the server changes. UI tests also depend on actual hub contents and English labels; diagnose missing fixtures separately from app failures.
## Important regression traps
- Keep initialization independent of cancellable tab requests and apply section results atomically. Cancelling initialization during a startup tab switch previously left Movies/TV blank.
- Preserve explicit D-pad row/column targets and fixed card geometry. Avoid expensive beyond-bounds focus searches, per-focus catalog recomposition and full-screen gradient overdraw. Contrast is baked into cached backdrop bitmaps off the main thread.
- Give every Media3 session a unique ID: next-episode creation can overlap the old controller's disposal. Plex HLS position is absolute; **do not add the requested resume offset again**.
- Handle remote Back explicitly before default focus handling. Wait for menu focus restoration in tests instead of sending blind rapid button sequences.
- Direct stream is the default preference, with original-file and conversion options available in-player. Augment Plex's existing HEVC target; competing transcode targets previously forced unnecessary H.264 conversion. A server decision to copy video does not itself prove successful rendering.
- **ADB screenshots can omit HEVC video on this onn while the actual TV displays it. The user confirmed this.** Do not force transcoding based solely on a blank capture. `scripts/check_video.py` has a pixel assertion that can falsely fail for this reason; use playback logs/rendered-frame evidence and physical TV confirmation as appropriate. Never infer universal HDR/codec support from one test.
- Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them.
### Performance testing
Fresh ADB installs may remain in ART `status=verify`, making Compose much slower. Compare matching compilation states. After installing the **release** APK, prepare only Kaleido:
```powershell
& $KaleidoAdb -s $KaleidoDevice shell am broadcast -a androidx.profileinstaller.action.INSTALL_PROFILE -n tv.kaleido.app/androidx.profileinstaller.ProfileInstallReceiver
& $KaleidoAdb -s $KaleidoDevice shell cmd package compile -f -m speed-profile tv.kaleido.app
& $KaleidoPython scripts/repro_runtime.py browse
```
The harness requires horizontal Y drift ≤3 px and frame-time p95 <40 ms. On 2026-10-23, the final release measured median 15 ms / p95 27 ms after profile compilation; some frames still missed 60 Hz. This is historical evidence, not a current guarantee. Baseline rules live in `app/src/main/baseline-prof.txt`; ordinary sideloads also depend on Android's background profile optimization.
## Releases and further detail
Updates come from `https://git.elijahkuntz.com/Elijah/Kaleido`. Keep the private `.tools/kaleido-signing.jks`; replacing it breaks in-place updates. `version.properties` is the version source. Before a requested release, increment version name/code, update `CHANGELOG.md`, build/test, and use `scripts/package_release.py`; the Forgejo workflow publishes matching version tags. Do not claim publication or updater installation was tested without verifying it.
See `docs/design-system.md` for the visual system and `docs/runtime-verification.md` for device evidence and limitations. Keep this file concise; put detailed investigation history there.

15
Build.ps1 Normal file
View file

@ -0,0 +1,15 @@
param([switch]$Release, [switch]$Test)
$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot
if (-not $env:JAVA_HOME -or -not (Test-Path "$env:JAVA_HOME\bin\javac.exe")) { $env:JAVA_HOME = (Get-ChildItem "$PSScriptRoot\.tools\jdk" -Directory | Select-Object -First 1).FullName }
$env:ANDROID_HOME = "$PSScriptRoot\.tools\sdk"
$env:GRADLE_USER_HOME = "$PSScriptRoot\.gradle"
if (-not (Test-Path .tools/kaleido-signing.jks) -and -not $env:KALEIDO_KEYSTORE) {
& "$env:JAVA_HOME\bin\keytool.exe" -genkeypair -keystore .tools/kaleido-signing.jks -storepass kaleido-local -keypass kaleido-local -alias kaleido -keyalg RSA -keysize 3072 -validity 36500 -dname 'CN=Kaleido' -noprompt
if ($LASTEXITCODE) { throw 'Signing key generation failed' }
}
$tasks = @('assembleDebug')
if ($Release) { $tasks = @('assembleRelease') }
if ($Test) { $tasks += @('testDebugUnitTest','lintDebug') }
& .tools/gradle-8.13/bin/gradle.bat --no-daemon @tasks
if ($LASTEXITCODE) { throw 'Build failed' }

5
CHANGELOG.md Normal file
View file

@ -0,0 +1,5 @@
# Kaleido releases
## 0.1.0
Initial independent Android TV Plex client with native Compose browsing, encrypted sessions, Plex account linking and server discovery, library filters and sorting, search, details and episode navigation, Media3 playback with conversion fallback, track selection, progress syncing, skip markers, and signed APK updates from the Kaleido repository.

43
README.md Normal file
View file

@ -0,0 +1,43 @@
# Kaleido
A native Kotlin / Jetpack Compose / Media3 client for personal Plex movie and television libraries on Android TV 9 and newer. Built for a remote, with cinematic server artwork, focused content rows, discovery hubs, paged libraries, and an original dark visual design inspired by the supplied references.
## Build on Windows
1. Run `scripts/bootstrap.py` with Python 3 to download an isolated JDK 17, Gradle 8.13, and Android command-line tools under `.tools/`.
2. Set `JAVA_HOME` to the extracted JDK directory and run `.tools/sdk/cmdline-tools/latest/bin/sdkmanager.bat --sdk_root=<absolute .tools/sdk path> "platforms;android-36" "build-tools;35.0.0"`. Accept the SDK license when prompted.
3. Run `./Build.ps1 -Test` for the debug APK, unit tests, and lint. Run `./Build.ps1 -Release` for the optimized release APK.
Open the project root in Android Studio to use an existing local Android SDK instead. Set `ANDROID_HOME` and use the bundled Gradle distribution or the wrapper.
The first local build creates `.tools/kaleido-signing.jks`. **Keep a private backup of this file and its credentials. Every app update must use the same signing key.** Debug and release builds share this local key so the test installation can receive the release through the updater. CI uses an ephemeral validation key and publishes only the locally signed distribution APK. For alternate signing, set `KALEIDO_KEYSTORE`, `KALEIDO_STORE_PASSWORD`, `KALEIDO_KEY_ALIAS`, and `KALEIDO_KEY_PASSWORD`.
## Connect
Open Kaleido and enter its code at [plex.tv/link](https://plex.tv/link). Settings → Sign in with Plex can link an account while keeping the current connection until successful server selection; Back cancels linking. Choose a server if more than one is available. The client tests the discovered server connections and prefers TLS. A manual server URL / token connection is also available. The credentials are AES-GCM encrypted with an Android Keystore key, never backed up, and removed on sign-out. Local HTTP servers remain supported. Account tokens are sent only to Plex account endpoints; server tokens are sent to the selected Plex server.
`.env` and signing keys are ignored by Git. No test credentials are included in source code, BuildConfig, resources, or APKs. `scripts/device.py seed` is an optional debug-only provisioning helper: it sends `.env` credentials to private app data over the already-authorized ADB connection. Kaleido immediately encrypts them and deletes the staging file. Release builds never read this staging file.
## Remote and playback
D-pad moves focus, OK activates, and Back returns through details and seasons. In the player, OK shows controls; Left/Right while controls are hidden seeks; dedicated media keys control playback. The on-screen controls provide pause, seeking, audio, subtitles, next episode, and exit. Back first hides controls, then exits playback. Stopping or leaving the app reports the latest position to Plex.
Direct stream is the default, requesting original resolution and remuxing where supported, with transcoding fallback. The player gear also exposes original-file playback, transcoding, audio, subtitles, speed, quality, and chapters. Media3's SurfaceView preserves supported HDR. Actual HDR, Dolby Vision, codecs, and audio passthrough depend on the device, connected display/receiver, source profile, and server. Plex owns transcoding capability and any account entitlements. Unsupported subtitle formats use server conversion. Intro and credit buttons appear when the server supplies markers. Scrubbing displays server-generated video previews or chapter thumbnails when available; the timeline also shows buffered progress. Episode endings and Skip credits show a cancellable five-second next-episode countdown, season episodes, and related shows.
## Updates and releases
Kaleido checks [the public repository releases](https://git.elijahkuntz.com/Elijah/Kaleido/releases) on launch and foreground entry, at most once per six hours. Settings offers an immediate check. It downloads the release APK over HTTPS, checks its supplied SHA-256 when available, and verifies the package name, increasing Android version code, and installed signing certificate before opening Android's package installer. Android requires a one-time “allow from this source” permission and confirmation for each installation.
To publish a version:
1. Increment **both** fields in `version.properties` and update `CHANGELOG.md`.
2. Run `./Build.ps1 -Release -Test`, then `python scripts/package_release.py`.
3. Commit the source and `distribution/`, push `main`, and push the matching `v<versionName>` tag.
The Forgejo workflow builds, tests, and lints the source, verifies the prebuilt signed distribution, then publishes its APK and checksum using Forgejo's repository-scoped token. The private production signing key never leaves the developer machine. The checked-in APK also provides a repository-file update channel, with an immutable tag URL in `distribution/latest.json`, for installations before the first Forgejo release is ready.
## Structure and references
`PlexApi.kt` owns Plex transport and server-relative API calls; `SecureSession.kt` owns credential encryption; `KaleidoViewModel.kt` owns navigation and async screen data; `Screens.kt` and `Theme.kt` implement the TV UI; `Playback.kt` owns Media3, stream negotiation, track selection, lifecycle, and timeline reporting; `AppUpdater.kt` verifies updates. Artwork has bounded memory and disk caches. Library data is paged in batches of 100.
Implementation follows the [official Plex Media Server API](https://developer.plex.tv/pms/), [Android Compose guidance](https://developer.android.com/compose), and [Media3 documentation](https://developer.android.com/media/media3). This is an independent client, unaffiliated with Plex. No existing Plex client source is copied.

54
app/build.gradle.kts Normal file
View file

@ -0,0 +1,54 @@
import java.util.Properties
plugins { id("com.android.application"); id("org.jetbrains.kotlin.android"); id("org.jetbrains.kotlin.plugin.compose") }
val version = Properties().apply { rootProject.file("version.properties").inputStream().use(::load) }
android {
namespace = "tv.kaleido.app"
compileSdk = 36
defaultConfig {
applicationId = "tv.kaleido.app"
minSdk = 28
targetSdk = 36
versionCode = version.getProperty("versionCode").toInt()
versionName = version.getProperty("versionName")
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
signingConfigs {
create("kaleido") {
storeFile = rootProject.file(System.getenv("KALEIDO_KEYSTORE") ?: ".tools/kaleido-signing.jks")
storePassword = System.getenv("KALEIDO_STORE_PASSWORD") ?: "kaleido-local"
keyAlias = System.getenv("KALEIDO_KEY_ALIAS") ?: "kaleido"
keyPassword = System.getenv("KALEIDO_KEY_PASSWORD") ?: "kaleido-local"
}
}
buildTypes {
debug { signingConfig = signingConfigs.getByName("kaleido") }
release { signingConfig = signingConfigs.getByName("kaleido"); isMinifyEnabled = true; proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") }
}
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
kotlinOptions { jvmTarget = "17" }
buildFeatures { compose = true; buildConfig = true }
packaging { resources.excludes += "/META-INF/{AL2.0,LGPL2.1}" }
}
dependencies {
implementation(platform("androidx.compose:compose-bom:2026.03.00"))
implementation("androidx.activity:activity-compose:1.11.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.4")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.4")
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.foundation:foundation")
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.material:material-icons-extended")
implementation("androidx.core:core-ktx:1.17.0")
implementation("androidx.media3:media3-exoplayer:1.11.1")
implementation("androidx.media3:media3-exoplayer-hls:1.11.1")
implementation("androidx.media3:media3-exoplayer-dash:1.11.1")
implementation("androidx.media3:media3-datasource-okhttp:1.11.1")
implementation("androidx.media3:media3-ui:1.11.1")
implementation("androidx.media3:media3-session:1.11.1")
implementation("io.coil-kt:coil-compose:2.7.0")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test:runner:1.6.2")
androidTestImplementation("androidx.test.ext:junit:1.2.1")
}

1
app/proguard-rules.pro vendored Normal file
View file

@ -0,0 +1 @@
-keepattributes Signature,InnerClasses,EnclosingMethod

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"))
}
}

5
build.gradle.kts Normal file
View file

@ -0,0 +1,5 @@
plugins {
id("com.android.application") version "8.13.2" apply false
id("org.jetbrains.kotlin.android") version "2.2.21" apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.2.21" apply false
}

41
docs/design-system.md Normal file
View file

@ -0,0 +1,41 @@
# Kaleido visual system
The interface gives artwork priority. App chrome uses neutral near-black, charcoal, and white. Color belongs to the user's media. Navigation, cards, and player controls share the same restrained focus language.
## Layout and typography
- Horizontal safe gutter: 44 dp. Navigation: 62 dp, with centered text destinations and independent search/settings icons.
- Home retains a large cinematic feature: an 80 percent stage with original title artwork, synopsis, playback and information actions. The scene continues beneath Continue Watching; entering the rail scrolls the feature away and the backdrop follows focused titles. Features interleave recently released, highly rated unwatched, and Plex-suggested movies/shows, excluding Continue Watching. They shuffle per refresh and rotate every 12 seconds while the hero is active, pausing during row browsing.
- Movies uses a compact fixed preview above poster rows, with the backdrop and synopsis following focused titles. Recently released films and movie recommendations lead. TV uses a shorter preview, larger episode thumbnails, next episodes, newly added seasons, and then new episodes and show recommendations. Redundant TV hubs are omitted when their episode lists match exactly. These are deliberately different compositions.
- Library: title and discovery/full-library navigation share a 64 dp header. A 43 dp filter row sits immediately above the six-column poster grid.
- Browsing card widths: landscape 214 dp, TV episodes 264 dp, posters 120 dp. Landscape artwork uses 16:9; posters use 2:3. The full grid scales six columns to available width. Captions reserve a fixed height.
- Search uses three columns of landscape results. Episodes use their actual stills, preserving their native proportions instead of cropping them into posters.
- Features use original Plex clear-logo artwork within 264 × 80 dp, falling back to title text. Detail title: 34/37 sp. Library title: 29/34 sp. Discovery rail heading: 17/22 sp. Supporting information: 10/14 sp.
- Poster and thumbnail corners: 6 dp. Compact action corners: 5 dp. Cards have no idle border; a compact bottom-right check marks watched titles, or a number shows remaining episodes for a show/season when Plex provides counts. Unwatched movies have no badge. Resumed movies/episodes only show a check after the configured playback threshold (80 percent by default), even if Plex retains a historical watched flag. Completed titles with no resume position retain Plex's watched state. Progress uses a two-dp inset line.
- The abstract six-facet aperture mark is shared by the header, sign-in, app icon, TV banner, and a short cold-start splash. It uses muted sea-glass and warm ivory facets around a dark center, with no letterform or sparkle.
- Audience ratings display Rotten Tomatoes as a percentage beside a local popcorn-bucket vector, and IMDb on its native ten-point scale beside the gold IMDb logo. Both appear when Plex exposes both; TVDB is retained as a fallback when neither is available. Critic scores and unsupported providers are omitted. Stable preview focus hydrates detail metadata, where Plex exposes the full provider list. The popcorn bucket tips for audience scores below 60 percent. The IMDb vector uses the official gold primary mark and supplied clear space from the [IMDb brand toolkit](https://brand.imdb.com/imdb).
## Focus and motion
- Discovery cards keep fixed bounds and use a two-dp white focus outline. No scale or shadow changes trigger lazy-row layout or move a neighboring row.
- Text actions scale to 1.025 over 160 ms. Navigation uses text, an understated selected underline, and a translucent charcoal focus surface.
- Navigation contrast comes from a gradient extending past the controls and fading to transparent. Home/Movies/TV activate on focus. Explicit row and column links prevent beyond-bounds focus searches when holding a remote direction.
- A D-pad move predicts the actual row/column destination before starting its scroll or focus change. The target backdrop is fetched and contrast-processed through the same Coil request/cache as the visible scene. Speculative artwork uses one low-priority worker so it cannot flood normal decode workers during a burst of input. Metadata starts in parallel; the visible preview and details page share that in-flight request. Rapid navigation replaces the queued metadata target and cancels superseded artwork prefetches. Full metadata uses a 64-item LRU with a 30-second lifetime, cleared on account/server changes and refreshed after watched updates. Neutral library/search grids prefetch metadata without fetching an unused full-screen backdrop.
- Section previews settle for 120 ms (Home artwork for 90 ms), overlapping the navigation animation, and retain previous artwork until replacement data is ready. Contrast gradients are baked into a cached bitmap on a worker thread, reducing GPU overdraw. Hero recommendation changes crossfade the artwork over 220 ms, including cache hits, and fade the title/summary out for 100 ms and back in over 180 ms. Rotation pauses on the information/next controls and preserves their focus. Vertical row changes animate to explicit row/column targets; page entrances fade and slide 28 dp over 280 ms. The cold-start logo reveals over 1.1 seconds; the cover lasts 1.6 seconds with up to 600 ms extra for loading, then fades over 240 ms. It does not replay when returning from background.
- Returning from details restores the library's mode, scroll position, and previously focused title.
## Player
Controls occupy a shallow bottom gradient. A compact title, slim timeline, small time labels, central transport icons, and right-aligned track icons replace the rectangular button grid. The timeline is a true D-pad focus target: Up from transport reaches it, Left/Right seek, and Down returns to Play/Pause. Holding a direction increases the seek step. Dedicated media keys remain supported.
The controls fade and slide away after five seconds during playback. OK reveals them; Back hides them before exiting. Audio and subtitle panels open above their icons and restore focus when dismissed. A gear exposes playback mode, audio, subtitles, speed, transcode quality, and chapters. Direct stream is the saved default. The timeline includes buffered progress and server-generated video/chapter previews. Skip actions have opaque contrast surfaces.
Episode endings and Skip credits open a five-second, cancellable next-episode countdown with season episodes and related shows. Each player session has a unique Media3 session ID so overlapping Compose disposal and next-episode creation cannot collide.
Settings includes a persistent watched percentage. Timeline reporting scrobbles the item in Plex once the selected percentage is reached, retries a failed write, and avoids repeated scrobbles within the same player session. This preference belongs to Kaleido and does not change the Plex server's global settings. Explicit watched changes refresh the title and parent episode counts across browsing caches.
## Device review
Use `scripts/verify_ui.py browse` and `scripts/verify_ui.py player` with the authorized ADB connection. These drive the actual UI with remote key events, assert focus and navigation, and capture screens into the ignored `evidence/private/` directory. The player check uses the live Plex server's existing conversion mode. Run `Build.ps1 -Test` for compilation, unit tests, and lint. Inspect the optimized release APK on the TV before judging startup or animation performance.
Visual references: [Netflix's TV experience](https://about.netflix.com/en/news/unveiling-our-innovative-new-tv-experience), [Netflix's current TV layout guidance](https://help.netflix.com/en/node/321880164349028), and [Apple TV](https://www.apple.com/apple-tv-app/). The layout and artwork remain independent and Plex-backed.

View file

@ -0,0 +1,46 @@
# Browsing composition rebuild
The supplied Apple TV and Netflix references were studied before this implementation. The relevant area is the TV screen itself, excluding the surrounding television frame and Netflix's promotional page text.
## Principles observed
The scene is the page, not a banner at its top. Both references preserve a broad cinematic frame, with the principal subject in the center or right and a restrained information area on the left. The artwork continues behind the first content heading and thumbnails. Gradients provide local text contrast and a gradual lower transition without dividing the screen into an image region and a solid catalog region.
The title identity, short synopsis, and playback action form one visual group inside the artwork. Metadata is secondary, and descriptive text stays narrow enough to leave the subject visible. Title artwork supplies character that a repeated generic text heading cannot.
The first row enters close to the bottom of the viewport, inviting downward exploration. Its relationship to the hero matters more than fitting a complete catalog row into the initial screen. Subsequent discovery sections vary scale and aspect ratio; the A–Z library is a different browsing task and remains a compact poster grid.
## What the preceding implementation missed
The old home artwork ended around 57 percent of the screen, followed by black catalog space. It also cropped a 16:9 backdrop into a shallow banner. Movies and TV discovery opened with a utility heading and uniformly sized rows rather than a featured scene. Making those elements smaller did not change their composition.
## New structure and review targets
- Home, Movies Discover, and TV Discover share a full-viewport backdrop canvas with light parallax and a localized left contrast gradient.
- The first rail overlaps the lower portion of that same canvas. The artwork does not end before the rail.
- Original Plex clear-logo artwork supplies title identity, with a real text fallback. Episode stills, scene backdrops, and portrait posters have separate contexts.
- Continue Watching uses compact landscape cards; recently added films use posters; larger featured recommendations and other landscape rails provide discovery variation.
- Navigation floats over the scene. Entering the dedicated A–Z view restores compact catalog chrome and the six-column filtered/sorted grid.
- Screen changes use a short entrance fade. Focus changes use bounded scale, a thin image outline, and debounced backdrop previews.
Validate screenshots from the onn against the supplied references for scene prominence, subject framing, title hierarchy, row overlap, and lack of a horizontal banner/catalog boundary. Record actual remaining shortcomings and iterate before delivery. The player is outside this redesign's scope.
## Device iterations
The first rebuilt composition made the scene dominant, but its title treatment was too large and the first row entered too low. The second reduced the logo to 264 dp and the hero stage to 77.5 percent of the viewport. Continue Watching identity moved toward the center of each thumbnail so it remains recognizable as the row enters the screen.
Movies retains the live Matchbox feature and leads with recently released posters, followed by larger movie recommendations. TV leads with resume-ready episodes, then newly aired episodes and series recommendations. These use the server's real hub contents; a duplicate recently-added episode hub is omitted when it exactly matches the newly-aired hub. Home remains a mixed destination.
Remote testing exposed focus boundaries between floating chrome and lazy content. Explicit focus links now connect primary navigation, section controls, and hero actions. Entering the full library focuses its Library control, and returning from details restores the selected discovery card.
A solid backing behind scrolled navigation proved too visually heavy in device review. It was replaced with an extended gradient that fades into the content. Section controls retreat while browsing lower rails and reappear when returning to the top; D-pad navigation scrolls the hero into place before requesting focus.
The optimized APK was installed on the authorized onn at 192.168.50.195. Five remote-driven browsing checks passed: live Home composition, card focus restoration after details, separate Movies discovery and filtered A–Z library, TV next/new episode rows, and section Back navigation. Release compilation, unit tests, and lint passed with no lint errors. Captures remain in the ignored evidence/private directory. The player was not part of this browsing review.
## Current direction after performance and usability review
Home again uses the large cinematic feature and playback actions. The compact fixed preview is specific to Movies, following focused posters above recently released films and movie recommendations. TV uses a shorter preview and larger episode thumbnails, with next episodes, newly added seasons, then new episodes and show recommendations. Full libraries retain their separate filtered A-Z poster grid.
Fixed card geometry, explicit D-pad row/column targets, cached backdrop contrast and debounced preview changes replace scaling cards, repeated lazy focus searches and full-screen gradient overdraw. Startup server discovery runs independently of tab requests: a cold-start tab switch previously cancelled initialization and left Movies/TV blank. Section data now updates atomically and empty discovery results offer a library action.
The earlier device-review paragraphs describe previous iterations, not the current test status. Current evidence and regression results are recorded under evidence/private; use scripts/repro_runtime.py sections, browse, episode, credits and postplay, plus scripts/verify_ui.py, for the applicable live device loops.

View file

@ -0,0 +1,29 @@
# Device regression review - 2026-10-23
Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`.
## Browsing
- Cold-start switching to Movies reproduced an empty page: tab loading cancelled server initialization before library discovery finished. Initialization now has its own job; section requests update their cache and visible results atomically. `scripts/repro_runtime.py sections` passes the same startup switch, TV loading and cached Movies return.
- Home again has the large cinematic feature with Play/Resume, information and feature navigation. Movies has the compact focused-title preview with recent-release posters and recommendations. TV has wider next-episode thumbnails, newly added seasons and new episodes. A-Z remains a separate filtered poster grid.
- All six `scripts/verify_ui.py browse` checks passed, including primary tab activation on focus, details/card focus restoration, library navigation and a live Plex PIN with cancellation preserving the connection.
- Fixed card geometry and explicit row/column navigation remove horizontal vertical drift. Cached bitmap contrast reduces backdrop GPU work. API JSON parsing is off the main thread.
- Profiling found substantial interpreted Compose/layout work immediately after ADB installation. Android reported `status=verify`, not profile-guided compilation. Installing the bundled baseline profile and compiling **only Kaleido** with `speed-profile` changed the measured browsing loop from p95 65 ms to 20 ms, median 14 ms, GPU p95 5 ms. Horizontal card bounds retained the same Y coordinate. This is a device stress measurement, not a guarantee of zero dropped frames. Baseline rules now also include app browsing paths.
For reproducible performance checks, install the release, send `androidx.profileinstaller.action.INSTALL_PROFILE` to Kaleido's ProfileInstallReceiver, compile its package with `cmd package compile -f -m speed-profile tv.kaleido.app`, then run `scripts/repro_runtime.py browse`. Do not benchmark debug builds or compare different compilation states. Ordinary sideloads receive profile-guided optimization through Android's background dex optimization; immediate first-run measurements can therefore be slower.
## Playback and account connection
- Six live Android integration tests passed: encrypted session persistence, library paging/filter/search/details/hubs, show/season/episode access, a real Plex PIN, generated JPEG previews/new seasons, and a server decision copying the supported HEVC test episode's video.
- Next episode previously crashed with `Session ID must be unique`. Each controller now owns a unique Media3 session ID. The actual episode replacement loop passes and reaches the expected next title.
- Plex HLS uses an absolute timeline. Removing the duplicate seek-start offset fixes resume/progress and credits-marker positions.
- Natural episode completion reached post-play, waited five seconds and reached READY on the next episode. Credits skipping also opened season/related rows and its autoplay cancellation test passed.
- Player tests exercised real video, scrubbing previews, audio/subtitle panels, speed changes and Direct stream selection. A separate targeted regression verifies that one Back hides controls, OK reveals them, playback auto-hides them and Back exits. Explicit preview-key handling fixes Back clearing focus before reaching the player handler.
- Direct stream is the default preference. The client augments the existing Plex HEVC target instead of supplying competing transcode targets. The server can still choose conversion for media it cannot remux using the negotiated profile. Original-file and compatibility playback remain available.
- The onn's ADB screen captures omit the tested HEVC picture even while Media3 reports rendered frames. The user confirmed that the actual TV displays the video. Do not treat that capture alone as a black-video failure or silently force transcoding.
- Skip actions use an opaque contrast surface. The timeline draws buffered and played ranges separately and shows generated server previews or chapter artwork when available.
- The release ZIP was checked for the actual private test token and `.env`: neither is present. The test connection is encrypted private device data. Settings exposes Plex account linking and server discovery.
Release compilation, unit tests and lint passed with zero lint errors (existing warnings remain). Temporary debugging log tags were removed.
The final release recheck after adding the app baseline rules passed again: median 15 ms, p95 27 ms, GPU p95 5 ms, stable row Y coordinates. Results remain dependent on device compilation state; some frames still miss a 60 Hz deadline under the burst test.

4
gradle.properties Normal file
View file

@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
android.useAndroidX=true
kotlin.code.style=official
org.gradle.parallel=true

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionSha256Sum=20f1b1176237254a6fc204d8434196fa11a4cfb387567519c61556e8710aed78

251
gradlew vendored Normal file
View file

@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
gradlew.bat vendored Normal file
View file

@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

22
scripts/bootstrap.py Normal file
View file

@ -0,0 +1,22 @@
"""Install an isolated, reproducible Windows Android build toolchain."""
import concurrent.futures, pathlib, urllib.request, zipfile
ROOT = pathlib.Path(__file__).resolve().parents[1]
TOOLS = ROOT / '.tools'
TOOLS.mkdir(exist_ok=True)
def install(name, url, destination, marker):
if (TOOLS / marker).exists(): return
archive = TOOLS / (name + '.zip')
if not archive.exists():
print('Downloading ' + name, flush=True)
urllib.request.urlretrieve(url, archive)
with zipfile.ZipFile(archive) as z: z.extractall(TOOLS / destination)
print('Installed ' + name, flush=True)
jobs = [
('jdk','https://cdn.azul.com/zulu/bin/zulu17.68.203-ca-crac-jdk17.0.20.1-win_x64.zip','jdk','jdk/zulu17.68.203-ca-crac-jdk17.0.20.1-win_x64/bin/java.exe'),
('gradle','https://services.gradle.org/distributions/gradle-8.13-bin.zip','','gradle-8.13/bin/gradle.bat'),
('commandline','https://dl.google.com/android/repository/commandlinetools-win-13114758_latest.zip','sdk/cmdline-tools','sdk/cmdline-tools/latest/bin/sdkmanager.bat')]
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
list(pool.map(lambda args: install(*args),jobs))
p = TOOLS / 'sdk/cmdline-tools/cmdline-tools'
if p.exists(): p.rename(p.with_name('latest'))
print('Tool downloads complete', flush=True)

22
scripts/check_video.py Normal file
View file

@ -0,0 +1,22 @@
"""Regression loop: play the known live test title at 90s and assert visible video."""
import pathlib, sys, time, re
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from device import adb,OUT
from PIL import Image
import io
mode=int(sys.argv[1]) if len(sys.argv)>1 else 0
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode',str(mode))
time.sleep(12)
pid=adb('shell','pidof','tv.kaleido.app').decode().strip()
assert pid,'Kaleido process exited during playback'
logs=adb('logcat','-d','-t','1000','--pid='+pid,'-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
assert 'READY item=' in logs,'Player never reached READY: '+logs[-3000:]
assert re.search(r'topResumedActivity=.*tv\.kaleido\.app',adb('shell','dumpsys','activity','activities').decode(errors='replace')),'Kaleido is not the foreground activity'
raw=adb('exec-out','screencap','-p');(OUT/f'video-mode-{mode}.png').write_bytes(raw)
im=Image.open(io.BytesIO(raw)).convert('RGB')
pixels=list(im.crop((450,150,1750,600)).getdata())
visible=sum(max(p)>32 for p in pixels)/len(pixels)
print(f'Video region visible pixels: {visible:.1%}')
assert visible>.05,'BLACK VIDEO: decoded picture is not visible'
print('PASS: actual video picture is visible')

36
scripts/device.py Normal file
View file

@ -0,0 +1,36 @@
"""Operate only Kaleido on the authorized onn streamer. Credentials stay on stdin."""
import argparse, json, pathlib, subprocess, sys, time, xml.etree.ElementTree as ET
ROOT=pathlib.Path(__file__).resolve().parents[1]
ADB=pathlib.Path(r'C:\Users\Elijah\Desktop\platform-tools\adb.exe')
DEVICE='192.168.50.195:5555'
OUT=ROOT/'evidence/private'
OUT.mkdir(parents=True,exist_ok=True)
def adb(*args, data=None):
p=subprocess.run([str(ADB),'-s',DEVICE,*args],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if p.returncode: raise RuntimeError(p.stderr.decode(errors='replace'))
return p.stdout
def screenshot(name):
path=OUT/(name+'.png');path.write_bytes(adb('exec-out','screencap','-p'));print(path)
def hierarchy():
adb('shell','uiautomator','dump','/data/local/tmp/kaleido-window.xml')
raw=adb('shell','cat','/data/local/tmp/kaleido-window.xml');(OUT/'window.xml').write_bytes(raw)
root=ET.fromstring(raw)
for n in root.iter('node'):
if n.get('text') or n.get('focused')=='true':print({k:n.get(k) for k in ['text','content-desc','focused','bounds']})
def seed():
env=dict(l.strip().split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#'))
data=json.dumps({'server':env['PLEX_SERVER_URL'].strip('\"\''),'token':env['PLEX_TOKEN'].strip('\"\'')}).encode()
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','run-as','tv.kaleido.app','mkdir','-p','files')
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > files/bootstrap.json"',data=data)
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
print('Private test session provisioned. No credentials are embedded in the APK.')
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['seed','screenshot','hierarchy','key','launch','logs']);p.add_argument('value',nargs='?',default='screen');a=p.parse_args()
if a.action=='seed':seed()
if a.action=='screenshot':screenshot(a.value)
if a.action=='hierarchy':hierarchy()
if a.action=='key':adb('shell','input','keyevent',a.value)
if a.action=='launch':print(adb('shell','am','start','-n','tv.kaleido.app/.MainActivity').decode())
if a.action=='logs':
text=adb('logcat','-d','-t','2000','KaleidoPlayback:I','AndroidRuntime:E','ExoPlayerImpl:I','*:S').decode(errors='replace');(OUT/'device.log').write_text(text);print(text[-16000:])

23
scripts/inspect_server.py Normal file
View file

@ -0,0 +1,23 @@
"""Read-only Plex connectivity inventory; never prints credentials."""
import json, pathlib, urllib.request, urllib.parse
ROOT = pathlib.Path(__file__).resolve().parents[1]
env = dict(line.strip().split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line and not line.startswith('#'))
base = env['PLEX_SERVER_URL'].strip('\"\'').rstrip('/')
token = env['PLEX_TOKEN'].strip('\"\'')
def get(path):
req = urllib.request.Request(base+path,headers={'X-Plex-Token':token,'Accept':'application/json','X-Plex-Product':'Kaleido','X-Plex-Client-Identifier':'kaleido-development'})
with urllib.request.urlopen(req,timeout=20) as r: return json.load(r)['MediaContainer']
if __name__ == '__main__':
print('Server:', get('/').get('friendlyName'), 'version:', get('/').get('version'))
sections = get('/library/sections').get('Directory',[])
for s in sections:
print('Section', s['key'],s['title'],s['type'])
d=get('/library/sections/'+s['key']+'/all?X-Plex-Container-Start=0&X-Plex-Container-Size=2&sort=titleSort')
print('Total:', d.get('totalSize',d.get('size')))
for m in d.get('Metadata',[]):
print('Sample:', {k:m.get(k) for k in ['ratingKey','title','type','duration','viewOffset']})
for media in m.get('Media',[]): print('Media:', {k:media.get(k) for k in ['container','videoCodec','audioCodec','videoResolution']})
for path in ['/hubs/home','/hubs','/library/onDeck']:
try:
d=get(path); print(path,[(h.get('title'),len(h.get('Metadata',[]))) for h in d.get('Hub',[])], 'items:',d.get('size'))
except Exception as e: print(path,type(e).__name__)

View file

@ -0,0 +1,15 @@
"""Stage a locally signed APK for Git distribution and tag-triggered Forgejo releases."""
import hashlib, json, pathlib, shutil, subprocess
ROOT=pathlib.Path(__file__).resolve().parents[1]
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().splitlines() if '=' in l)
apk=ROOT/'app/build/outputs/apk/release/app-release.apk'
if not apk.exists():raise SystemExit('Run Build.ps1 -Release first.')
out=ROOT/'distribution';out.mkdir(exist_ok=True)
shutil.copyfile(apk,out/'Kaleido.apk')
digest=hashlib.sha256(apk.read_bytes()).hexdigest()
(out/'Kaleido.apk.sha256').write_text(digest+' Kaleido.apk\n')
repo='https://git.elijahkuntz.com/Elijah/Kaleido'
tag='v'+version['versionName']
manifest={'version':version['versionName'],'versionCode':int(version['versionCode']),'url':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk','checksumUrl':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk.sha256','notes':(ROOT/'CHANGELOG.md').read_text().split('\n## ')[1].split('\n## ')[0] if (ROOT/'CHANGELOG.md').exists() else ''}
(out/'latest.json').write_text(json.dumps(manifest,indent=2)+'\n')
print('Packaged',tag,'SHA-256',digest)

23
scripts/profile_browse.py Normal file
View file

@ -0,0 +1,23 @@
"""Capture app atrace sections around actual remote navigation."""
import re,time,collections
from device import adb,OUT
from verify_ui import launch,key
launch();key(20);time.sleep(2)
pid=adb('shell','pidof','tv.kaleido.app').decode().strip()
adb('shell','atrace','--async_start','-b','16384','-a','tv.kaleido.app','gfx','view','sched')
adb('shell','input','keyevent',*(['KEYCODE_DPAD_RIGHT']*15))
adb('shell','input','keyevent',*(['KEYCODE_DPAD_DOWN']*3))
adb('shell','input','keyevent',*(['KEYCODE_DPAD_UP']*6))
raw=adb('shell','atrace','--async_stop','-a','tv.kaleido.app','gfx','view','sched').decode(errors='replace')
(OUT/'browse-atrace.txt').write_text(raw)
stacks=collections.defaultdict(list);spans=[]
for line in raw.splitlines():
match=re.search(r'-(\d+)\s+.*?\s(\d+\.\d+): tracing_mark_write: ([BE])(?:\|(.*))?',line)
if not match:continue
tid,stamp,kind,payload=match.groups();stamp=float(stamp)
if kind=='B':
owner,_,name=(payload or '').partition('|');stacks[tid].append((stamp,name,owner))
elif stacks[tid]:
start,name,owner=stacks[tid].pop()
if owner==pid:spans.append(((stamp-start)*1000,name,tid))
for duration,name,tid in sorted(spans,reverse=True)[:35]:print(f'{duration:8.2f}ms tid={tid} {name}')

View file

@ -0,0 +1,26 @@
"""Publish the checked-in, signed APK using Forgejo's repository-scoped CI token."""
import hashlib, json, os, pathlib, urllib.request, uuid
ROOT=pathlib.Path(__file__).resolve().parents[1]
API='https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido'
token=os.environ['KALEIDO_RELEASE_TOKEN']
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().splitlines() if '=' in l)
tag='v'+version['versionName']
ref=os.environ.get('RELEASE_REF','')
assert ref=='refs/tags/'+tag,'Tag must match version.properties exactly'
out=ROOT/'distribution'
assert hashlib.sha256((out/'Kaleido.apk').read_bytes()).hexdigest()==(out/'Kaleido.apk.sha256').read_text().split()[0]
def call(path,data=None,method=None,content='application/json'):
req=urllib.request.Request(API+path,data=data,method=method,headers={'Authorization':'token '+token,'Content-Type':content})
with urllib.request.urlopen(req,timeout=120) as response:return json.load(response)
try:release=call('/releases/tags/'+tag)
except urllib.error.HTTPError as e:
if e.code!=404:raise
release=call('/releases',json.dumps({'tag_name':tag,'name':'Kaleido '+version['versionName'],'body':(ROOT/'CHANGELOG.md').read_text(),'draft':True,'prerelease':False}).encode(),'POST')
existing={a['name']:a for a in release.get('assets',[])}
for name in ['Kaleido.apk','Kaleido.apk.sha256']:
if name in existing:continue
boundary='kaleido'+uuid.uuid4().hex
data=(f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode()+(out/name).read_bytes()+f'\r\n--{boundary}--\r\n'.encode()
call(f'/releases/{release["id"]}/assets?name='+name,data,'POST','multipart/form-data; boundary='+boundary)
call('/releases/'+str(release['id']),json.dumps({'draft':False}).encode(),'PATCH')
print('Published',tag)

117
scripts/repro_runtime.py Normal file
View file

@ -0,0 +1,117 @@
"""On-device regression loops for focus geometry, frame pacing, and episode replacement."""
import sys,time,re,json
from device import adb,OUT,screenshot
from verify_ui import key,snapshot,focus,labels,wait,focused,launch
def sections():
# The splash gates remote input; switch as soon as the first browsing frame is available.
# Initialization must remain independent of tab loading on slow servers.
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
wait(lambda r:'Home' in labels(r) and labels(r).count('KALEIDO')==1,'Cold-start splash must finish')
key(22)
wait(lambda r:'Recently released' in labels(r),'Movies must finish loading after a startup tab switch')
focused('Movies');screenshot('cold-tabs-fixed')
key(22);wait(lambda r:'Next episodes' in labels(r),'TV recommendations must load');focused('TV Shows')
key(21);wait(lambda r:'Recently released' in labels(r),'Cached Movies must return');focused('Movies')
print('PASS startup tab switch, TV loading, and cached section return')
def controls():
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','1')
time.sleep(9);key(127);focused('Play')
screenshot('direct-stream-episode')
key(4);wait(lambda r:not labels(r),'One Back must hide controls rather than only clearing focus')
key(23);focused('Play');key(126);time.sleep(6)
wait(lambda r:not labels(r),'Controls must auto-hide during playback')
key(4);wait(lambda r:'Continue Watching' in labels(r),'Back must exit hidden player')
print('PASS one-press Back, OK reveal, timed hide, and exit')
def browse():
launch();key(20)
if focus(snapshot()) in ('Play','Resume'):key(20)
wait(lambda r:focus(r) not in ('','Home','Play','Resume'),'Content focus')
adb('shell','dumpsys','gfxinfo','tv.kaleido.app','reset')
geometry=[]
for _ in range(5):
root=snapshot();node=next(n for n in root.iter('node') if n.get('focused')=='true')
bounds=list(map(int,re.findall(r'\d+',node.get('bounds'))))
geometry.append({'focus':focus(root),'bounds':bounds});key(22)
adb('shell','input','keyevent',*(['KEYCODE_DPAD_RIGHT']*15))
adb('shell','input','keyevent',*(['KEYCODE_DPAD_UP']*12))
stats=adb('shell','dumpsys','gfxinfo','tv.kaleido.app','framestats').decode(errors='replace')
(OUT/'browse-framestats.txt').write_text(stats)
(OUT/'browse-geometry.json').write_text(json.dumps(geometry,indent=2))
print(json.dumps(geometry),flush=True)
print('\n'.join(x for x in stats.splitlines() if any(k in x for k in ('Total frames','Janky frames','percentile','Missed Vsync'))),flush=True)
ys=[r['bounds'][1] for r in geometry]
assert max(ys)-min(ys)<=3,f'Horizontal navigation moved row vertically by {max(ys)-min(ys)}px'
print('PASS stable horizontal focus geometry')
p95=int(re.search(r'95th percentile: (\d+)ms',stats)[1])
assert p95<40,f'Browsing frame pacing regression: p95={p95}ms (target below 40ms)'
def episode():
from inspect_server import get
titles=get('/library/metadata/6115/allLeaves').get('Metadata',[])
item=titles[0];expected=str(titles[1]['ratingKey'])
adb('shell','am','force-stop','tv.kaleido.app')
adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item['ratingKey']),'--el','testOffset','90000','--ei','testMode','2')
time.sleep(9);key(127);focused('Play')
for _ in range(6):
if 'Next episode' in focus(snapshot()):break
key(22)
focused('Next episode');key(23);time.sleep(5)
logs=adb('logcat','-d','-t','700','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
(OUT/'episode-replacement.log').write_text(logs)
print(logs[-10000:],flush=True)
assert 'FATAL EXCEPTION' not in logs,'Next episode crashed Android runtime'
assert adb('shell','pidof','tv.kaleido.app').strip(),'Process exited'
assert re.search(r'topResumedActivity=.*tv\.kaleido\.app',adb('shell','dumpsys','activity','activities').decode(errors='replace')),'Lost foreground'
assert 'item='+expected in logs,'Next episode did not become the active player'
print('PASS next episode replaced player with expected title')
def postplay():
from inspect_server import get
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(item['duration']-12000),'--ei','testMode','2')
deadline=time.monotonic()+45
while time.monotonic()<deadline:
time.sleep(1)
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
if 'READY item=8594' in logs or 'FATAL EXCEPTION' in logs:break
(OUT/'postplay-ended.log').write_text(logs);print(logs[-8000:],flush=True)
assert 'FATAL EXCEPTION' not in logs,'Episode end crashed'
assert 'reason=ended' in logs,'Natural end did not open postplay'
assert 'AUTOPLAY starting next=8594' in logs,'Five-second countdown did not start next episode'
assert 'READY item=8594' in logs,'Autoplay did not reach READY'
print('PASS natural end -> five-second countdown -> next episode READY')
def credits():
from inspect_server import get
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
marker=next(m for m in item['Marker'] if m['type']=='credits')
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(marker['startTimeOffset']+2000),'--ei','testMode','2')
time.sleep(6);key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits')
screenshot('skip-credits-contrast');key(23)
deadline=time.monotonic()+8
while time.monotonic()<deadline:
time.sleep(.1)
ready=adb('logcat','-d','-s','KaleidoPlayback:I','*:S').decode(errors='replace')
if 'POSTPLAY focus=play' in ready:break
assert 'POSTPLAY focus=play' in ready,'Postplay initial action never received focus'
key(22);key(23)
wait(lambda r:'Autoplay off' in labels(r),'Autoplay cancellation')
screenshot('postplay-season-and-related');time.sleep(6)
root=snapshot();assert 'Up next' in labels(root),'Cancellation failed to keep postplay open'
assert 'Episodes in this season' in labels(root),'Season episodes absent'
assert 'Related shows' in labels(root),'Related shows absent'
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
assert 'reason=skip-credits' in logs,'Skip credits did not open postplay'
assert 'AUTOPLAY starting' not in logs,'Cancelled autoplay still advanced'
(OUT/'postplay-cancel.log').write_text(logs)
print('PASS skip credits -> postplay, episode/related rows, cancellable autoplay')
globals()[sys.argv[1]]()

View file

@ -0,0 +1,41 @@
"""Focused browsing checks for the real onn; all captures stay private."""
import io,json,time
from PIL import Image,ImageChops,ImageStat
from device import adb,OUT,screenshot
from verify_ui import key,snapshot,labels,focus,wait,focused,launch
def capture_bytes(name):
raw=adb('exec-out','screencap','-p');(OUT/(name+'.png')).write_bytes(raw)
return Image.open(io.BytesIO(raw)).convert('RGB')
launch();key(20);focused('Play');key(22,2);focused('Next featured title')
# Explicitly advance to see all three categories without waiting for the carousel timer.
reasons=[]
for i in range(3):
root=snapshot();reasons.append(next((s for s in labels(root) if s in ('RECENTLY RELEASED','HIGHLY RATED · UNWATCHED','SUGGESTED FOR YOU')),''))
if i<2:
focused('Next featured title');key(23);time.sleep(.7);focused('Next featured title')
assert len(set(reasons))==3,reasons
print('PASS real hero cycles recent releases, highly rated unwatched, and suggestions',flush=True)
key(21,2);focused('Play');key(20);time.sleep(1)
first=focus(snapshot());a=capture_bytes('updates-home-focus-one')
key(22);time.sleep(1);second=focus(snapshot());b=capture_bytes('updates-home-focus-two')
assert first!=second
w,h=a.size
# Above the row and below navigation, only the backdrop occupies this region.
region=(int(w*.58),int(h*.10),int(w*.94),int(h*.16))
difference=sum(ImageStat.Stat(ImageChops.difference(a.crop(region),b.crop(region))).mean)/3
assert difference>3,f'Focused Home background did not change: {difference}'
print('PASS Home backdrop follows focused title (mean pixel change %.1f)'%difference,flush=True)
key(20);single_row=focus(snapshot())
launch();key(20);focused('Play');key(20);snapshot()
for _ in range(6):adb('shell','input','keyevent','20');time.sleep(.08)
held=focus(snapshot())
assert held!=single_row,f'Rapid Down kept restarting the same row: {held}'
print('PASS rapid Down advances beyond one animated row',flush=True)
launch();key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23)
root=wait(lambda r:any('episodes remaining' in n.get('content-desc','') for n in r.iter('node')),'Show episode counts')
screenshot('updates-show-counts');print('PASS show library exposes remaining episode badges',flush=True)
# Leave the device in a useful Home state.
key(4);key(4);focused('Home')
(OUT/'browse-updates-results.json').write_text(json.dumps({'hero_categories':reasons,'backdrop_pixel_difference':difference},indent=2),encoding='utf-8')

89
scripts/verify_ui.py Normal file
View file

@ -0,0 +1,89 @@
"""Remote-only UI regression checks on the authorized onn; captures remain private."""
import argparse,json,pathlib,re,sys,time,xml.etree.ElementTree as ET
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from device import adb,OUT,screenshot
results=[]
def key(code,count=1):
for _ in range(count):
adb('shell','input','keyevent',str(code));time.sleep(.22)
def snapshot():
adb('shell','uiautomator','dump','/data/local/tmp/kaleido-window.xml')
return ET.fromstring(adb('shell','cat','/data/local/tmp/kaleido-window.xml'))
def labels(root):return [n.get('text','') for n in root.iter('node') if n.get('text')]
def focus(root):
n=next((n for n in root.iter('node') if n.get('focused')=='true'),None)
if n is None:return ''
return n.get('content-desc','') or ' '.join(labels(n))
def wait(check,description,timeout=25):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
root=snapshot()
if check(root):return root
time.sleep(.2)
raise AssertionError(description+'; last focus='+focus(root)+'; labels='+str(labels(root)[:10]))
def text(value):return wait(lambda root:value in labels(root),'Expected text '+value)
def focused(value):return wait(lambda root:value in focus(root),'Expected focus '+value)
def passed(name):results.append(name);print('PASS '+name,flush=True)
def capture(name):time.sleep(.4);screenshot('final-'+name)
def launch():
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
text('Continue Watching')
wait(lambda r:labels(r).count('KALEIDO')==1,'Cold-start splash must finish')
focused('Home')
def browse():
launch();key(20);wait(lambda r:focus(r) in ('Play','Resume'),'Home hero action');capture('home')
key(20);wait(lambda r:bool(focus(r)) and focus(r) not in ('Home','Play','Resume'),'Continue Watching focus');capture('home-continue')
passed('Large cinematic Home hero and separate landscape Continue Watching')
key(22);selected=focus(snapshot());key(23)
wait(lambda r:any(x.startswith('Resume') or x=='Play' for x in labels(r)),'Playable details')
key(4);focused(selected);passed('Discovery details returns to the same focused card')
key(19);wait(lambda r:focus(r) in ('Play','Resume'),'Return to Home hero');key(19);focused('Home');key(22);text('Recently released');focused('Movies')
capture('movies-discover');key(20);focused('Discover');key(22);focused('Library');key(23)
text('All genres ⌄');focused('Library');capture('movies-library')
passed('Movies prioritizes recent releases and retains a separate filtered A-Z grid')
key(20);wait(lambda r:bool(focus(r)) and 'Library' not in focus(r),'Library content or filter focus')
key(4);focused('Discover');key(19);focused('Movies');key(22)
text('Next episodes');focused('TV Shows');capture('tv-discover')
key(20);focused('Discover');key(20);wait(lambda r:bool(focus(r)) and focus(r)!='Discover','TV next episode focus')
capture('tv-next-episodes');key(20);text('New seasons');capture('tv-new-seasons');key(20);text('New episodes');capture('tv-new-episodes')
passed('TV prioritizes next episodes, new seasons, and new episodes')
key(4);focused('Home');passed('Section Back returns to Home navigation')
key(22,4);focused('Settings');key(23);text('Settings');focused('Sign in with Plex');key(23)
text('Sign in to Plex');text('plex.tv/link')
wait(lambda r:any(re.fullmatch(r'[A-Z0-9]{4,6}',s) for s in labels(r)),'Live Plex PIN')
capture('plex-sign-in');key(4);text('Settings');key(4);focused('Home')
passed('Plex account linking obtains a real PIN and cancellation preserves the session')
def player():
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2')
time.sleep(12);key(127);focused('Play');capture('player')
passed('Compact player controls over actual video')
key(19);focused('Playback timeline');key(22);capture('timeline');key(20);focused('Play')
passed('D-pad Up focuses timeline, Right seeks, Down returns to play')
key(22,2);focused('Audio tracks');key(23);text('Audio');capture('audio')
key(4);focused('Audio tracks');key(22);focused('Subtitles');key(23);text('Off');capture('subtitles')
passed('Audio and subtitle panels open, close, and restore focus')
key(4);focused('Subtitles');key(22);focused('Playback options');key(23);text('Playback options')
key(20,3);focused('Speed');key(23);text('Playback speed');focused('1.0×');key(20);focused('1.25×');key(23)
focused('Playback options');key(23);text('Speed · 1.25×');key(4);focused('Playback options')
key(23);text('Playback options');key(23);text('Playback mode');focused('Transcode');key(19);focused('Direct stream');key(23)
focused('Playback options');time.sleep(5);key(23);text('Mode · Direct stream');key(4);focused('Playback options')
passed('Player gear changes speed and Direct stream while retaining focus')
key(4)
wait(lambda r:focus(r)=='' and '2 Fast 2 Furious' not in labels(r),'Controls hidden by Back')
key(23);focused('Play');key(126);time.sleep(6)
wait(lambda r:'2 Fast 2 Furious' not in labels(r),'Controls auto-hide during playback')
passed('OK reveals controls; Back and playback timer hide them')
key(4);text('Continue Watching');passed('Back exits playback to live home')
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('phase',choices=['browse','player']);args=parser.parse_args()
try:
globals()[args.phase]()
finally:
(OUT/('ui-'+args.phase+'-results.json')).write_text(json.dumps(results,indent=2))
print(f'Completed {len(results)} UI checks',flush=True)

4
settings.gradle.kts Normal file
View file

@ -0,0 +1,4 @@
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
rootProject.name = "Kaleido"
include(":app")

2
version.properties Normal file
View file

@ -0,0 +1,2 @@
versionName=0.1.0
versionCode=1