From 2b585badac52acffbc0fef181e19a134074ed13c Mon Sep 17 00:00:00 2001 From: Elijah Date: Sat, 24 Oct 2026 09:09:55 -0700 Subject: [PATCH] Initial Beta build --- .forgejo/workflows/release.yml | 44 +++ .gitignore | 17 ++ AGENTS.md | 91 ++++++ Build.ps1 | 15 + CHANGELOG.md | 5 + README.md | 43 +++ app/build.gradle.kts | 54 ++++ app/proguard-rules.pro | 1 + .../java/tv/kaleido/app/BrowsePolicyTest.kt | 92 ++++++ .../java/tv/kaleido/app/LivePlexTest.kt | 67 +++++ .../tv/kaleido/app/PreviewMetadataTest.kt | 44 +++ app/src/main/AndroidManifest.xml | 13 + app/src/main/baseline-prof.txt | 6 + .../main/java/tv/kaleido/app/AppUpdater.kt | 66 +++++ .../java/tv/kaleido/app/AudienceRatings.kt | 29 ++ app/src/main/java/tv/kaleido/app/Branding.kt | 56 ++++ .../java/tv/kaleido/app/BrowseBackdrop.kt | 62 ++++ .../main/java/tv/kaleido/app/BrowseScreens.kt | 193 +++++++++++++ .../java/tv/kaleido/app/DiscoveryScreens.kt | 98 +++++++ .../main/java/tv/kaleido/app/FocusedBrowse.kt | 267 +++++++++++++++++ .../main/java/tv/kaleido/app/HomeFeatures.kt | 28 ++ .../java/tv/kaleido/app/KaleidoApplication.kt | 17 ++ .../java/tv/kaleido/app/KaleidoViewModel.kt | 272 ++++++++++++++++++ .../main/java/tv/kaleido/app/MainActivity.kt | 43 +++ app/src/main/java/tv/kaleido/app/Models.kt | 84 ++++++ app/src/main/java/tv/kaleido/app/Playback.kt | 160 +++++++++++ .../java/tv/kaleido/app/PlaybackExtras.kt | 82 ++++++ .../java/tv/kaleido/app/PlayerControls.kt | 215 ++++++++++++++ app/src/main/java/tv/kaleido/app/PlexApi.kt | 112 ++++++++ .../java/tv/kaleido/app/PreviewMetadata.kt | 47 +++ app/src/main/java/tv/kaleido/app/Screens.kt | 148 ++++++++++ .../main/java/tv/kaleido/app/SecureSession.kt | 36 +++ app/src/main/java/tv/kaleido/app/Theme.kt | 99 +++++++ .../java/tv/kaleido/app/WatchedProgress.kt | 9 + .../main/res/drawable/audience_popcorn.xml | 1 + .../res/drawable/audience_popcorn_spilled.xml | 1 + app/src/main/res/drawable/banner.xml | 1 + app/src/main/res/drawable/brand_mark.xml | 1 + app/src/main/res/drawable/icon.xml | 1 + app/src/main/res/drawable/rating_imdb.xml | 1 + app/src/main/res/values/styles.xml | 1 + .../main/res/xml/data_extraction_rules.xml | 1 + app/src/main/res/xml/file_paths.xml | 1 + .../test/java/tv/kaleido/app/VersionsTest.kt | 13 + build.gradle.kts | 5 + docs/design-system.md | 41 +++ docs/reference-analysis.md | 46 +++ docs/runtime-verification.md | 29 ++ gradle.properties | 4 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43705 bytes gradle/wrapper/gradle-wrapper.properties | 8 + gradlew | 251 ++++++++++++++++ gradlew.bat | 94 ++++++ scripts/bootstrap.py | 22 ++ scripts/check_video.py | 22 ++ scripts/device.py | 36 +++ scripts/inspect_server.py | 23 ++ scripts/package_release.py | 15 + scripts/profile_browse.py | 23 ++ scripts/publish_release.py | 26 ++ scripts/repro_runtime.py | 117 ++++++++ scripts/verify_browse_updates.py | 41 +++ scripts/verify_ui.py | 89 ++++++ settings.gradle.kts | 4 + version.properties | 2 + 65 files changed, 3535 insertions(+) create mode 100644 .forgejo/workflows/release.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 Build.ps1 create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100644 app/build.gradle.kts create mode 100644 app/proguard-rules.pro create mode 100644 app/src/androidTest/java/tv/kaleido/app/BrowsePolicyTest.kt create mode 100644 app/src/androidTest/java/tv/kaleido/app/LivePlexTest.kt create mode 100644 app/src/androidTest/java/tv/kaleido/app/PreviewMetadataTest.kt create mode 100644 app/src/main/AndroidManifest.xml create mode 100644 app/src/main/baseline-prof.txt create mode 100644 app/src/main/java/tv/kaleido/app/AppUpdater.kt create mode 100644 app/src/main/java/tv/kaleido/app/AudienceRatings.kt create mode 100644 app/src/main/java/tv/kaleido/app/Branding.kt create mode 100644 app/src/main/java/tv/kaleido/app/BrowseBackdrop.kt create mode 100644 app/src/main/java/tv/kaleido/app/BrowseScreens.kt create mode 100644 app/src/main/java/tv/kaleido/app/DiscoveryScreens.kt create mode 100644 app/src/main/java/tv/kaleido/app/FocusedBrowse.kt create mode 100644 app/src/main/java/tv/kaleido/app/HomeFeatures.kt create mode 100644 app/src/main/java/tv/kaleido/app/KaleidoApplication.kt create mode 100644 app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt create mode 100644 app/src/main/java/tv/kaleido/app/MainActivity.kt create mode 100644 app/src/main/java/tv/kaleido/app/Models.kt create mode 100644 app/src/main/java/tv/kaleido/app/Playback.kt create mode 100644 app/src/main/java/tv/kaleido/app/PlaybackExtras.kt create mode 100644 app/src/main/java/tv/kaleido/app/PlayerControls.kt create mode 100644 app/src/main/java/tv/kaleido/app/PlexApi.kt create mode 100644 app/src/main/java/tv/kaleido/app/PreviewMetadata.kt create mode 100644 app/src/main/java/tv/kaleido/app/Screens.kt create mode 100644 app/src/main/java/tv/kaleido/app/SecureSession.kt create mode 100644 app/src/main/java/tv/kaleido/app/Theme.kt create mode 100644 app/src/main/java/tv/kaleido/app/WatchedProgress.kt create mode 100644 app/src/main/res/drawable/audience_popcorn.xml create mode 100644 app/src/main/res/drawable/audience_popcorn_spilled.xml create mode 100644 app/src/main/res/drawable/banner.xml create mode 100644 app/src/main/res/drawable/brand_mark.xml create mode 100644 app/src/main/res/drawable/icon.xml create mode 100644 app/src/main/res/drawable/rating_imdb.xml create mode 100644 app/src/main/res/values/styles.xml create mode 100644 app/src/main/res/xml/data_extraction_rules.xml create mode 100644 app/src/main/res/xml/file_paths.xml create mode 100644 app/src/test/java/tv/kaleido/app/VersionsTest.kt create mode 100644 build.gradle.kts create mode 100644 docs/design-system.md create mode 100644 docs/reference-analysis.md create mode 100644 docs/runtime-verification.md create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 scripts/bootstrap.py create mode 100644 scripts/check_video.py create mode 100644 scripts/device.py create mode 100644 scripts/inspect_server.py create mode 100644 scripts/package_release.py create mode 100644 scripts/profile_browse.py create mode 100644 scripts/publish_release.py create mode 100644 scripts/repro_runtime.py create mode 100644 scripts/verify_browse_updates.py create mode 100644 scripts/verify_ui.py create mode 100644 settings.gradle.kts create mode 100644 version.properties diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml new file mode 100644 index 0000000..5bdb08d --- /dev/null +++ b/.forgejo/workflows/release.yml @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..afe14ab --- /dev/null +++ b/.gitignore @@ -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 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..d003093 --- /dev/null +++ b/AGENTS.md @@ -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 ` | 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. diff --git a/Build.ps1 b/Build.ps1 new file mode 100644 index 0000000..0222221 --- /dev/null +++ b/Build.ps1 @@ -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' } diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..7112cea --- /dev/null +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3b85726 --- /dev/null +++ b/README.md @@ -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= "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` 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. diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..e158b59 --- /dev/null +++ b/app/build.gradle.kts @@ -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") +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..b2b9efb --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1 @@ +-keepattributes Signature,InnerClasses,EnclosingMethod diff --git a/app/src/androidTest/java/tv/kaleido/app/BrowsePolicyTest.kt b/app/src/androidTest/java/tv/kaleido/app/BrowsePolicyTest.kt new file mode 100644 index 0000000..3fbe39d --- /dev/null +++ b/app/src/androidTest/java/tv/kaleido/app/BrowsePolicyTest.kt @@ -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()) + } +} diff --git a/app/src/androidTest/java/tv/kaleido/app/LivePlexTest.kt b/app/src/androidTest/java/tv/kaleido/app/LivePlexTest.kt new file mode 100644 index 0000000..e69b0b1 --- /dev/null +++ b/app/src/androidTest/java/tv/kaleido/app/LivePlexTest.kt @@ -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")) + } +} diff --git a/app/src/androidTest/java/tv/kaleido/app/PreviewMetadataTest.kt b/app/src/androidTest/java/tv/kaleido/app/PreviewMetadataTest.kt new file mode 100644 index 0000000..d7920a3 --- /dev/null +++ b/app/src/androidTest/java/tv/kaleido/app/PreviewMetadataTest.kt @@ -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();val finish=CompletableDeferred();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();val finish=CompletableDeferred();val calls=mutableListOf() + 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() + 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) + } + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..1bd8dc6 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/app/src/main/baseline-prof.txt b/app/src/main/baseline-prof.txt new file mode 100644 index 0000000..b6a41a1 --- /dev/null +++ b/app/src/main/baseline-prof.txt @@ -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**->**(**)** diff --git a/app/src/main/java/tv/kaleido/app/AppUpdater.kt b/app/src/main/java/tv/kaleido/app/AppUpdater.kt new file mode 100644 index 0000000..647c5d3 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/AppUpdater.kt @@ -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()} + 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} + } +} diff --git a/app/src/main/java/tv/kaleido/app/AudienceRatings.kt b/app/src/main/java/tv/kaleido/app/AudienceRatings.kt new file mode 100644 index 0000000..463d7e7 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/AudienceRatings.kt @@ -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) + }} + } +} diff --git a/app/src/main/java/tv/kaleido/app/Branding.kt b/app/src/main/java/tv/kaleido/app/Branding.kt new file mode 100644 index 0000000..1d4bf95 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/Branding.kt @@ -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)) + } + } +} diff --git a/app/src/main/java/tv/kaleido/app/BrowseBackdrop.kt b/app/src/main/java/tv/kaleido/app/BrowseBackdrop.kt new file mode 100644 index 0000000..bd753f3 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/BrowseBackdrop.kt @@ -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(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(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}) +} diff --git a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt new file mode 100644 index 0000000..4e5a755 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt @@ -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,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)})} + } + } +} diff --git a/app/src/main/java/tv/kaleido/app/DiscoveryScreens.kt b/app/src/main/java/tv/kaleido/app/DiscoveryScreens.kt new file mode 100644 index 0000000..dadbbcb --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/DiscoveryScreens.kt @@ -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}) + } +} diff --git a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt new file mode 100644 index 0000000..e99c5e5 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt @@ -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)) + } +} diff --git a/app/src/main/java/tv/kaleido/app/HomeFeatures.kt b/app/src/main/java/tv/kaleido/app/HomeFeatures.kt new file mode 100644 index 0000000..d25b524 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/HomeFeatures.kt @@ -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 + } + } +} diff --git a/app/src/main/java/tv/kaleido/app/KaleidoApplication.kt b/app/src/main/java/tv/kaleido/app/KaleidoApplication.kt new file mode 100644 index 0000000..3256d6b --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/KaleidoApplication.kt @@ -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() +} diff --git a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt new file mode 100644 index 0000000..64c590d --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt @@ -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&§ion?.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}} +} diff --git a/app/src/main/java/tv/kaleido/app/MainActivity.kt b/app/src/main/java/tv/kaleido/app/MainActivity.kt new file mode 100644 index 0000000..1c6855e --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/MainActivity.kt @@ -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) } +} diff --git a/app/src/main/java/tv/kaleido/app/Models.kt b/app/src/main/java/tv/kaleido/app/Models.kt new file mode 100644 index 0000000..28ca72b --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/Models.kt @@ -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) diff --git a/app/src/main/java/tv/kaleido/app/Playback.kt b/app/src/main/java/tv/kaleido/app/Playback.kt new file mode 100644 index 0000000..b329fbe --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/Playback.kt @@ -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)} diff --git a/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt b/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt new file mode 100644 index 0000000..3b48191 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt @@ -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)) + } + } + } + } +} diff --git a/app/src/main/java/tv/kaleido/app/PlayerControls.kt b/app/src/main/java/tv/kaleido/app/PlayerControls.kt new file mode 100644 index 0000000..63a37a2 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/PlayerControls.kt @@ -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) + } +} diff --git a/app/src/main/java/tv/kaleido/app/PlexApi.kt b/app/src/main/java/tv/kaleido/app/PlexApi.kt new file mode 100644 index 0000000..8b8f1ca --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/PlexApi.kt @@ -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"&¤t.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)) } +} diff --git a/app/src/main/java/tv/kaleido/app/PreviewMetadata.kt b/app/src/main/java/tv/kaleido/app/PreviewMetadata.kt new file mode 100644 index 0000000..182ef8f --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/PreviewMetadata.kt @@ -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()} +} diff --git a/app/src/main/java/tv/kaleido/app/Screens.kt b/app/src/main/java/tv/kaleido/app/Screens.kt new file mode 100644 index 0000000..ccca696 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/Screens.kt @@ -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)})}}}}} diff --git a/app/src/main/java/tv/kaleido/app/SecureSession.kt b/app/src/main/java/tv/kaleido/app/SecureSession.kt new file mode 100644 index 0000000..e8f0c27 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/SecureSession.kt @@ -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() } +} diff --git a/app/src/main/java/tv/kaleido/app/Theme.kt b/app/src/main/java/tv/kaleido/app/Theme.kt new file mode 100644 index 0000000..8af1872 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/Theme.kt @@ -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))) + } +} diff --git a/app/src/main/java/tv/kaleido/app/WatchedProgress.kt b/app/src/main/java/tv/kaleido/app/WatchedProgress.kt new file mode 100644 index 0000000..c3ab753 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/WatchedProgress.kt @@ -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} + } +} diff --git a/app/src/main/res/drawable/audience_popcorn.xml b/app/src/main/res/drawable/audience_popcorn.xml new file mode 100644 index 0000000..a9258da --- /dev/null +++ b/app/src/main/res/drawable/audience_popcorn.xml @@ -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> diff --git a/app/src/main/res/drawable/audience_popcorn_spilled.xml b/app/src/main/res/drawable/audience_popcorn_spilled.xml new file mode 100644 index 0000000..71a7e1f --- /dev/null +++ b/app/src/main/res/drawable/audience_popcorn_spilled.xml @@ -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> diff --git a/app/src/main/res/drawable/banner.xml b/app/src/main/res/drawable/banner.xml new file mode 100644 index 0000000..c5bbc91 --- /dev/null +++ b/app/src/main/res/drawable/banner.xml @@ -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> diff --git a/app/src/main/res/drawable/brand_mark.xml b/app/src/main/res/drawable/brand_mark.xml new file mode 100644 index 0000000..ba71e8b --- /dev/null +++ b/app/src/main/res/drawable/brand_mark.xml @@ -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> diff --git a/app/src/main/res/drawable/icon.xml b/app/src/main/res/drawable/icon.xml new file mode 100644 index 0000000..854d2f6 --- /dev/null +++ b/app/src/main/res/drawable/icon.xml @@ -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> diff --git a/app/src/main/res/drawable/rating_imdb.xml b/app/src/main/res/drawable/rating_imdb.xml new file mode 100644 index 0000000..7793cff --- /dev/null +++ b/app/src/main/res/drawable/rating_imdb.xml @@ -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> diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..73dfb17 --- /dev/null +++ b/app/src/main/res/values/styles.xml @@ -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> diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000..1772ef3 --- /dev/null +++ b/app/src/main/res/xml/data_extraction_rules.xml @@ -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> diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..30c52c5 --- /dev/null +++ b/app/src/main/res/xml/file_paths.xml @@ -0,0 +1 @@ +<paths><cache-path name="updates" path="updates/" /></paths> diff --git a/app/src/test/java/tv/kaleido/app/VersionsTest.kt b/app/src/test/java/tv/kaleido/app/VersionsTest.kt new file mode 100644 index 0000000..0c78573 --- /dev/null +++ b/app/src/test/java/tv/kaleido/app/VersionsTest.kt @@ -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")) + } +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..4893ab4 --- /dev/null +++ b/build.gradle.kts @@ -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 +} diff --git a/docs/design-system.md b/docs/design-system.md new file mode 100644 index 0000000..e2b3065 --- /dev/null +++ b/docs/design-system.md @@ -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. diff --git a/docs/reference-analysis.md b/docs/reference-analysis.md new file mode 100644 index 0000000..bade28b --- /dev/null +++ b/docs/reference-analysis.md @@ -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. diff --git a/docs/runtime-verification.md b/docs/runtime-verification.md new file mode 100644 index 0000000..73b01de --- /dev/null +++ b/docs/runtime-verification.md @@ -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. diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..ff8219c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 +android.useAndroidX=true +kotlin.code.style=official +org.gradle.parallel=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..9bbc975c742b298b441bfb90dbc124400a3751b9 GIT binary patch literal 43705 zcma&Obx`DOvL%eWOXJW;<L>V64viP??$)@wHcsJ<yG!Hl?(U7dFYnCW{r1k?dA}jz z`Gcs6s9#i`JSR_PKBXuF4uJsz0|NsB0z&+G{=YvI5Lgg7F;yWtDS2@QSt$`Qc@;4= zRY(xfzuvO0rR}uJ{>68)>bJS6*&iHnskXE8MjvIPVl|FrmV}Npeql07fCw6`pw`0s zGauF(<*@v{3t!qoUU*=j)6;|-(yg@jvDx&fV^trtZt27?4Tkn729qrItVh@PMwG5$ z+oXHSPM??iHZ!cVP~gYact-CwV`}~Q+R}PPNRy+T-geK+>fHrijpllon_F4N{@b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%q1Pi?WpsUUt(tI ztjNjY*y&Rm9(S(DC2GuPHBJs@5M{RGm`c1z<6nwyN^)rMo-AS{M2$oM9|y%fM|}G~ DHx0+F literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ccf4a08 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..faf9300 --- /dev/null +++ b/gradlew @@ -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -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 diff --git a/scripts/bootstrap.py b/scripts/bootstrap.py new file mode 100644 index 0000000..080a2e5 --- /dev/null +++ b/scripts/bootstrap.py @@ -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) diff --git a/scripts/check_video.py b/scripts/check_video.py new file mode 100644 index 0000000..5ac3aa7 --- /dev/null +++ b/scripts/check_video.py @@ -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') diff --git a/scripts/device.py b/scripts/device.py new file mode 100644 index 0000000..fbdf882 --- /dev/null +++ b/scripts/device.py @@ -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:]) diff --git a/scripts/inspect_server.py b/scripts/inspect_server.py new file mode 100644 index 0000000..8289fd4 --- /dev/null +++ b/scripts/inspect_server.py @@ -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__) diff --git a/scripts/package_release.py b/scripts/package_release.py new file mode 100644 index 0000000..7f45b6e --- /dev/null +++ b/scripts/package_release.py @@ -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) diff --git a/scripts/profile_browse.py b/scripts/profile_browse.py new file mode 100644 index 0000000..d96ac65 --- /dev/null +++ b/scripts/profile_browse.py @@ -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}') diff --git a/scripts/publish_release.py b/scripts/publish_release.py new file mode 100644 index 0000000..abda943 --- /dev/null +++ b/scripts/publish_release.py @@ -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) diff --git a/scripts/repro_runtime.py b/scripts/repro_runtime.py new file mode 100644 index 0000000..4bf3768 --- /dev/null +++ b/scripts/repro_runtime.py @@ -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]]() diff --git a/scripts/verify_browse_updates.py b/scripts/verify_browse_updates.py new file mode 100644 index 0000000..6e0434b --- /dev/null +++ b/scripts/verify_browse_updates.py @@ -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') diff --git a/scripts/verify_ui.py b/scripts/verify_ui.py new file mode 100644 index 0000000..5358903 --- /dev/null +++ b/scripts/verify_ui.py @@ -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) diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..b5f7b38 --- /dev/null +++ b/settings.gradle.kts @@ -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") diff --git a/version.properties b/version.properties new file mode 100644 index 0000000..de6b9ea --- /dev/null +++ b/version.properties @@ -0,0 +1,2 @@ +versionName=0.1.0 +versionCode=1