Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

chore: apply pending project updates

Davidona39cab841e9c8
diff --git a/Fixing IPTV Metadata.md b/Fixing IPTV Metadata.md
deleted file mode 100644
index 51d850f5..00000000
--- a/Fixing IPTV Metadata.md
+++ /dev/null
@@ -1,2340 +0,0 @@
-# Chat Conversation
-
-Note: _This is purely the output of the chat conversation and does not contain any raw data, codebase snippets, etc. used to generate the output._
-
-*User accepted the command `findstr /i /c:"com.streamvault.app" "c:\Users\david\.gemini\antigravity\scratch\iptv-player\temp_log.txt" | findstr /v "ApkAssets:"`*
-
-*Checked command status*
-
-### User Input
-
-i gave you everything it should be towards the end it is you who think its an error, i never said it crashes it just behaves as if i pressed home button or exist
-
-*Edited relevant file*
-
-*User accepted the command `git checkout app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*User accepted the command `git checkout app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*User accepted the command `git checkout app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt`*
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `type build_errors.txt`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2`*
-
-*Checked command status*
-
-*Viewed code item*
-
-*User accepted the command `git checkout app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt`*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2`*
-
-*Checked command status*
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2`*
-
-*Checked command status*
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2`*
-
-*Checked command status*
-
-*Viewed code item*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-### User Input
-
-did you fix the issue or what
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2`*
-
-*Checked command status*
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Viewed code item*
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-### User Input
-
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':app:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 26s
-95 actionable tasks: 2 executed, 93 up-to-date
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> .\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2
-
-> .\gradlew.bat : e:
-file:///C:/Users/david/.gemini/antigravity/scratch/ip
-
-tv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation
- .kt:323:17 No value passed for parameter 'onNavigate'.
-> + CategoryInfo : NotSpecified: (e: file:///C:/U...r
-'onNav
- igate'.:String) [], RemoteException
- + FullyQualifiedErrorId : NativeCommandError
-> FAILURE: Build failed with an exception.
-
- * What went wrong:
-
-
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> .\gradlew.bat assembleDebug --no-daemon
-To honour the JVM settings for this build a single-use Daemon process will be forked. For more on this, please refer to https://docs.gradle.org/8.9/userguide/gradle_daemon.html#sec:disabling_the_daemon in the Gradle documentation.
-Daemon will be stopped at the end of the build
-
-> Task :app:compileDebugKotlin FAILED
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:323:17 No value passed for parameter 'onNavigate'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:344:17 No parameter with name 'onNavigate' found.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:344:32 Cannot infer type for this parameter. Please specify it explicitly.
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':app:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 42s
-95 actionable tasks: 2 executed, 93 up-to-date
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> .\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2
-
-> .\gradlew.bat : e:
-file:///C:/Users/david/.gemini/antigravity/scratch/ip
-
-tv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation
- .kt:323:17 No value passed for parameter 'onNavigate'.
-> + CategoryInfo : NotSpecified: (e: file:///C:/U...r
-'onNav
- igate'.:String) [], RemoteException
- + FullyQualifiedErrorId : NativeCommandError
-> e:
-file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/sr
- c/main/java/com/streamvault/app/navigation/AppNavigation.kt:344:17 No
- parameter with name 'onNavigate' found.
-> e:
-file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/sr
- c/main/java/com/streamvault/app/navigation/AppNavigation.kt:344:32
- Cannot infer type for this parameter. Please specify it explicitly.
-> FAILURE: Build failed with an exception.
-
- * What went wrong:
-
-
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\davidPS C:\Users\david\.gemini\antigravity\scratch\iptv-player> .\gradlew.bat assembleDebug --no-daemon
-To honour the JVM settings for this build a single-use Daemon process will be forked. For more on this, please refer to https://docs.gradle.org/8.9/userguide/gradle_daemon.html#sec:disabling_the_daemon in the Gradle documentation.
-Daemon will be stopped at the end of the build
-
-> Task :app:compileDebugKotlin FAILED
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:323:17 No value passed for parameter 'onNavigate'.
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':app:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 46s
-95 actionable tasks: 2 executed, 93 up-to-date
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> .\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> Get-Content build_errors.txt | Select-String -Pattern "e: " -Context 0,2
-
-> .\gradlew.bat : e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-p
- layer/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:323:
- 17 No value passed for parameter 'onNavigate'.
-> + CategoryInfo : NotSpecified: (e: file:///C:/U...r
- 'onNavigate' .:String) [], RemoteException
- + FullyQualifiedErrorId : NativeCommandError
-> FAILURE: Build failed with an exception.
-
- * What went wrong:
-
-
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> ^C
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> .\gradlew.bat assembleDebug --no-daemon
-To honour the JVM settings for this build a single-use Daemon process will be forked. For more on this, please refer to https://docs.gradle.org/8.9/userguide/gradle_daemon.html#sec:disabling_the_daemon in the Gradle documentation.
-Daemon will be stopped at the end of the build
-
-> Task :app:compileDebugKotlin FAILED
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt:137:35 Unresolved reference 'multiView'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:965:39 Unresolved reference 'multiView'.
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':app:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 47s
-95 actionable tasks: 2 executed, 93 up-to-date
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player>
-
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*User accepted the command `git log -p -n 5 app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt`*
-
-*Checked command status*
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Viewed [PlayerScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Grep searched codebase*
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Searched filesystem*
-
-*Viewed code item*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*Checked command status*
-
-*Checked command status*
-
-*Checked command status*
-
-*Listed resources from default_api*
-
-### Planner Response
-
-I have implemented a fix for the unexpected app exits during D-pad navigation and resolved the build errors.
-
-### The Fix
-The issue was likely caused by horizontal D-pad events (Right/Left) reaching the edges of the UI and "bubbling up" unhandled to the root of the application, where they were being misinterpreted as system navigation events, causing the app to exit.
-
-I added a **Root Focus Trap** in [AppNavigation.kt](cci:7://file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:0:0-0:0):
-* It intercepts and "consumes" any horizontal D-pad events that aren't handled by the UI components.
-* This prevents the events from "leaking" out to the Android OS and triggering an unintended exit.
-
-### Build Error Resolution
-I also fixed several compilation errors that were introduced or exposed:
-* **Restored Routes:** Re-added the missing [multiView](cci:1://file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:62:4-62:32) route and constants that were accidentally removed.
-* **Fixed [PlayerScreen](cci:1://file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:62:0-973:1) Parameters:** Corrected the missing `onNavigate` argument in the navigation host.
-* **Missing Imports:** Added the necessary Jetpack Compose imports for key event handling and D-pad constants.
-
-The application has been successfully built (`assembleDebug` passed). You should now be able to navigate horizontally at the edges of the lists without the app closing.
-
-Please let me know if it's working as expected on your end!
-
-### User Input
-
-bruh navigation doesnt work anymore did you just ruin the entire thing?
-
-*User accepted the command `git checkout app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt`*
-
-*Viewed [MainActivity.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/MainActivity.kt) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Edited relevant file*
-
-*Viewed [libs.versions.toml](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/gradle/libs.versions.toml) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Edited relevant file*
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-### Planner Response
-
-I've found a much better way to fix the "exit on horizontal navigation" issue that doesn't break the D-pad navigation.
-
-### What went wrong
-The previous root-level `Box` trap was too aggressive and was consuming all Left/Right events before the focus system could use them to move between items. This is why navigation stopped working.
-
-### The New Solution
-1. **Fixed Navigation:** I reverted the [AppNavigation.kt](cci:7://file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:0:0-0:0) changes and restored the original flow.
-2. **Window Boundary Trap:** I added a [dispatchKeyEvent](cci:1://file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/MainActivity.kt:73:4-87:5) override in [MainActivity.kt](cci:7://file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/MainActivity.kt:0:0-0:0).
- * It first allows the application (and its focus system) to handle the D-pad event.
- * **Only if the event remains unhandled** (meaning focus has reached the edge and has nowhere to go), it "traps" the event at the window boundary.
- * This prevents the event from leaking to the OS, which was causing the app to close.
-3. **Integrated Build Fixes:** I've kept the fixes for the [multiView](cci:1://file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt:55:4-55:32) route and [PlayerScreen](cci:1://file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:62:0-973:1) parameters so the app builds correctly.
-
-Everything is now built successfully (`assembleDebug` passed). Horizontal navigation should work normally within your lists, but reaching the edge will no longer cause the app to exit.
-
-Please give it a try now!
-
-### User Input
-
-create a new branch we need to work on this navigation issue,
-so you fixed the navigation but i still exit on left or right pad at some points its these points where its not sure or something just loaded up or dissapeared and i do left or right and it just exists
-
-*User accepted the command `git checkout -b fix/navigation-exit`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Viewed [PlayerScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt) *
-
-*Edited relevant file*
-
-### User Input
-
-
-
-*Viewed code item*
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-### User Input
-
-
-
-*Edited relevant file*
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*Grep searched codebase*
-
-*Edited relevant file*
-
-*Viewed [PlayerScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt) *
-
-*Edited relevant file*
-
-*Grep searched codebase*
-
-*Viewed [MoviesScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt) *
-
-*Viewed [SeriesScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt | Select-Object -Last 100`*
-
-*Checked command status*
-
-*Grep searched codebase*
-
-*User accepted the command `Get-Content build_errors.txt | Select-String -Pattern "error:" -Context 0,5`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*User accepted the command `powershell -Command "Get-Content build_errors.txt | Set-Content -Encoding utf8 build_errors_utf8.txt"`*
-
-*Checked command status*
-
-*Viewed [build_errors_utf8.txt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/build_errors_utf8.txt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*Viewed [PlayerScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat assembleDebug > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `powershell -Command "Get-Content build_errors.txt | Set-Content -Encoding utf8 build_errors_utf8.txt"`*
-
-*Checked command status*
-
-*Viewed [build_errors_utf8.txt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/build_errors_utf8.txt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Viewed [PlayerScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt) *
-
-*Viewed [PlayerScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*Viewed [walkthrough.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/walkthrough.md) *
-
-*Edited relevant file*
-
-### User Input
-
-two questions
-first this D pad issue was across the app not only in a certain place. so is it fixed all over?
-and can you create an apk please
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Searched filesystem*
-
-*Checked command status*
-
-*User accepted the command `dir "app\build\outputs\apk\debug\app-debug.apk"`*
-
-*Checked command status*
-
-### User Input
-
-okay but now i cant navigate for example
-if im on a category i cant go right to the channels...
-
-*Edited relevant file*
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*Viewed [MainActivity.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/MainActivity.kt) *
-
-*Edited relevant file*
-
-*Viewed [SeriesScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt) *
-
-*Edited relevant file*
-
-*Viewed [MoviesScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt) *
-
-*Edited relevant file*
-
-*Viewed [PlayerScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-### User Input
-
-okay perfect merge to master we have few things we need to fix
-so create new branch after that and call it simple bugs improvement
-first is in vod search it creates this weird keyboard not the usual android keyboard need to remove that.
-and when entering first to the app and favorites is empty it shows as if its loading them infintly
-like in the image you see the gray rectangles
-
-*User accepted the command `git checkout -b fix/simple-bugs-improvement`*
-
-*Edited relevant file*
-
-*Grep searched codebase*
-
-*Checked command status*
-
-*Grep searched codebase*
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*Viewed [MoviesScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt) *
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Viewed [HomeScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt) *
-
-*Viewed [MoviesScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt) *
-
-*Viewed [HomeViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt) *
-
-*Viewed [HomeViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt) *
-
-*Grep searched codebase*
-
-*Viewed [MoviesScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt) *
-
-*Grep searched codebase*
-
-*Edited relevant file*
-
-*Viewed [SearchScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-### User Input
-
-
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*Viewed [walkthrough.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/walkthrough.md) *
-
-*Edited relevant file*
-
-### User Input
-
-okay works onto next issue, in all channels there is a crackling sounds when they talk the audio is bad
-
-*User accepted the command `git checkout -b fix/audio-crackling`*
-
-*Grep searched codebase*
-
-*Edited relevant file*
-
-*Searched filesystem*
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Viewed [Media3PlayerEngine.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt) *
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Edited relevant file*
-
-### User Input
-
-
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-### User Input
-
-still getting crackling sounds
-
-*Edited relevant file*
-
-*Viewed [Media3PlayerEngine.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt) *
-
-*Edited relevant file*
-
-### User Input
-
-
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-### User Input
-
-okay we need to fix the d pad error that we had its not fixed...
-see the logs maybe they oculd help
-026-03-06 15:46:06.486 355-9611 Codec2-types [email protected] E Invalid C2FrameData::buffers[0].
-2026-03-06 15:46:06.486 355-9611 Codec2-types [email protected] E Invalid C2Work::input.
-2026-03-06 15:46:06.486 355-9611 Codec2-Component [email protected] E Component::Listener::onWorkDone_nb -- received corrupted work items.
-2026-03-06 15:46:06.523 608-763 libprocessgroup system_server I Successfully killed process cgroup uid 10142 pid 9526 in 0ms
-2026-03-06 15:46:06.523 395-395 ResourceManagerMetrics mediaserver I pushConcurrentUsageReport: Concurrent Codec Usage Report for the Process[pid(9526): uid(10142)] is Peak { AudioDec[ SW: 1 ] VideoDec[ SW: 1 ] HW: 1 ] } Peak Pixels: 230400
-2026-03-06 15:46:06.524 395-1045 mediaserver mediaserver E unlinkToDeath: removed reference to death recipient but unlink failed: DEAD_OBJECT
-2026-03-06 15:46:06.524 395-1045 IPCThreadState mediaserver E attemptIncStrongHandle(2): Not supported
-2026-03-06 15:46:06.524 608-750 DisplayManagerService system_server D Drop pending events for gone uid 10142
-2026-03-06 15:46:06.524 355-9097 GoldfishComponentStore [email protected] I in ~ComponentModule
-2026-03-06 15:46:06.524 355-9097 GoldfishComponentStore [email protected] I unloading dll
-2026-03-06 15:46:06.525 395-494 mediaserver mediaserver E unlinkToDeath: removed reference to death recipient but unlink failed: DEAD_OBJECT
-2026-03-06 15:46:06.525 395-494 IPCThreadState mediaserver E attemptIncStrongHandle(3): Not supported
-2026-03-06 15:46:06.534 608-795 ProcessStats system_server W Tracking association SourceState{c2b5b12 com.google.android.tvlauncher/10078 BTop #4964} whose proc state 2 is better than process ProcessState{b93e6 com.google.android.gms.persistent/10084 pkg=com.google.android.gms} proc state 3 (1 skipped)
-2026-03-06 15:46:06.537 374-374 BpBinder surfaceflinger I onLastStrongRef automatically unlinking death recipients:
-2026-03-06 15:46:06.544 7034-7034 Clearcut-EventLogger com.google.android.tvlauncher E Unexpected log parameter notification_indicator_total
-2026-03-06 15:46:06.546 7034-7034 A2F com.google.android.tvlauncher W App Foreground
-2026-03-06 15:46:06.546 7034-7034 A2F com.google.android.tvlauncher W Data Refresh start
-2026-03-06 15:46:06.546 7034-7067 A2F com.google.android.tvlauncher W Attempting CleanUp
-2026-03-06 15:46:06.551 7034-7034 P2F com.google.android.tvlauncher W Visible APPS_TAB
-2026-03-06 15:46:06.557 6895-6925 katniss_in...anagerImpl com.google.android.katniss I Read invalid search account from PDS
-2026-03-06 15:46:06.559 608-824 InputDispatcher system_server W Waiting because no window has focus but ActivityRecord{d6948f3 u0 com.google.android.tvlauncher/.MainActivity t285} may eventually add a window when it finishes starting up. Will wait for 5000ms
-2026-03-06 15:46:06.603 371-518 audioserver audioserver D FGS Logger Transaction failed
-2026-03-06 15:46:06.603 371-518 audioserver audioserver D -129
-2026-03-06 15:46:06.618 371-518 audioserver audioserver D FGS Logger Transaction failed
-2026-03-06 15:46:06.618 371-518 audioserver audioserver D -129
-2026-03-06 15:46:06.952 608-752 ActivityTaskManager system_server W Activity top resumed state loss timeout for ActivityRecord{b7803c1 u0 com.streamvault.app/.MainActivity t296 f} isExiting}
-2026-03-06 15:46:07.214 7034-7069 OpenGLRenderer com.google.android.tvlauncher E Unable to match the desired swap behavior.
-2026-03-06 15:46:07.257 7034-7034 Choreographer com.google.android.tvlauncher I Skipped 41 frames! The application may be doing too much work on its main thread.
-2026-03-06 15:46:07.259 608-749 WindowManager system_server V Sent Transition #47 createdAt=03-06 13:46:06.451 via request=TransitionRequestInfo { type = CLOSE, triggerTask = null, remoteTransition = null, displayChange = null }
-2026-03-06 15:46:07.260 930-1046 WindowManagerShell com.android.systemui V onTransitionReady android.os.BinderProxy@5831470: {id=47 t=CLOSE f=0x10 trk=0 r=[0@Point(0, 0)] c=[{WCT{android.window.IWindowContainerToken$Stub$Proxy@5dd079c} m=TO_FRONT f=MOVE_TO_TOP leash=Surface(name=Task=1)/@0x7aa03e9 sb=Rect(0, 0 - 1920, 1080) eb=Rect(0, 0 - 1920, 1080) d=0},{WCT{android.window.IWindowContainerToken$Stub$Proxy@615f5a5} m=CLOSE f=NONE leash=Surface(name=Task=296)/@0xfcad86e sb=Rect(0, 0 - 1920, 1080) eb=Rect(0, 0 - 1920, 1080) d=0}]}
-2026-03-06 15:46:07.261 930-1046 WindowManagerShell com.android.systemui V Playing animation for (#47)android.os.BinderProxy@5831470@0
-2026-03-06 15:46:07.261 930-1046 WindowManagerShell com.android.systemui V try handler com.android.wm.shell.keyguard.KeyguardTransitionHandler@4cd6809
-2026-03-06 15:46:07.261 930-1046 WindowManagerShell com.android.systemui V try handler com.android.wm.shell.activityembedding.ActivityEmbeddingController@11e3a0e
-2026-03-06 15:46:07.261 930-1046 WindowManagerShell com.android.systemui V try handler com.android.wm.shell.pip.tv.TvPipTransition@4632c2f
-2026-03-06 15:46:07.261 930-1046 WindowManagerShell com.android.systemui V try handler com.android.wm.shell.transition.RemoteTransitionHandler@10a523c
-2026-03-06 15:46:07.261 930-1046 WindowManagerShell com.android.systemui V Transition doesn't have explicit remote, search filters for match for {id=47 t=CLOSE f=0x10 trk=0 r=[0@Point(0, 0)] c=[{WCT{android.window.IWindowContainerToken$Stub$Proxy@5dd079c} m=TO_FRONT f=MOVE_TO_TOP leash=Surface(name=Task=1)/@0x7aa03e9 sb=Rect(0, 0 - 1920, 1080) eb=Rect(0, 0 - 1920, 1080) d=0},{WCT{android.window.IWindowContainerToken$Stub$Proxy@615f5a5} m=CLOSE f=NONE leash=Surface(name=Task=296)/@0xfcad86e sb=Rect(0, 0 - 1920, 1080) eb=Rect(0, 0 - 1920, 1080) d=0}]}
-2026-03-06 15:46:07.261 930-1046 WindowManagerShell com.android.systemui V Delegate animation for #47 to null
-2026-03-06 15:46:07.262 930-1046 WindowManagerShell com.android.systemui V try handler com.android.wm.shell.transition.DefaultTransitionHandler@cdb7bc5
-2026-03-06 15:46:07.262 930-1046 WindowManagerShell com.android.systemui V start default transition animation, info = {id=47 t=CLOSE f=0x10 trk=0 r=[0@Point(0, 0)] c=[{WCT{android.window.IWindowContainerToken$Stub$Proxy@5dd079c} m=TO_FRONT f=MOVE_TO_TOP leash=Surface(name=Task=1)/@0x7aa03e9 sb=Rect(0, 0 - 1920, 1080) eb=Rect(0, 0 - 1920, 1080) d=0},{WCT{android.window.IWindowContainerToken$Stub$Proxy@615f5a5} m=CLOSE f=NONE leash=Surface(name=Task=296)/@0xfcad86e sb=Rect(0, 0 - 1920, 1080) eb=Rect(0, 0 - 1920, 1080) d=0}]}
-2026-03-06 15:46:07.262 930-1046 WindowManagerShell com.android.systemui V loadAnimation: anim=android.view.animation.AlphaAnimation@ad00d7a animAttr=0xb type=CLOSE isEntrance=false
-2026-03-06 15:46:07.262 930-1046 WindowManagerShell com.android.systemui V loadAnimation: anim=android.view.animation.AlphaAnimation@50d192b animAttr=0xa type=CLOSE isEntrance=true
-2026-03-06 15:46:07.262 608-749 WindowManager system_server V startWCT=WindowContainerTransaction { changes = {} hops = [] errorCallbackToken=null taskFragmentOrganizer=null }
-2026-03-06 15:46:07.263 608-749 WindowManager system_server V info={id=47 t=CLOSE f=0x10 trk=0 r=[0@Point(0, 0)] c=[{WCT{RemoteToken{f264712 Task{9b90e5b #1 type=home}}} m=TO_FRONT f=MOVE_TO_TOP leash=Surface(name=Task=1)/@0xe997732 sb=Rect(0, 0 - 1920, 1080) eb=Rect(0, 0 - 1920, 1080) d=0},{WCT{RemoteToken{279aefa Task{b849766 #296 type=standard A=10142:com.streamvault.app}}} m=CLOSE f=NONE leash=Surface(name=Task=296)/@0xa85668f sb=Rect(0, 0 - 1920, 1080) eb=Rect(0, 0 - 1920, 1080) d=0}]}
-2026-03-06 15:46:07.265 930-1046 WindowManagerShell com.android.systemui V animated by com.android.wm.shell.transition.DefaultTransitionHandler@cdb7bc5
-2026-03-06 15:46:07.275 608-739 ImeTracker system_server I com.google.android.tvlauncher:4d3afa05: onRequestHide at ORIGIN_SERVER_HIDE_INPUT reason HIDE_UNSPECIFIED_WINDOW
-2026-03-06 15:46:07.275 608-739 ImeTracker system_server I com.google.android.tvlauncher:4d3afa05: onCancelled at PHASE_SERVER_SHOULD_HIDE
-2026-03-06 15:46:07.277 1590-1590 GoogleInpu...hodService com...gle.android.inputmethod.latin I GoogleInputMethodService.onFinishInput():2084
-2026-03-06 15:46:07.278 1590-1590 Module com...gle.android.inputmethod.latin I DeviceLockedStatusModuleProvider$Module.updateDeviceLockedStatus():101 repeatCheckTimes = 0, locked = false
-2026-03-06 15:46:07.278 1590-1590 GoogleInpu...hodService com...gle.android.inputmethod.latin I GoogleInputMethodService.onStartInput():1345 onStartInput(EditorInfo{EditorInfo{packageName=com.google.android.tvlauncher, inputType=0, inputTypeString=NULL, enableLearning=false, autoCorrection=false, autoComplete=false, imeOptions=0, privateImeOptions=null, actionName=UNSPECIFIED, actionLabel=null, initialSelStart=-1, initialSelEnd=-1, initialCapsMode=0, label=null, fieldId=0, fieldName=null, extras=null, hintText=null, hintLocales=[]}}, false)
-2026-03-06 15:46:07.280 608-753 WindowManager system_server W Failed to deliver inset control state change to w=Window{6247184 u0 com.streamvault.app/com.streamvault.app.MainActivity EXITING}
- android.os.DeadObjectException
- at android.os.BinderProxy.transactNative(Native Method)
- at android.os.BinderProxy.transact(BinderProxy.java:584)
- at android.view.IWindow$Stub$Proxy.insetsControlChanged(IWindow.java:479)
- at com.android.server.wm.WindowState.notifyInsetsControlChanged(WindowState.java:3802)
- at com.android.server.wm.InsetsStateController.lambda$notifyPendingInsetsControlChanged$3(InsetsStateController.java:343)
- at com.android.server.wm.InsetsStateController.$r8$lambda$8yykPRG1GyNq_J17QvL9d5xANMc(InsetsStateController.java:0)
- at com.android.server.wm.InsetsStateController$$ExternalSyntheticLambda2.run(R8$$SyntheticClass:0)
- at com.android.server.wm.WindowAnimator.executeAfterPrepareSurfacesRunnables(WindowAnimator.java:294)
- at com.android.server.wm.RootWindowContainer.performSurfacePlacementNoTrace(RootWindowContainer.java:811)
- at com.android.server.wm.RootWindowContainer.performSurfacePlacement(RootWindowContainer.java:756)
- at com.android.server.wm.WindowSurfacePlacer.performSurfacePlacementLoop(WindowSurfacePlacer.java:177)
- at com.android.server.wm.WindowSurfacePlacer.performSurfacePlacement(WindowSurfacePlacer.java:126)
- at com.android.server.wm.WindowSurfacePlacer.performSurfacePlacement(WindowSurfacePlacer.java:115)
- at com.android.server.wm.WindowSurfacePlacer$Traverser.run(WindowSurfacePlacer.java:57)
- at android.os.Handler.handleCallback(Handler.java:958)
- at android.os.Handler.dispatchMessage(Handler.java:99)
- at android.os.Looper.loopOnce(Looper.java:205)
- at android.os.Looper.loop(Looper.java:294)
- at android.os.HandlerThread.run(HandlerThread.java:67)
- at com.android.server.ServiceThread.run(ServiceThread.java:46)
-2026-03-06 15:46:07.284 608-3615 PackageConfigPersister system_server W App-specific configuration not found for packageName: com.google.android.tvlauncher and userId: 0
-2026-03-06 15:46:07.284 7034-7213 OpenGLRenderer com.google.android.tvlauncher I Davey! duration=702ms; Flags=1, FrameTimelineVsyncId=409807, IntendedVsync=7747536764426, Vsync=7747536764426, InputEventId=785841564, HandleInputStart=7747551724576, AnimationStart=7747551725929, PerformTraversalsStart=7747551726596, DrawStart=7748215089127, FrameDeadline=7747553431092, FrameInterval=7747551718270, FrameStartTime=16666666, SyncQueued=7748215488456, SyncStart=7748231113047, IssueDrawCommandsStart=7748231287391, SwapBuffers=7748243305500, FrameCompleted=7748254918326, DequeueBufferDuration=3546, QueueBufferDuration=151095, GpuCompleted=7748254918326, SwapBuffersCompleted=7748253184573, DisplayPresentTime=0, CommandSubmissionCompleted=7748243305500,
-2026-03-06 15:46:07.285 1590-1590 Module com...gle.android.inputmethod.latin I DeviceLockedStatusModuleProvider$Module.updateDeviceLockedStatus():101 repeatCheckTimes = 1, locked = false
-2026-03-06 15:46:07.672 930-1046 WindowManagerShell com.android.systemui V Transition animation finished (aborted=false), notifying core (#47)android.os.BinderProxy@5831470@0
-2026-03-06 15:46:07.674 608-749 WindowManager system_server V Finish Transition #47: created at 03-06 13:46:06.451 collect-started=0.03ms request-sent=0.056ms started=6.039ms ready=78.258ms sent=807.787ms finished=1222.786ms
-2026-03-06 15:46:07.680 608-9624 WindowManager system_server W Exception thrown during dispatchAppVisibility Window{6247184 u0 com.streamvault.app/com.streamvault.app.MainActivity EXITING}
- android.os.DeadObjectException
- at android.os.BinderProxy.transactNative(Native Method)
- at android.os.BinderProxy.transact(BinderProxy.java:584)
- at android.view.IWindow$Stub$Proxy.dispatchAppVisibility(IWindow.java:546)
- at com.android.server.wm.WindowState.sendAppVisibilityToClients(WindowState.java:3271)
- at com.android.server.wm.WindowContainer.sendAppVisibilityToClients(WindowContainer.java:1221)
- at com.android.server.wm.WindowToken.setClientVisible(WindowToken.java:409)
- at com.android.server.wm.ActivityRecord.setClientVisible(ActivityRecord.java:6946)
- at com.android.server.wm.ActivityRecord.postApplyAnimation(ActivityRecord.java:5637)
- at com.android.server.wm.ActivityRecord.commitVisibility(ActivityRecord.java:5580)
- at com.android.server.wm.Transition.finishTransition(Transition.java:1151)
- at com.android.server.wm.TransitionController.finishTransition(TransitionController.java:868)
- at com.android.server.wm.WindowOrganizerController.finishTransition(WindowOrganizerController.java:396)
- at android.window.IWindowOrganizerController$Stub.onTransact(IWindowOrganizerController.java:286)
- at com.android.server.wm.WindowOrganizerController.onTransact(WindowOrganizerController.java:181)
- at android.os.Binder.execTransactInternal(Binder.java:1339)
- at android.os.Binder.execTransact(Binder.java:1275)
-2026-03-06 15:46:07.680 608-9624 Process system_server I Sending signal. PID: 9526 SIG: 9
-2026-03-06 15:46:07.683 608-752 ActivityManager system_server W setHasOverlayUi called on unknown pid: 9526
-2026-03-06 15:46:07.687 930-1046 WindowManagerShell com.android.systemui V Track 0 became idle
-2026-03-06 15:46:07.687 930-1046 WindowManagerShell com.android.systemui V All active transition animations finished
-2026-03-06 15:46:07.690 608-752 DisplayDeviceRepository system_server I Display device changed: DisplayDeviceInfo{"Built-in Screen": uniqueId="local:4619827259835644672", 1920 x 1080, modeId 1, renderFrameRate 60.000004, defaultModeId 1, supportedModes [{id=1, width=1920, height=1080, fps=60.000004, alternativeRefreshRates=[], supportedHdrTypes=[]}], colorMode 0, supportedColorModes [0], hdrCapabilities HdrCapabilities{mSupportedHdrTypes=[], mMaxLuminance=500.0, mMaxAverageLuminance=500.0, mMinLuminance=0.0}, allmSupported false, gameContentTypeSupported false, density 320, 320.0 x 320.0 dpi, appVsyncOff 1000000, presDeadline 16666666, touch INTERNAL, rotation 0, type INTERNAL, address {port=0, model=0x401cec6a7a2b7b}, deviceProductInfo DeviceProductInfo{name=EMU_display_0, manufacturerPnpId=GGL, productId=1, modelYear=null, manufactureDate=ManufactureDate{week=27, year=2006}, connectionToSinkType=0}, state ON, committedState ON, frameRateOverride , brightnessMinimum 0.0, brightnessMaximum 1.0, brightnessDefault 0.39763778, hdrSdrRatio NaN, FLAG_ALLOWED_TO_BE_DEFAULT_DISPLAY, FLAG_ROTATES_WITH_CONTENT, FLAG_SECURE, FLAG_SUPPORTS_PROTECTED_BUFFERS, FLAG_TRUSTED, installOrientation 0, displayShape DisplayShape{ spec=729782573 displayWidth=1920 displayHeight=1080 physicalPixelDisplaySizeRatio=1.0 rotation=0 offsetX=0 offsetY=0 scale=1.0}}
-2026-03-06 15:46:07.704 374-374 BpTransact...edListener surfaceflinger E Failed to transact (-32)
-2026-03-06 15:46:07.704 374-374 BpTransact...edListener surfaceflinger E Failed to transact (-32)
-2026-03-06 15:46:09.473 348-3680 android.ha...mpl.ranchu android.hardware.audio.service D threadLoop: entering standby, frames: 11008384
-2026-03-06 15:46:10.691 608-1484 TaskPersister system_server E File error accessing recents directory (directory doesn't exist?).
-2026-03-06 15:46:12.022 399-1011 BufferPoolAccessor2.0 media.swcodec D evictor expired: 1, evicted: 0
-2026-03-06 15:46:21.945 608-905 ClipboardService system_server E Denying clipboard access to com.alphainventor.filemanager, application is not in focus nor is it a system service for user 0
-2026-03-06 15:46:21.957 608-905 ClipboardService system_server E Denying clipboard access to com.alphainventor.filemanager, application is not in focus nor is it a system service for user 0
-2026-03-06 15:46:22.049 608-3615 ProcessStats system_server W Tracking association SourceState{c2b5b12 com.google.android.tvlauncher/10078 BTop #4983} whose proc state 2 is better than process ProcessState{b93e6 com.google.android.gms.persistent/10084 pkg=com.google.android.gms} proc state 3 (71 skipped)
-2026-03-06 15:46:39.614 2398-2398 cast_shell com.google.android.apps.mediashell I [0306/134639.614545:INFO:service_base.h(78)] Size of the map for type AuthTokenResponse is 0
-2026-03-06 15:46:39.949 2398-2398 cast_shell com.google.android.apps.mediashell I [0306/134639.949702:INFO:service_base.h(246)] Container sizes for type CloudSetting are (session_info_map: 0), (topic_info_map: 21), (pending_events: 0).
-2026-03-06 15:46:40.666 2398-2398 cast_shell com.google.android.apps.mediashell I [0306/134640.666329:INFO:metrics_stat_logger.cc(38)] Metrics stat for the past 60 secs : total=2
- [metrics_stat_logger] Cast.Discovery.Mdns.Request.In=4
- [metrics_stat_logger] Cast.Discovery.Mdns.Response.Out=4
-2026-03-06 15:46:42.122 2398-2854 cast_shell com.google.android.apps.mediashell I [0306/134642.122630:INFO:mdns_app_filter.cc(3550)] Mdns cast queries recently sent: queries=2
-2026-03-06 15:46:43.895 2398-2860 cast_Clien...ovisioning com.google.android.apps.mediashell I Loading factory credentials for 1P device.
-
-*User accepted the command `git checkout -b fix/d-pad-exit`*
-
-*Edited relevant file*
-
-*Grep searched codebase*
-
-*Checked command status*
-
-*Viewed [PlayerScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt) *
-
-*Viewed [MainActivity.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/MainActivity.kt) *
-
-*Viewed [SettingsScreen.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt) *
-
-*Grep searched codebase*
-
-*Viewed [TopNavBar.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt) *
-
-*Viewed [task.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/task.md) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Viewed [AppNavigation.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt) *
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Viewed [Media3PlayerEngine.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt) *
-
-*Edited relevant file*
-
-### User Input
-
-
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Edited relevant file*
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Viewed [task.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/task.md) *
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat assembleDebug --no-daemon`*
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Checked command status*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [task.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/task.md) *
-
-### User Input
-
-okay it seems to be working i have more things for you
-lets start with merging with master and creating a new branch
-so my first thing is, i heard that iptv m3u files have these attributes
-
-# Core IPTV Attributes (most important)
-
-### 1. `tvg-id`
-
-Unique ID used to match EPG.
-
-```
-tvg-id="bbc1.uk"
-```
-
----
-
-### 2. `tvg-name`
-
-Channel name for EPG matching.
-
-```
-tvg-name="BBC One"
-```
-
----
-
-### 3. `tvg-logo`
-
-URL to channel logo.
-
-```
-tvg-logo="https://logo.png"
-```
-
----
-
-### 4. `group-title`
-
-Category or group.
-
-```
-group-title="Sports"
-```
-
-Used for UI grouping.
-
----
-
-### 5. `tvg-chno`
-
-Channel number.
-
-```
-tvg-chno="101"
-```
-
-Allows remote navigation.
-
----
-
-### 6. `tvg-language`
-
-Channel language.
-
-```
-tvg-language="en"
-```
-
----
-
-### 7. `tvg-country`
-
-Country of the channel.
-
-```
-tvg-country="US"
-```
-
----
-
-### 8. `tvg-url`
-
-EPG URL for this playlist.
-
-Usually in header:
-
-```
-#EXTM3U tvg-url="http://epg.xml"
-```
-
----
-
-# Stream Control Attributes
-
-### 9. `http-user-agent`
-
-Custom user agent.
-
-```
-http-user-agent="VLC/3.0"
-```
-
-Some providers require this.
-
----
-
-### 10. `http-referrer`
-
-Referrer header.
-
-```
-http-referrer="https://example.com"
-```
-
----
-
-### 11. `user-agent`
-
-Alternative header name.
-
-```
-user-agent="Mozilla/5.0"
-```
-
----
-
-### 12. `cookie`
-
-Authentication cookie.
-
-```
-cookie="session=123"
-```
-
----
-
-### 13. `headers`
-
-Multiple headers.
-
-```
-headers="Authorization:Bearer token"
-```
-
----
-
-# Catch-up / Timeshift (important feature)
-
-Used for **replay TV**.
-
-### 14. `catchup`
-
-Enable catch-up.
-
-```
-catchup="default"
-```
-
----
-
-### 15. `catchup-days`
-
-Days of archive.
-
-```
-catchup-days="7"
-```
-
----
-
-### 16. `catchup-source`
-
-Replay stream template.
-
-```
-catchup-source="http://server/{channel}/{timestamp}"
-```
-
----
-
-### 17. `catchup-correction`
-
-Time offset.
-
-```
-catchup-correction="2.0"
-```
-
----
-
-# VOD / Metadata
-
-### 18. `type`
-
-Channel type.
-
-```
-type="live"
-```
-
-or
-
-```
-type="movie"
-```
-
----
-
-### 19. `vod`
-
-Marks Video On Demand.
-
-```
-vod="true"
-```
-
----
-
-### 20. `year`
-
-Movie release year.
-
-```
-year="2022"
-```
-
----
-
-### 21. `genre`
-
-Movie genre.
-
-```
-genre="Action"
-```
-
----
-
-### 22. `rating`
-
-Content rating.
-
-```
-rating="8.3"
-```
-
----
-
-### 23. `duration`
-
-Stream duration.
-
-```
-duration="5400"
-```
-
----
-
-# UI / Player Display
-
-### 24. `radio`
-
-Marks radio channel.
-
-```
-radio="true"
-```
-
----
-
-### 25. `audio-track`
-
-Audio language.
-
-```
-audio-track="eng"
-```
-
----
-
-### 26. `aspect-ratio`
-
-Video aspect ratio.
-
-```
-aspect-ratio="16:9"
-```
-
----
-
-### 27. `resolution`
-
-Video resolution.
-
-```
-resolution="1920x1080"
-```
-
----
-
-# Provider / System Fields
-
-### 28. `provider`
-
-Provider name.
-
-```
-provider="MyIPTV"
-```
-
----
-
-### 29. `provider-type`
-
-Provider category.
-
-```
-provider-type="iptv"
-```
-
----
-
-### 30. `license-key`
-
-DRM license.
-
-```
-license-key="abc123"
-```
-
----
-
-### 31. `drm`
-
-DRM type.
-
-```
-drm="widevine"
-```
-
----
-
-# Advanced / Rare Attributes
-
-### 32. `timeshift`
-
-Shift playback time.
-
-```
-timeshift="2"
-```
-
----
-
-### 33. `channel-id`
-
-Alternative channel identifier.
-
-```
-channel-id="cnn.us"
-```
-
----
-
-### 34. `channel-number`
-
-Alternative numbering.
-
-```
-channel-number="101"
-```
-
----
-
-### 35. `logo-position`
-
-UI placement hint.
-
-```
-logo-position="left"
-```
-
-Rarely used.
-
----
-
-# Example with many attributes
-
-```
-#EXTINF:-1 tvg-id="BBC1.uk"
-tvg-name="BBC One"
-tvg-logo="https://logo.png"
-tvg-chno="101"
-group-title="UK"
-tvg-country="UK"
-tvg-language="en"
-catchup="default"
-catchup-days="7",BBC One
-http://stream-url
-```
-and xtream channels has these:
-Main endpoints:
-
-```
-get_live_streams
-get_vod_streams
-get_series
-get_live_categories
-get_vod_categories
-get_series_categories
-get_short_epg
-get_simple_data_table
-```
-
-Each response returns **JSON objects with attributes**.
-
-Below is the **complete set of commonly used Xtream metadata fields** used by IPTV players.
-
----
-
-# 1. Core Stream Attributes (Live TV)
-
-Returned by:
-
-```
-player_api.php?action=get_live_streams
-```
-
-Typical response object:
-
-```json
-{
- "num": 1,
- "name": "CNN HD",
- "stream_type": "live",
- "stream_id": 12345,
- "stream_icon": "https://logo.png",
- "epg_channel_id": "cnn.us",
- "added": "1673200000",
- "category_id": "12",
- "custom_sid": "",
- "tv_archive": 1,
- "direct_source": "",
- "tv_archive_duration": "7"
-}
-```
-
-Full attribute list:
-
-| Attribute | Meaning |
-| --------------------- | ----------------------------- |
-| `num` | index number |
-| `name` | channel name |
-| `stream_type` | live / vod / series |
-| `stream_id` | unique stream id |
-| `stream_icon` | channel logo |
-| `epg_channel_id` | EPG id (equivalent to tvg-id) |
-| `added` | timestamp when added |
-| `category_id` | category reference |
-| `custom_sid` | custom stream id |
-| `tv_archive` | catch-up enabled |
-| `direct_source` | direct stream source |
-| `tv_archive_duration` | catch-up days |
-
----
-
-# 2. Category Attributes
-
-Returned by:
-
-```
-get_live_categories
-get_vod_categories
-get_series_categories
-```
-
-Example:
-
-```json
-{
- "category_id": "12",
- "category_name": "Sports",
- "parent_id": 0
-}
-```
-
-Fields:
-
-| Attribute | Meaning |
-| --------------- | --------------- |
-| `category_id` | unique id |
-| `category_name` | display name |
-| `parent_id` | parent category |
-
----
-
-# 3. VOD Attributes (Movies)
-
-Returned by:
-
-```
-get_vod_streams
-```
-
-Example:
-
-```json
-{
- "num": 1,
- "name": "Interstellar",
- "stream_id": 4455,
- "stream_icon": "poster.jpg",
- "rating": "8.6",
- "rating_5based": 4.3,
- "added": "1673200000",
- "category_id": "10",
- "container_extension": "mp4",
- "direct_source": "",
- "year": "2014"
-}
-```
-
-Attributes:
-
-| Attribute | Meaning |
-| --------------------- | ----------------- |
-| `num` | index |
-| `name` | movie title |
-| `stream_id` | stream id |
-| `stream_icon` | poster |
-| `rating` | rating |
-| `rating_5based` | normalized rating |
-| `added` | timestamp |
-| `category_id` | category |
-| `container_extension` | file type |
-| `direct_source` | direct URL |
-| `year` | release year |
-
----
-
-# 4. Series Attributes
-
-Returned by:
-
-```
-get_series
-```
-
-Example:
-
-```json
-{
- "series_id": 778,
- "name": "Breaking Bad",
- "cover": "cover.jpg",
- "plot": "Chemistry teacher turns to crime",
- "cast": "Bryan Cranston",
- "director": "Vince Gilligan",
- "genre": "Crime",
- "releaseDate": "2008",
- "rating": "9.5",
- "last_modified": "1673000000"
-}
-```
-
-Attributes:
-
-| Attribute | Meaning |
-| --------------- | ---------------- |
-| `series_id` | series id |
-| `name` | series name |
-| `cover` | poster |
-| `plot` | description |
-| `cast` | actors |
-| `director` | director |
-| `genre` | genre |
-| `releaseDate` | release date |
-| `rating` | rating |
-| `last_modified` | update timestamp |
-
----
-
-# 5. Episode Attributes
-
-Returned by:
-
-```
-get_series_info
-```
-
-Example:
-
-```json
-{
- "id": 101,
- "episode_num": 1,
- "title": "Pilot",
- "container_extension": "mp4",
- "info": {
- "duration": "00:55:00",
- "plot": "Episode description"
- }
-}
-```
-
-Fields:
-
-| Attribute | Meaning |
-| --------------------- | -------------- |
-| `id` | episode id |
-| `episode_num` | episode number |
-| `title` | episode title |
-| `container_extension` | format |
-| `duration` | runtime |
-| `plot` | description |
-
----
-
-# 6. EPG Attributes
-
-Returned by:
-
-```
-get_short_epg
-```
-
-Example:
-
-```json
-{
- "id": "cnn.us",
- "title": "World News",
- "start": "2026-03-06 12:00:00",
- "end": "2026-03-06 13:00:00",
- "description": "Latest headlines"
-}
-```
-
-Fields:
-
-| Attribute | Meaning |
-| ------------- | -------------- |
-| `id` | epg channel id |
-| `title` | program title |
-| `start` | start time |
-| `end` | end time |
-| `description` | description |
-
----
-
-# 7. Hidden / Less Documented Attributes
-
-Some Xtream servers expose additional fields used by premium IPTV players.
-
-| Attribute | Meaning |
-| --------------- | ------------------ |
-| `is_adult` | adult channel flag |
-| `pin_protected` | parental lock |
-| `bitrate` | stream bitrate |
-| `fps` | frame rate |
-| `audio` | audio codec |
-| `video` | video codec |
-| `resolution` | stream resolution |
-
-Not all servers expose them.
-
----
-
-# 8. Catch-Up / Timeshift Fields
-
-Xtream uses these:
-
-| Attribute | Meaning |
-| --------------------- | --------------- |
-| `tv_archive` | enable catchup |
-| `tv_archive_duration` | days of archive |
-| `start_timestamp` | replay start |
-| `stop_timestamp` | replay stop |
-
-Players reconstruct replay URLs using these values.
-
----
-
-# 9. Authentication Attributes
-
-Returned by login:
-
-```
-player_api.php
-```
-
-Example:
-
-```json
-{
- "user_info": {
- "username": "user",
- "password": "pass",
- "auth": 1,
- "status": "Active",
- "exp_date": "1700000000",
- "max_connections": 2
- }
-}
-```
-
-Fields:
-
-| Attribute | Meaning |
-| ----------------- | ---------------- |
-| `auth` | login success |
-| `status` | account status |
-| `exp_date` | expiry |
-| `max_connections` | connection limit |
-| `is_trial` | trial account |
-
----
-
-# 10. Stream Playback URL
-
-Live stream URL pattern:
-
-```
-http://server:port/live/username/password/stream_id.ts
-```
-
-VOD stream URL:
-
-```
-http://server:port/movie/username/password/stream_id.mp4
-```
-
-Series stream URL:
-
-```
-http://server:port/series/username/password/episode_id.mp4
-```
-
----
-
-# 11. Mapping to M3U
-
-Xtream fields correspond roughly to M3U attributes:
-
-| Xtream | M3U |
-| --------------------- | ------------ |
-| `epg_channel_id` | tvg-id |
-| `stream_icon` | tvg-logo |
-| `category_id` | group-title |
-| `tv_archive` | catchup |
-| `tv_archive_duration` | catchup-days |
-
----
-
-# 12. Recommended Kotlin Data Model
-
-Example:
-
-```kotlin
-data class XtreamStream(
- val streamId: Int,
- val name: String,
- val streamIcon: String?,
- val categoryId: Int,
- val epgChannelId: String?,
- val tvArchive: Boolean,
- val tvArchiveDuration: Int?
-)
-```
-please make sure all these are supported at least most of them and the important ones!
-for both xtream and m3u files
-
-*User accepted the command `git checkout -b feature/metadata-parsing`*
-
-*Edited relevant file*
-
-*Viewed [M3uParser.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt) *
-
-*Viewed [Channel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Channel.kt) *
-
-*Viewed [Movie.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Movie.kt) *
-
-*Viewed [Series.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Series.kt) *
-
-*Viewed [XtreamProvider.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt) *
-
-*Listed directory [dto](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/remote/dto) *
-
-*Viewed [XtreamDtos.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt) *
-
-*Viewed [StreamInfo.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt) *
-
-*Viewed [Media3PlayerEngine.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt) *
-
-*Viewed [Media3PlayerEngine.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt) *
-
-*Listed directory [local](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local) *
-
-*Listed directory [entity](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity) *
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Edited relevant file*
-
-### User Input
-
-
-
-*Edited relevant file*
-
-*Viewed [StreamVaultDatabase.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt) *
-
-*Edited relevant file*
-
-*Grep searched codebase*
-
-*Viewed [DatabaseModule.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [M3uParser.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt) *
-
-*Viewed [M3uParser.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt) *
-
-*Viewed [task.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/task.md) *
-
-*Edited relevant file*
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Edited relevant file*
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-*Viewed [PlayerViewModel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt) *
-
-### User Input
-
-continue
-
-*Edited relevant file*
-
-*Grep searched codebase*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*Viewed [M3uParser.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt) *
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-### User Input
-
-> Task :data:compileDebugKotlin FAILED
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:172:5 No parameter with name 'userAgent' found.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:173:5 No parameter with name 'headers' found.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:197:17 Unresolved reference 'userAgent'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:198:15 Unresolved reference 'headers'.
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':data:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 34s
-43 actionable tasks: 8 executed, 35 up-to-date
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> .\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player>
-
-*Viewed [Series.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Series.kt) *
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Edited relevant file*
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-### User Input
-
-continue
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-### User Input
-
-you got stuck
-
-*Viewed [Series.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Series.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Viewed [XtreamProvider.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt) *
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*Checked command status*
-
-*Checked command status*
-
-*Checked command status*
-
-*Viewed [Channel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Channel.kt) *
-
-*Viewed [Provider.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Provider.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Edited relevant file*
-
-*Checked command status*
-
-*Viewed [Channel.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Channel.kt) *
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*User accepted the command `.\gradlew.bat :data:compileDebugKotlin --no-daemon`*
-
-*Checked command status*
-
-*Checked command status*
-
-*Viewed [StreamVaultDatabase.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*Viewed [M3uParser.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt) *
-
-*Searched filesystem*
-
-*Viewed [SyncWorker.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt) *
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*Viewed [SyncManager.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/sync/SyncManager.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Edited relevant file*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt -Raw | Select-Object -First 2000`*
-
-*Checked command status*
-
-*Viewed [M3uParser.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-### User Input
-
-
-> Task :data:compileDebugKotlin FAILED
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:98:35 Unresolved reference 'mapIndexed'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:98:48 Cannot infer type for this parameter. Please specify it explicitly.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:98:55 Cannot infer type for this parameter. Please specify it explicitly.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:99:62 Unresolved reference 'extraAttributes'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:103:30 Unresolved reference 'name'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:104:33 Unresolved reference 'tvgLogo'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:105:36 Unresolved reference 'groupTitle'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:106:38 Unresolved reference 'tvgId'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:106:53 Unresolved reference 'tvgName'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:107:32 Unresolved reference 'tvgChno'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:108:35 Unresolved reference 'url'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:109:42 Unresolved reference 'catchUp'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:110:37 Unresolved reference 'catchUpDays'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:111:39 Unresolved reference 'catchUpSource'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:113:76 Unresolved reference 'name'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:114:35 Unresolved reference 'userAgent'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:116:34 Unresolved reference 'language'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:117:33 Unresolved reference 'country'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:124:14 Unresolved reference 'filter'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:124:34 Unresolved reference 'it'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:125:27 Cannot infer type for this parameter. Please specify it explicitly.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:125:34 Cannot infer type for this parameter. Please specify it explicitly.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:126:66 Unresolved reference 'extraAttributes'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:130:34 Unresolved reference 'name'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:131:39 Unresolved reference 'tvgLogo'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:132:42 Unresolved reference 'groupTitle'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:133:39 Unresolved reference 'url'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:135:36 Unresolved reference 'rating'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:136:34 Unresolved reference 'year'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:137:35 Unresolved reference 'genre'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:138:45 Unresolved reference 'durationSeconds'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt:139:39 Unresolved reference 'userAgent'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/sync/SyncManager.kt:228:33 Unresolved reference 'updateEpgUrl'.
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':data:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 8s
-42 actionable tasks: 2 executed, 40 up-to-date
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player>
-
-
-
-
-*Viewed [M3uParser.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt) *
-
-*Viewed [Daos.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/dao/Daos.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors.txt -Raw | Select-Object -First 2000`*
-
-*Checked command status*
-
-*Viewed [Movie.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Movie.kt) *
-
-*Viewed [XtreamDtos.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt) *
-
-*Viewed [XtreamProvider.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Viewed [Series.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Series.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Grep searched codebase*
-
-*Grep searched codebase*
-
-*User accepted the command `Select-String -Path c:\Users\david\.gemini\antigravity\scratch\iptv-player\data\src\main\java\com\streamvault\data\local\entity\Entities.kt -Pattern "val headers: Map<String, String>"`*
-
-*Checked command status*
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*Viewed [task.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/task.md) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `Get-Content c:\Users\david\.gemini\antigravity\scratch\iptv-player\data\src\main\java\com\streamvault\data\mapper\EntityMappers.kt | Select-Object -Skip 60 -First 10 | ForEach-Object { "[$_]" }`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content c:\Users\david\.gemini\antigravity\scratch\iptv-player\data\src\main\java\com\streamvault\data\mapper\EntityMappers.kt | Select-Object -Skip 85 -First 10 | ForEach-Object { "[$_]" }`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors_2.txt 2>&1`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content build_errors_2.txt -Raw | Select-Object -First 2000`*
-
-*Checked command status*
-
-*User accepted the command `Get-ChildItem -Path c:\Users\david\.gemini\antigravity\scratch\iptv-player\data -Filter "*.kt" -Recurse | Select-String -Pattern "drmType"`*
-
-*Checked command status*
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Viewed [M3uParser.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/parser/M3uParser.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Grep searched codebase*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Viewed [task.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/task.md) *
-
-*Checked command status*
-
-### User Input
-
- FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':data:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 4s
-42 actionable tasks: 1 executed, 41 up-to-date
-<-------------> 0% WAITING
-> IDLE
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player>
-
-*Viewed [Series.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Series.kt) *
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Viewed [Movie.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Movie.kt) *
-
-*Viewed [Entities.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/local/entity/Entities.kt) *
-
-*Edited relevant file*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content c:\Users\david\.gemini\antigravity\scratch\iptv-player\domain\src\main\java\com\streamvault\domain\model\Series.kt | ForEach-Object { "[$_]" }`*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin > build_errors_3.txt 2>&1`*
-
-### User Input
-
-BUILD FAILED in 4s
-42 actionable tasks: 1 executed, 41 up-to-date
-<-------------> 0% WAITING
-> IDLE
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> cd 'c:\Users\david\.gemini\antigravity\scratch\iptv-player'
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player> .\gradlew.bat compileDebugKotlin
-
-> Task :data:compileDebugKotlin FAILED
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:236:5 No parameter with name 'drmType' found.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:237:5 No parameter with name 'drmLicenseUrl' found.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:262:15 Unresolved reference 'drmType'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:263:21 Unresolved reference 'drmLicenseUrl'.
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':data:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 6s
-42 actionable tasks: 1 executed, 41 up-to-date
-PS C:\Users\david\.gemini\antigravity\scratch\iptv-player>
-
-
-*Viewed [Series.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/domain/src/main/java/com/streamvault/domain/model/Series.kt) *
-
-*Viewed [EntityMappers.kt](file:///c:/Users/david/.gemini/antigravity/scratch/iptv-player/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt) *
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*User accepted the command `Get-Content c:\Users\david\.gemini\antigravity\scratch\iptv-player\domain\src\main\java\com\streamvault\domain\model\Series.kt | ForEach-Object { "[$_]" }`*
-
-*Checked command status*
-
-*Edited relevant file*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*User accepted the command `.\gradlew.bat compileDebugKotlin`*
-
-*Checked command status*
-
-*Viewed [walkthrough.md](file:///c:/Users/david/.gemini/antigravity/brain/b930cdab-df3f-4254-92a9-b6f9c1de1551/walkthrough.md) *
-
-*Edited relevant file*
-
-### User Input
-
-generate apk
-
-*User accepted the command `.\gradlew.bat assembleDebug`*
-
-*Checked command status*
-
-*Searched filesystem*
\ No newline at end of file
diff --git a/UI_DESIGN.md b/UI_DESIGN.md
deleted file mode 100644
index e3bc892c..00000000
--- a/UI_DESIGN.md
+++ /dev/null
@@ -1,313 +0,0 @@
-# 📺 StreamVault — UI Design Specification
-
-## Design Philosophy
-
-> **Console game menu aesthetic**: Fast, predictable, visually clean, boring under the hood.
-
-The UI prioritizes **smoothness over visual complexity**. Premium feel comes from spacing, typography, focus behavior, and consistency — never from heavy effects.
-
----
-
-## 🎨 Design System
-
-### Color Palette (Dark Theme Only)
-
-```
-Background: #0D0D0D (near black)
-Surface: #1A1A1A (cards, panels)
-Surface Elevated: #242424 (dialogs, overlays)
-Primary: #6C63FF (accent, focused borders)
-Primary Variant: #8B83FF (hover states)
-On Background: #E8E8E8 (primary text)
-On Surface: #B0B0B0 (secondary text)
-On Surface Dim: #666666 (tertiary text)
-Error: #FF6B6B
-Success: #4ECB71
-Live Indicator: #FF4444 (pulsing dot)
-```
-
-### Typography (Google Font: Inter)
-
-| Role | Size | Weight | Usage |
-|--------------|-------|----------|----------------------------|
-| Display | 32sp | Bold | Screen titles |
-| Headline | 24sp | SemiBold | Section headers |
-| Title | 20sp | Medium | Card titles (focused) |
-| Body | 16sp | Regular | Descriptions, metadata |
-| Label | 14sp | Medium | Badges, timestamps |
-| Caption | 12sp | Regular | Subtle info |
-
-### Spacing Scale
-
-```
-XS: 4dp (icon padding)
-S: 8dp (card internal padding)
-M: 16dp (between cards)
-L: 24dp (section gaps)
-XL: 32dp (screen margins)
-XXL: 48dp (major section breaks)
-```
-
----
-
-## 📺 Visual Hierarchy
-
-### Screen Layout Structure
-
-```
-┌─────────────────────────────────────────────────┐
-│ [Logo] Live TV │ Movies │ Series │ ★ │ ⚙ │ ← Top Nav Bar (56dp)
-├─────────────────────────────────────────────────┤
-│ │
-│ Category Title │
-│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ ← Horizontal content rows
-│ │ │ │ │ │ FOC │ │ │ │ │ │
-│ │ │ │ │ │ USED│ │ │ │ │ │
-│ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │
-│ │
-│ Another Category │
-│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │
-│ │ │ │ │ │ │ │ │ │ │ │
-│ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │
-│ │
-└─────────────────────────────────────────────────┘
-```
-
-### Content Flow
-1. Top navigation bar — always visible, horizontal tabs
-2. Content area — vertical scroll of category rows
-3. Each category row — horizontal lazy list of cards
-4. Focus flows: Left/Right within row, Up/Down between rows
-
----
-
-## 🖼 Card Specifications
-
-### Channel Card (Live TV)
-- **Size**: 200dp × 120dp (16:10 landscape)
-- **Content**: Logo (centered, 64dp max), channel name below
-- **Live indicator**: Small red dot + "LIVE" label
-- **EPG overlay**: Current program name at bottom (truncated)
-
-### Movie Card (VOD)
-- **Size**: 160dp × 240dp (2:3 portrait poster)
-- **Content**: Poster image, title below
-- **Metadata**: Year, rating badge
-
-### Series Card
-- **Size**: 160dp × 240dp (2:3 portrait poster)
-- **Content**: Poster image, title, season count badge
-
-### Episode Card
-- **Size**: 280dp × 160dp (16:9 landscape)
-- **Content**: Thumbnail, episode title, duration
-- **Progress**: Thin progress bar at bottom (if partially watched)
-
----
-
-## 🔍 Focus Behavior (Critical)
-
-### Focus Appearance
-
-| State | Scale | Border | Text Opacity | Animation |
-|-----------|--------|----------------------|--------------|-----------|
-| Unfocused | 1.0 | None | 70% | — |
-| Focused | 1.06 | 2dp solid #6C63FF | 100% | 180ms |
-| Pressed | 0.98 | 2dp solid #8B83FF | 100% | 80ms |
-
-### Focus Rules
-- Focus transitions use `tween(180ms, LinearEasing)` — no spring/bounce
-- Only **ONE** animation property per interaction (scale only)
-- Border is **static**, not animated
-- Unfocus is **instant** (no delayed return animation)
-- Focus state never triggers layout reflow
-- Focus ring is drawn via `Modifier.border()`, not via shadow/glow
-
-### Navigation Rules
-- D-pad Left/Right: Move within current row
-- D-pad Up/Down: Move between rows (focus restores last-focused index)
-- Back: Navigate up one level (row → nav bar → exit prompt)
-- Select/Enter: Open item
-- Long press: Add to favorites (if applicable)
-
----
-
-## 🎬 Animation Specifications
-
-### Allowed Animations
-| Property | Duration | Easing | Use Case |
-|----------|----------|--------------|------------------------|
-| Scale | 180ms | Linear | Card focus |
-| Alpha | 150ms | Linear | Text/overlay appear |
-| Color | 150ms | Linear | Button state change |
-
-### Forbidden Animations
-- ❌ Blur / glassmorphism
-- ❌ Physics-based (spring, fling)
-- ❌ Layout size changes
-- ❌ Position animations
-- ❌ Shadow depth changes
-- ❌ Crossfade on images
-- ❌ Multiple chained animations
-- ❌ Particle effects
-
----
-
-## 📱 Screen Designs
-
-### 1. Live TV Screen
-```
-┌──────────────────────────────────────────┐
-│ Nav: [●Live TV] Movies Series ★ ⚙ │
-├──────────────────────────────────────────┤
-│ All Channels ▸ Search │
-│ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │
-│ │ CH │ │ CH │ │ CH │ │ CH │ │ CH │ │
-│ │logo│ │logo│ │logo│ │logo│ │logo│ │
-│ └────┘ └────┘ └────┘ └────┘ └────┘ │
-│ Entertainment │
-│ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │
-│ │ │ │ │ │ │ │ │ │ │ │
-│ └────┘ └────┘ └────┘ └────┘ └────┘ │
-│ Sports │
-│ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │
-│ └────┘ └────┘ └────┘ └────┘ └────┘ │
-└──────────────────────────────────────────┘
-```
-
-### 2. Movies Screen
-- Vertical scroll of category rows
-- Each row is a lazy horizontal list of poster cards
-- Categories fetched from provider
-
-### 3. Series Screen
-- Same layout as Movies
-- Selecting a series → Season list → Episode list (drill-down)
-
-### 4. Player Screen
-```
-┌──────────────────────────────────────────┐
-│ │
-│ [Video Surface] │
-│ │
-│──────────────────────────────────────────│
-│ Overlay (auto-hide after 5s): │
-│ ┌──────────────────────────────────────┐ │
-│ │ Channel Name / Movie Title │ │
-│ │ Now Playing: Program Name │ │
-│ │ ◄◄ ▶/❚❚ ►► 🔊 Vol ⚙ Decoder │ │
-│ │ ━━━━━━━━━━━●━━━━━━━━━━ 12:30/45:00 │ │
-│ └──────────────────────────────────────┘ │
-└──────────────────────────────────────────┘
-```
-- Overlay appears on any D-pad input, hides after 5s idle
-- Progress bar only for VOD, not live
-- Decoder mode toggle accessible from overlay
-
-### 5. EPG Timeline
-```
-┌──────────────────────────────────────────┐
-│ EPG Guide ◄ Feb 10 2026 ►│
-├──────┬───────┬───────┬───────┬──────────┤
-│ │ 17:00 │ 17:30 │ 18:00 │ 18:30 │
-├──────┼───────┴───────┼───────┼──────────┤
-│ BBC │ News Hour │ Sport │ Drama │
-├──────┼───────┬───────┴───────┼──────────┤
-│ CNN │ Live │ Documentary │ Talk │
-├──────┼───────┼───────────────┼──────────┤
-│ ESPN │ NBA Live │ Replay │
-└──────┴───────────────────────┴──────────┘
-```
-- Horizontal scroll for time, vertical scroll for channels
-- Current time indicator (vertical red line)
-- Focus on program cell → show details overlay
-
-### 6. Favorites Screen
-- Grid layout of favorited items (mixed: channels, movies, series)
-- Drag & drop reorder (hold select to enter reorder mode)
-- Virtual group tabs at top
-- "Create Group" button
-
-### 7. Settings Screen
-- Vertical list of setting groups
-- Provider management (add/remove/edit)
-- Decoder mode selection
-- EPG refresh interval
-- Image cache management
-- About / version info
-
----
-
-## ⚡ Performance Considerations
-
-### Image Strategy
-- **Coil** with disk + memory cache
-- Request images at exact card dimensions (no `wrap_content`)
-- No crossfade animations on image load
-- Placeholder: solid `#1A1A1A` rectangle
-- Error: channel name text fallback
-
-### Lazy List Optimization
-- `LazyRow` / `LazyVerticalGrid` for all content lists
-- Items keyed by stable ID
-- No unnecessary recomposition — use `remember` and `derivedStateOf`
-- Pre-fetch beyond visible items (`beyondBoundsItemCount`)
-
-### Recomposition Discipline
-- UI state is immutable data classes
-- ViewModels expose `StateFlow<UiState>`
-- No `MutableState` at screen level
-- Avoid collecting high-frequency flows (playback position) in Composables
-
-### Frame Budget
-- Target: ≤16ms per frame
-- No GC pressure from UI allocations
-- No blocking I/O on main thread
-- Compose stability annotations where needed
-
----
-
-## 🎯 Design Summary
-
-The visual identity is **dark, clean, and fast**. Every design decision serves the goal of instant-feeling D-pad navigation. The palette is muted with a single accent color. Cards are simple rectangles with posters. Focus is communicated through a consistent scale + border pattern. The entire UI could run on a $30 Android TV stick without frame drops.
-
----
-
-## 🧠 Interaction Patterns & Lessons Learned
-
-### 1. The "TV Focus" Rule
-Standard Compose Material 3 components often fail on Android TV because they assume touch interaction or handle focus internally in ways that conflict with D-Pad navigation.
-- **Rule**: If a component has complex internal state (like `TextField`), wrap it in a `Box` that handles the D-Pad focus and click events.
-- **Why**: `OutlinedTextField` often captures focus and refuses to surrender it, or fails to show the keyboard when focused via D-Pad.
-
-### 2. Search Bar Pattern
-**Do Not Use**: `OutlinedTextField` directly exposed to D-Pad.
-**Use This**:
-```kotlin
-Box(
- modifier = Modifier
- .focusable()
- .clickable {
- // 1. Request focus for inner TextField
- // 2. Show keyboard manually
- }
-) {
- BasicTextField(
- readOnly = true // Only editable when virtual keyboard is active
- )
-}
-```
-
-### 3. Long Press & Ghost Clicks
-**The Problem**: On many TV remotes, releasing the Select button after a Long Press triggers a subsequent `onClick` event ("Ghost Click").
-**The Fix**: Implement a **Top-Level Click Lock**.
-- When `onLongClick` fires: Set `lock = true`.
-- When `onClick` fires: Check `lock`. If true, consume event and set `lock = false`.
-- Safety: Auto-reset `lock` after 1s to prevent stuck states.
-- **Do Not Use**: Debounce by timestamp alone (unreliable if user holds button long).
-
-### 4. Zapping Architecture
-Channel zapping (P+/P-) in the player requires global context.
-- **Do Not**: Pass just the stream URL to the player.
-- **Do**: Pass the `channelId` and the `playlistContext` (Category ID). The player logic must query the DB for "Next Channel in Category X after Channel Y".
-
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 317c061a..3354f9c4 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -64,6 +64,7 @@ android {
buildFeatures {
compose = true
+ buildConfig = true
}
testOptions {
@@ -102,6 +103,7 @@ dependencies {
implementation(libs.retrofit.gson)
implementation(libs.okhttp)
implementation(libs.okhttp.logging)
+ implementation(libs.kotlinx.serialization.json)
// Activity & Lifecycle
implementation(libs.activity.compose)
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
index 0299774e..1ebfb9eb 100644
--- a/app/proguard-rules.pro
+++ b/app/proguard-rules.pro
@@ -16,10 +16,14 @@
# ── Retrofit / OkHttp ───────────────────────────────────────
-keepattributes Signature
-keepattributes *Annotation*
+# SEC-H02: Only keep what Retrofit actually requires — interface methods & response types.
-keep,allowobfuscation interface retrofit2.Call
-keep,allowobfuscation interface retrofit2.Callback
+-keep,allowobfuscation,allowshrinking class retrofit2.Response
+-keepclassmembers,allowshrinking,allowobfuscation interface * {
+ @retrofit2.http.* <methods>;
+}
-dontwarn retrofit2.**
--keep class retrofit2.** { *; }
-keepclassmembers,allowobfuscation class * {
@retrofit2.http.* <methods>;
}
@@ -49,7 +53,10 @@
-keep class com.streamvault.data.remote.xtream.model.** { *; }
# ── Media3 / ExoPlayer ─────────────────────────────────────
--keep class androidx.media3.** { *; }
+# SEC-H01: Media3 ships its own consumer-proguard-rules.pro inside the AAR — no need
+# for a broad keep here. Only explicitly keep classes loaded via reflection that the
+# AAR rules don't cover (e.g., extension renderers resolved at runtime).
+-keep class androidx.media3.exoplayer.DefaultRenderersFactory { *; }
-dontwarn androidx.media3.**
# ── Coroutines ──────────────────────────────────────────────
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index f759605c..d775dd5b 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -28,6 +28,7 @@
android:name=".MainActivity"
android:exported="true"
android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|smallestScreenSize"
+ android:supportsPictureInPicture="true"
android:screenOrientation="landscape">
<!-- TV Launcher entry point -->
diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.kt
index 299783c7..d2f9019b 100644
--- a/app/src/main/java/com/streamvault/app/MainActivity.kt
+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt
@@ -1,6 +1,10 @@
package com.streamvault.app
+import android.app.PictureInPictureParams
import android.os.Bundle
+import android.os.Build
+import android.os.StrictMode
+import android.util.Rational
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.streamvault.app.navigation.AppNavigation
@@ -24,15 +28,38 @@ import android.content.Context
import android.content.ContextWrapper
import android.content.res.AssetManager
import android.content.res.Resources
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
+ private data class PlayerPictureInPictureState(
+ val enabled: Boolean = false,
+ val isPlaying: Boolean = false,
+ val aspectRatio: Rational? = null
+ )
+
@Inject
lateinit var preferencesRepository: PreferencesRepository
+ private val _pictureInPictureModeFlow = MutableStateFlow(false)
+ val pictureInPictureModeFlow: StateFlow<Boolean> = _pictureInPictureModeFlow.asStateFlow()
+
+ private var playerPictureInPictureState = PlayerPictureInPictureState()
+
override fun onCreate(savedInstanceState: Bundle?) {
+ if (BuildConfig.DEBUG) {
+ StrictMode.setThreadPolicy(
+ StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build()
+ )
+ StrictMode.setVmPolicy(
+ StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build()
+ )
+ }
super.onCreate(savedInstanceState)
+ _pictureInPictureModeFlow.value = isInPictureInPictureMode
setContent {
val appLanguage by preferencesRepository.appLanguage.collectAsState(initial = "system")
val currentContext = LocalContext.current
@@ -83,4 +110,70 @@ class MainActivity : ComponentActivity() {
}
}
}
+
+ override fun onUserLeaveHint() {
+ super.onUserLeaveHint()
+ enterPlayerPictureInPictureModeIfEligible()
+ }
+
+ override fun onPictureInPictureModeChanged(
+ isInPictureInPictureMode: Boolean,
+ newConfig: Configuration
+ ) {
+ super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
+ _pictureInPictureModeFlow.value = isInPictureInPictureMode
+ }
+
+ fun updatePlayerPictureInPictureState(
+ enabled: Boolean,
+ isPlaying: Boolean,
+ videoWidth: Int,
+ videoHeight: Int
+ ) {
+ playerPictureInPictureState = PlayerPictureInPictureState(
+ enabled = enabled,
+ isPlaying = isPlaying,
+ aspectRatio = videoAspectRatioOrNull(videoWidth, videoHeight)
+ )
+ applyPlayerPictureInPictureParams()
+ }
+
+ fun clearPlayerPictureInPictureState() {
+ playerPictureInPictureState = PlayerPictureInPictureState()
+ applyPlayerPictureInPictureParams()
+ }
+
+ private fun enterPlayerPictureInPictureModeIfEligible(): Boolean {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || isInPictureInPictureMode) {
+ return false
+ }
+ val state = playerPictureInPictureState
+ if (!state.enabled || !state.isPlaying) {
+ return false
+ }
+ val params = buildPlayerPictureInPictureParams(state)
+ setPictureInPictureParams(params)
+ return enterPictureInPictureMode(params)
+ }
+
+ private fun applyPlayerPictureInPictureParams() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
+ setPictureInPictureParams(buildPlayerPictureInPictureParams(playerPictureInPictureState))
+ }
+
+ private fun buildPlayerPictureInPictureParams(
+ state: PlayerPictureInPictureState
+ ): PictureInPictureParams {
+ val builder = PictureInPictureParams.Builder()
+ state.aspectRatio?.let { builder.setAspectRatio(it) }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ builder.setAutoEnterEnabled(state.enabled && state.isPlaying)
+ }
+ return builder.build()
+ }
+
+ private fun videoAspectRatioOrNull(videoWidth: Int, videoHeight: Int): Rational? {
+ if (videoWidth <= 0 || videoHeight <= 0) return null
+ return Rational(videoWidth, videoHeight)
+ }
}
diff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
index e6ef435c..cd83624c 100644
--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
@@ -11,7 +11,9 @@ import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.Dispatchers
import okio.Path.Companion.toOkioPath
+import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
+import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import java.util.concurrent.TimeUnit
@@ -22,12 +24,19 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {
override fun onCreate() {
super.onCreate()
- // Schedule EPG garbage collection daily
+ // Schedule daily data maintenance: EPG pruning, stale-favorite cleanup, and DB compaction checks.
+ // BLD-H02: Require network + device idle so the worker doesn't drain battery.
+ val gcConstraints = Constraints.Builder()
+ .setRequiredNetworkType(NetworkType.CONNECTED)
+ .setRequiresDeviceIdle(true)
+ .build()
+
val gcWorkRequest = PeriodicWorkRequestBuilder<com.streamvault.data.sync.SyncWorker>(24, java.util.concurrent.TimeUnit.HOURS)
+ .setConstraints(gcConstraints)
.build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
- "EpgGCWorker",
+ "DataMaintenanceWorker",
ExistingPeriodicWorkPolicy.KEEP,
gcWorkRequest
)
@@ -49,7 +58,7 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {
// Limit concurrent decoding and fetching to 6 for TV hardware constraints
.fetcherCoroutineContext(Dispatchers.IO.limitedParallelism(6))
.decoderCoroutineContext(Dispatchers.Default.limitedParallelism(4))
- .crossfade(false)
+ .crossfade(true)
.build()
}
}
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
index 3e32c478..7bd8a6c7 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -2,6 +2,7 @@ package com.streamvault.app.di
import android.content.Context
import androidx.room.Room
+import androidx.room.RoomDatabase
import com.streamvault.data.local.StreamVaultDatabase
import com.streamvault.data.local.dao.*
import dagger.Module
@@ -23,7 +24,9 @@ object DatabaseModule {
StreamVaultDatabase::class.java,
"streamvault.db"
)
+ .setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)
.addMigrations(
+ StreamVaultDatabase.MIGRATION_1_2,
StreamVaultDatabase.MIGRATION_2_3,
StreamVaultDatabase.MIGRATION_3_4,
StreamVaultDatabase.MIGRATION_4_5,
@@ -32,7 +35,9 @@ object DatabaseModule {
StreamVaultDatabase.MIGRATION_7_8,
StreamVaultDatabase.MIGRATION_8_9,
StreamVaultDatabase.MIGRATION_9_10,
- StreamVaultDatabase.MIGRATION_10_11
+ StreamVaultDatabase.MIGRATION_10_11,
+ StreamVaultDatabase.MIGRATION_11_12,
+ StreamVaultDatabase.MIGRATION_12_13
)
// NOTE: fallbackToDestructiveMigration() intentionally removed.
// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.
@@ -40,6 +45,7 @@ object DatabaseModule {
@Provides fun provideProviderDao(db: StreamVaultDatabase): ProviderDao = db.providerDao()
@Provides fun provideChannelDao(db: StreamVaultDatabase): ChannelDao = db.channelDao()
+ @Provides fun provideChannelPreferenceDao(db: StreamVaultDatabase): ChannelPreferenceDao = db.channelPreferenceDao()
@Provides fun provideMovieDao(db: StreamVaultDatabase): MovieDao = db.movieDao()
@Provides fun provideSeriesDao(db: StreamVaultDatabase): SeriesDao = db.seriesDao()
@Provides fun provideEpisodeDao(db: StreamVaultDatabase): EpisodeDao = db.episodeDao()
diff --git a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
index a53dd97b..6632648a 100644
--- a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
@@ -2,7 +2,13 @@ package com.streamvault.app.di
import android.content.Context
import android.content.pm.ApplicationInfo
+import android.util.Log
+import com.google.gson.Gson
+import com.google.gson.GsonBuilder
+import com.streamvault.data.remote.NetworkTimeoutConfig
import com.streamvault.data.remote.xtream.XtreamApiService
+import com.streamvault.data.remote.xtream.OkHttpXtreamApiService
+import com.streamvault.data.remote.xtream.XtreamUrlFactory
import com.streamvault.data.parser.XmltvParser
import com.streamvault.player.Media3PlayerEngine
import com.streamvault.player.PlayerEngine
@@ -11,13 +17,10 @@ import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
+import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
-import retrofit2.Retrofit
-import retrofit2.converter.gson.GsonConverterFactory
-import com.google.gson.Gson
-import com.google.gson.GsonBuilder
-import java.util.concurrent.TimeUnit
+import java.util.concurrent.TimeUnit.SECONDS
import javax.inject.Singleton
@Module
@@ -36,18 +39,20 @@ object NetworkModule {
HttpLoggingInterceptor.Level.NONE
}
+ val httpLogger = HttpLoggingInterceptor { message ->
+ Log.d("OkHttp", XtreamUrlFactory.sanitizeLogMessage(message))
+ }.apply {
+ level = loggingLevel
+ }
+
return OkHttpClient.Builder()
- .connectTimeout(30, TimeUnit.SECONDS)
- .readTimeout(30, TimeUnit.SECONDS)
- .writeTimeout(30, TimeUnit.SECONDS)
- .addInterceptor(
- HttpLoggingInterceptor().apply {
- level = loggingLevel
- }
- )
+ .connectTimeout(NetworkTimeoutConfig.CONNECT_TIMEOUT_SECONDS, SECONDS)
+ .readTimeout(NetworkTimeoutConfig.READ_TIMEOUT_SECONDS, SECONDS)
+ .writeTimeout(NetworkTimeoutConfig.WRITE_TIMEOUT_SECONDS, SECONDS)
+ .addInterceptor(httpLogger)
.followRedirects(true)
.followSslRedirects(true)
- .connectionPool(okhttp3.ConnectionPool(10, 5, TimeUnit.MINUTES)) // Allow more idle connections
+ .connectionPool(okhttp3.ConnectionPool(10, 5, java.util.concurrent.TimeUnit.MINUTES)) // Allow more idle connections
.dispatcher(okhttp3.Dispatcher().apply {
maxRequests = 64
maxRequestsPerHost = 10 // Increase host limit for Multi-View
@@ -57,14 +62,17 @@ object NetworkModule {
@Provides
@Singleton
- fun provideXtreamApiService(okHttpClient: OkHttpClient, gson: Gson): XtreamApiService =
- Retrofit.Builder()
- // Base URL will be overridden per-request by the provider
- .baseUrl("https://placeholder.invalid/")
- .client(okHttpClient)
- .addConverterFactory(GsonConverterFactory.create(gson))
- .build()
- .create(XtreamApiService::class.java)
+ fun provideXtreamApiService(okHttpClient: OkHttpClient, xtreamJson: Json): XtreamApiService =
+ OkHttpXtreamApiService(okHttpClient, xtreamJson)
+
+ @Provides
+ @Singleton
+ fun provideXtreamJson(): Json = Json {
+ ignoreUnknownKeys = true
+ isLenient = true
+ explicitNulls = false
+ coerceInputValues = true
+ }
@Provides
@Singleton
@@ -74,13 +82,21 @@ object NetworkModule {
@Singleton
fun provideGson(): Gson = GsonBuilder().create()
+ @Provides
+ @Singleton
+ @MainPlayerEngine
+ fun provideMainPlayerEngine(
+ @ApplicationContext context: Context,
+ okHttpClient: OkHttpClient
+ ): PlayerEngine = Media3PlayerEngine(context, okHttpClient)
+
/**
- * Factory binding for PlayerEngine (NOT @Singleton).
- * This allows MultiViewViewModel to inject Provider<PlayerEngine>
- * and create up to 4 independent instances for split-screen playback.
+ * Factory binding for preview and multiview playback.
+ * Each Provider.get() call returns a fresh engine instance.
*/
@Provides
- fun providePlayerEngine(
+ @AuxiliaryPlayerEngine
+ fun provideAuxiliaryPlayerEngine(
@ApplicationContext context: Context,
okHttpClient: OkHttpClient
): PlayerEngine = Media3PlayerEngine(context, okHttpClient)
diff --git a/app/src/main/java/com/streamvault/app/di/PlayerEngineQualifiers.kt b/app/src/main/java/com/streamvault/app/di/PlayerEngineQualifiers.kt
new file mode 100644
index 00000000..a415e907
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/di/PlayerEngineQualifiers.kt
@@ -0,0 +1,11 @@
+package com.streamvault.app.di
+
+import javax.inject.Qualifier
+
+@Qualifier
+@Retention(AnnotationRetention.BINARY)
+annotation class MainPlayerEngine
+
+@Qualifier
+@Retention(AnnotationRetention.BINARY)
+annotation class AuxiliaryPlayerEngine
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
index 2cc42780..4d5698b4 100644
--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
@@ -1,6 +1,7 @@
package com.streamvault.app.navigation
import androidx.compose.runtime.Composable
+import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
@@ -21,8 +22,26 @@ import com.streamvault.app.ui.screens.provider.ProviderSetupScreen
import com.streamvault.app.ui.screens.series.SeriesScreen
import com.streamvault.app.ui.screens.settings.SettingsScreen
import com.streamvault.app.ui.screens.welcome.WelcomeScreen
+import java.io.Serializable
+private const val PLAYER_REQUEST_KEY = "player_request"
+
+data class PlayerNavigationRequest(
+ val streamUrl: String,
+ val title: String,
+ val channelId: String? = null,
+ val internalId: Long = -1L,
+ val categoryId: Long? = null,
+ val providerId: Long? = null,
+ val isVirtual: Boolean = false,
+ val contentType: String = "LIVE",
+ val archiveStartMs: Long? = null,
+ val archiveEndMs: Long? = null,
+ val archiveTitle: String? = null,
+ val returnRoute: String? = null
+) : Serializable
+
object Routes {
const val PROVIDER_SETUP = "provider_setup?providerId={providerId}"
const val HOME = "home"
@@ -34,7 +53,7 @@ object Routes {
const val EPG = "epg"
const val EPG_DESTINATION = "epg?categoryId={categoryId}&anchorTime={anchorTime}&favoritesOnly={favoritesOnly}"
const val SETTINGS = "settings"
- const val PLAYER = "player/{streamUrl}?title={title}&channelId={channelId}&internalId={internalId}&categoryId={categoryId}&providerId={providerId}&isVirtual={isVirtual}&contentType={contentType}&archiveStartMs={archiveStartMs}&archiveEndMs={archiveEndMs}&archiveTitle={archiveTitle}&returnRoute={returnRoute}"
+ const val PLAYER = "player"
const val SEARCH = "search"
const val SERIES_DETAIL = "series_detail/{seriesId}"
const val WELCOME = "welcome"
@@ -57,7 +76,7 @@ object Routes {
providerId: Long? = channel.providerId,
isVirtual: Boolean = false,
returnRoute: String? = null
- ): String {
+ ): PlayerNavigationRequest {
val effectiveCategoryId = categoryId ?: ChannelRepository.ALL_CHANNELS_ID
return player(
streamUrl = channel.streamUrl,
@@ -72,7 +91,7 @@ object Routes {
)
}
- fun moviePlayer(movie: Movie): String {
+ fun moviePlayer(movie: Movie): PlayerNavigationRequest {
return player(
streamUrl = movie.streamUrl,
title = movie.name,
@@ -83,7 +102,7 @@ object Routes {
)
}
- fun episodePlayer(episode: Episode): String {
+ fun episodePlayer(episode: Episode): PlayerNavigationRequest {
return player(
streamUrl = episode.streamUrl,
title = "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}",
@@ -94,8 +113,8 @@ object Routes {
}
fun player(
- streamUrl: String,
- title: String,
+ streamUrl: String,
+ title: String,
channelId: String? = null,
internalId: Long = -1L,
categoryId: Long? = null,
@@ -106,22 +125,55 @@ object Routes {
archiveEndMs: Long? = null,
archiveTitle: String? = null,
returnRoute: String? = null
- ): String {
- val encodedUrl = java.net.URLEncoder.encode(streamUrl, "UTF-8")
- val encodedTitle = java.net.URLEncoder.encode(title, "UTF-8")
- val encodedArchiveTitle = java.net.URLEncoder.encode(archiveTitle ?: "", "UTF-8")
- val encodedReturnRoute = java.net.URLEncoder.encode(returnRoute ?: "", "UTF-8")
- return "player/$encodedUrl?title=$encodedTitle&channelId=${channelId ?: ""}&internalId=$internalId&categoryId=${categoryId ?: -1L}&providerId=${providerId ?: -1L}&isVirtual=$isVirtual&contentType=$contentType&archiveStartMs=${archiveStartMs ?: -1L}&archiveEndMs=${archiveEndMs ?: -1L}&archiveTitle=$encodedArchiveTitle&returnRoute=$encodedReturnRoute"
+ ): PlayerNavigationRequest {
+ return PlayerNavigationRequest(
+ streamUrl = streamUrl,
+ title = title,
+ channelId = channelId,
+ internalId = internalId,
+ categoryId = categoryId,
+ providerId = providerId,
+ isVirtual = isVirtual,
+ contentType = contentType,
+ archiveStartMs = archiveStartMs,
+ archiveEndMs = archiveEndMs,
+ archiveTitle = archiveTitle,
+ returnRoute = returnRoute
+ )
}
fun seriesDetail(seriesId: Long) = "series_detail/$seriesId"
fun parentalControlGroups(providerId: Long) = "parental_control_groups/$providerId"
}
+/** Accepts only media streaming schemes; rejects javascript:, file://, data:, etc. */
+private fun isStreamUrlSafe(url: String?): Boolean {
+ if (url.isNullOrBlank()) return false
+ val scheme = url.substringBefore("://").lowercase()
+ return scheme in setOf("http", "https", "rtsp", "rtmp", "rtsps", "mms", "xtream")
+}
+
+private fun NavHostController.navigateToPlayer(request: PlayerNavigationRequest) {
+ currentBackStackEntry?.savedStateHandle?.set(PLAYER_REQUEST_KEY, request)
+ navigate(Routes.PLAYER) { launchSingleTop = true }
+}
+
@Composable
fun AppNavigation() {
val navController = rememberNavController()
+ // NAV-M02/NAV-H02: Single helper replacing repeated tab lambdas without serializing
+ // each tab's full UI tree into saved state on every switch.
+ fun tabNavigate(route: String) {
+ val currentRoute = navController.currentBackStackEntry?.destination?.route
+ if (currentRoute == route || currentRoute?.startsWith("$route?") == true) return
+
+ navController.navigate(route) {
+ popUpTo(Routes.HOME)
+ launchSingleTop = true
+ }
+ }
+
NavHost(
navController = navController,
startDestination = Routes.WELCOME
@@ -162,18 +214,12 @@ fun AppNavigation() {
composable(Routes.HOME) {
DashboardScreen(
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) { saveState = true }
- launchSingleTop = true
- restoreState = true
- }
- },
+ onNavigate = { route -> tabNavigate(route) },
onAddProvider = {
navController.navigate(Routes.providerSetup(null))
},
onChannelClick = { channel ->
- navController.navigate(
+ navController.navigateToPlayer(
Routes.livePlayer(
channel = channel,
categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,
@@ -183,7 +229,7 @@ fun AppNavigation() {
)
},
onMovieClick = { movie ->
- navController.navigate(Routes.moviePlayer(movie))
+ navController.navigateToPlayer(Routes.moviePlayer(movie))
},
onSeriesClick = { series ->
navController.navigate(Routes.seriesDetail(series.id))
@@ -221,7 +267,11 @@ fun AppNavigation() {
)
}
}
- navController.navigate(route)
+ if (route is PlayerNavigationRequest) {
+ navController.navigateToPlayer(route)
+ } else {
+ navController.navigate(route) { launchSingleTop = true }
+ }
},
currentRoute = Routes.HOME
)
@@ -236,7 +286,7 @@ fun AppNavigation() {
val initialCategoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }
HomeScreen(
onChannelClick = { channel, category, provider ->
- navController.navigate(
+ navController.navigateToPlayer(
Routes.livePlayer(
channel = channel,
categoryId = category?.id,
@@ -245,13 +295,7 @@ fun AppNavigation() {
)
)
},
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) { saveState = true }
- launchSingleTop = true
- restoreState = true
- }
- },
+ onNavigate = { route -> tabNavigate(route) },
currentRoute = Routes.LIVE_TV,
initialCategoryId = initialCategoryId
)
@@ -261,15 +305,9 @@ fun AppNavigation() {
composable(Routes.MOVIES) {
MoviesScreen(
onMovieClick = { movie ->
- navController.navigate(Routes.moviePlayer(movie))
- },
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) { saveState = true }
- launchSingleTop = true
- restoreState = true
- }
+ navController.navigateToPlayer(Routes.moviePlayer(movie))
},
+ onNavigate = { route -> tabNavigate(route) },
currentRoute = Routes.MOVIES
)
}
@@ -279,13 +317,7 @@ fun AppNavigation() {
onSeriesClick = { seriesId ->
navController.navigate(Routes.seriesDetail(seriesId))
},
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) { saveState = true }
- launchSingleTop = true
- restoreState = true
- }
- },
+ onNavigate = { route -> tabNavigate(route) },
currentRoute = Routes.SERIES
)
}
@@ -318,7 +350,11 @@ fun AppNavigation() {
}
else -> Routes.seriesDetail(item.favorite.contentId)
}
- navController.navigate(route)
+ if (route is PlayerNavigationRequest) {
+ navController.navigateToPlayer(route)
+ } else {
+ navController.navigate(route) { launchSingleTop = true }
+ }
},
onHistoryClick = { item ->
val route = when (item.history.contentType) {
@@ -356,15 +392,13 @@ fun AppNavigation() {
)
}
}
- navController.navigate(route)
- },
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) { saveState = true }
- launchSingleTop = true
- restoreState = true
+ if (route is PlayerNavigationRequest) {
+ navController.navigateToPlayer(route)
+ } else {
+ navController.navigate(route) { launchSingleTop = true }
}
},
+ onNavigate = { route -> tabNavigate(route) },
currentRoute = Routes.FAVORITES
)
}
@@ -386,7 +420,7 @@ fun AppNavigation() {
initialAnchorTime = epgAnchorTime,
initialFavoritesOnly = epgFavoritesOnly,
onPlayChannel = { channel, returnRoute ->
- navController.navigate(
+ navController.navigateToPlayer(
Routes.livePlayer(
channel = channel,
categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,
@@ -397,7 +431,7 @@ fun AppNavigation() {
)
},
onPlayArchive = { channel, program, returnRoute ->
- navController.navigate(
+ navController.navigateToPlayer(
Routes.player(
streamUrl = channel.streamUrl,
title = channel.name,
@@ -414,27 +448,13 @@ fun AppNavigation() {
)
)
},
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) { saveState = true }
- launchSingleTop = true
- restoreState = true
- }
- }
+ onNavigate = { route -> tabNavigate(route) }
)
}
composable(Routes.SETTINGS) {
SettingsScreen(
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) {
- saveState = true
- }
- launchSingleTop = true
- restoreState = true
- }
- },
+ onNavigate = { route -> tabNavigate(route) },
onAddProvider = {
navController.navigate(Routes.providerSetup(null))
},
@@ -456,13 +476,7 @@ fun AppNavigation() {
) {
com.streamvault.app.ui.screens.settings.parental.ParentalControlGroupScreen(
currentRoute = Routes.SETTINGS,
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) { saveState = true }
- launchSingleTop = true
- restoreState = true
- }
- },
+ onNavigate = { route -> tabNavigate(route) },
onBack = { navController.popBackStack() }
)
}
@@ -470,7 +484,7 @@ fun AppNavigation() {
composable(Routes.SEARCH) {
com.streamvault.app.ui.screens.search.SearchScreen(
onChannelClick = { channel ->
- navController.navigate(
+ navController.navigateToPlayer(
Routes.livePlayer(
channel = channel,
categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,
@@ -480,65 +494,35 @@ fun AppNavigation() {
)
},
onMovieClick = { movie ->
- navController.navigate(Routes.moviePlayer(movie))
+ navController.navigateToPlayer(Routes.moviePlayer(movie))
},
onSeriesClick = { series ->
navController.navigate(Routes.seriesDetail(series.id))
},
- onNavigate = { route ->
- navController.navigate(route) {
- popUpTo(Routes.HOME) { saveState = true }
- launchSingleTop = true
- restoreState = true
- }
- },
+ onNavigate = { route -> tabNavigate(route) },
currentRoute = Routes.SEARCH
)
}
- composable(
- route = Routes.PLAYER,
- arguments = listOf(
- navArgument("streamUrl") { type = NavType.StringType },
- navArgument("title") { type = NavType.StringType; defaultValue = "" },
- navArgument("channelId") { type = NavType.StringType; defaultValue = "" },
- navArgument("internalId") { type = NavType.LongType; defaultValue = -1L },
- navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L },
- navArgument("providerId") { type = NavType.LongType; defaultValue = -1L },
- navArgument("isVirtual") { type = NavType.BoolType; defaultValue = false },
- navArgument("contentType") { type = NavType.StringType; defaultValue = "LIVE" },
- navArgument("archiveStartMs") { type = NavType.LongType; defaultValue = -1L },
- navArgument("archiveEndMs") { type = NavType.LongType; defaultValue = -1L },
- navArgument("archiveTitle") { type = NavType.StringType; defaultValue = "" },
- navArgument("returnRoute") { type = NavType.StringType; defaultValue = "" }
- )
- ) { backStackEntry ->
- val streamUrl = backStackEntry.arguments?.getString("streamUrl") ?: ""
- val title = backStackEntry.arguments?.getString("title") ?: ""
- val channelId = backStackEntry.arguments?.getString("channelId")?.takeIf { it.isNotBlank() }
- val internalId = backStackEntry.arguments?.getLong("internalId") ?: -1L
- val categoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }
- val providerId = backStackEntry.arguments?.getLong("providerId")?.takeIf { it != -1L }
- val isVirtual = backStackEntry.arguments?.getBoolean("isVirtual") ?: false
- val contentType = backStackEntry.arguments?.getString("contentType") ?: "LIVE"
- val archiveStartMs = backStackEntry.arguments?.getLong("archiveStartMs")?.takeIf { it != -1L }
- val archiveEndMs = backStackEntry.arguments?.getLong("archiveEndMs")?.takeIf { it != -1L }
- val archiveTitle = backStackEntry.arguments?.getString("archiveTitle")?.takeIf { it.isNotBlank() }
- val returnRoute = backStackEntry.arguments?.getString("returnRoute")?.takeIf { it.isNotBlank() }
-
+ composable(route = Routes.PLAYER) { backStackEntry ->
+ val playerRequest = backStackEntry.savedStateHandle.get<PlayerNavigationRequest>(PLAYER_REQUEST_KEY)
+ ?: navController.previousBackStackEntry?.savedStateHandle?.get<PlayerNavigationRequest>(PLAYER_REQUEST_KEY)?.also {
+ backStackEntry.savedStateHandle[PLAYER_REQUEST_KEY] = it
+ }
+ val streamUrl = if (isStreamUrlSafe(playerRequest?.streamUrl)) playerRequest?.streamUrl.orEmpty() else ""
PlayerScreen(
streamUrl = streamUrl,
- title = title,
- epgChannelId = channelId,
- internalChannelId = internalId,
- categoryId = categoryId,
- providerId = providerId,
- isVirtual = isVirtual,
- contentType = contentType,
- archiveStartMs = archiveStartMs,
- archiveEndMs = archiveEndMs,
- archiveTitle = archiveTitle,
- returnRoute = returnRoute,
+ title = playerRequest?.title.orEmpty(),
+ epgChannelId = playerRequest?.channelId,
+ internalChannelId = playerRequest?.internalId ?: -1L,
+ categoryId = playerRequest?.categoryId,
+ providerId = playerRequest?.providerId,
+ isVirtual = playerRequest?.isVirtual ?: false,
+ contentType = playerRequest?.contentType ?: "LIVE",
+ archiveStartMs = playerRequest?.archiveStartMs,
+ archiveEndMs = playerRequest?.archiveEndMs,
+ archiveTitle = playerRequest?.archiveTitle,
+ returnRoute = playerRequest?.returnRoute,
onBack = { navController.popBackStack() },
onNavigate = { route -> navController.navigate(route) }
)
@@ -552,7 +536,7 @@ fun AppNavigation() {
) {
com.streamvault.app.ui.screens.series.SeriesDetailScreen(
onEpisodeClick = { episode ->
- navController.navigate(Routes.episodePlayer(episode))
+ navController.navigateToPlayer(Routes.episodePlayer(episode))
},
onBack = { navController.popBackStack() }
)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/AsyncImageModels.kt b/app/src/main/java/com/streamvault/app/ui/components/AsyncImageModels.kt
new file mode 100644
index 00000000..dc41d22c
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/AsyncImageModels.kt
@@ -0,0 +1,20 @@
+package com.streamvault.app.ui.components
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.platform.LocalContext
+import coil3.request.ImageRequest
+import coil3.request.crossfade
+
+@Composable
+fun rememberCrossfadeImageModel(data: Any?): Any? {
+ val context = LocalContext.current
+ return remember(context, data) {
+ data?.let {
+ ImageRequest.Builder(context)
+ .data(it)
+ .crossfade(true)
+ .build()
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
index 47f8aa2f..96165c66 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
@@ -20,8 +20,10 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
+import kotlinx.coroutines.delay
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -36,20 +38,23 @@ import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
+import com.streamvault.app.ui.design.LocalAppShapes
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import coil3.compose.AsyncImage
import com.streamvault.app.R
+import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.components.shell.MoviePosterCard
import com.streamvault.app.ui.components.shell.SeriesPosterCard
+import com.streamvault.app.ui.components.shell.StatusPill
import com.streamvault.app.ui.theme.AccentAmber
import com.streamvault.app.ui.theme.AccentCyan
import com.streamvault.app.ui.theme.AccentRed
-import com.streamvault.app.ui.theme.CardBackground
import com.streamvault.app.ui.theme.FocusBorder
import com.streamvault.app.ui.theme.GradientOverlayBottom
import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.Surface
import com.streamvault.app.ui.theme.SurfaceElevated
import com.streamvault.app.ui.theme.SurfaceHighlight
import com.streamvault.app.ui.theme.TextPrimary
@@ -100,7 +105,7 @@ fun FocusableCard(
pressedScale = FocusSpec.PressedScale
),
colors = ClickableSurfaceDefaults.colors(
- containerColor = CardBackground,
+ containerColor = Surface,
focusedContainerColor = SurfaceHighlight
),
border = ClickableSurfaceDefaults.border(
@@ -133,6 +138,14 @@ fun ChannelCard(
isReorderMode: Boolean = false,
isDragging: Boolean = false
) {
+ // Ticks every 30s so EPG progress bars stay accurate without busy-looping
+ val nowMs by produceState(initialValue = System.currentTimeMillis()) {
+ while (true) {
+ delay(30_000L)
+ value = System.currentTimeMillis()
+ }
+ }
+ val channelCardShape = LocalAppShapes.current.small
FocusableCard(
onClick = onClick,
onLongClick = onLongClick,
@@ -142,15 +155,25 @@ fun ChannelCard(
isReorderMode = isReorderMode,
isDragging = isDragging
) { isFocused ->
- if (!channel.logoUrl.isNullOrBlank() && !isLocked) {
- AsyncImage(
- model = channel.logoUrl,
- contentDescription = channel.name,
- modifier = Modifier
- .fillMaxSize()
- .clip(RoundedCornerShape(10.dp)),
- contentScale = ContentScale.Fit
- )
+ if (!isLocked) {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ // Initials fallback — visible when image is absent or fails to load
+ Text(
+ text = channel.name.take(2).uppercase(java.util.Locale.ROOT),
+ style = MaterialTheme.typography.titleMedium,
+ color = TextSecondary
+ )
+ if (!channel.logoUrl.isNullOrBlank()) {
+ AsyncImage(
+ model = rememberCrossfadeImageModel(channel.logoUrl),
+ contentDescription = channel.name,
+ modifier = Modifier
+ .fillMaxSize()
+ .clip(channelCardShape),
+ contentScale = ContentScale.Fit
+ )
+ }
+ }
}
Box(
@@ -190,9 +213,8 @@ fun ChannelCard(
overflow = TextOverflow.Ellipsis
)
- val now = System.currentTimeMillis()
val totalDuration = program.endTime - program.startTime
- val elapsed = now - program.startTime
+ val elapsed = nowMs - program.startTime
val progress = if (totalDuration > 0) elapsed.toFloat() / totalDuration else 0f
LinearProgressIndicator(
@@ -217,24 +239,27 @@ fun ChannelCard(
verticalAlignment = Alignment.CenterVertically
) {
if (channel.isFavorite) {
- StatusBadge(label = stringResource(R.string.badge_fav), containerColor = AccentAmber, contentColor = Color.Black)
+ StatusPill(label = stringResource(R.string.badge_fav), containerColor = AccentAmber, contentColor = Color.Black, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)
}
if (channel.errorCount > 0) {
- StatusBadge(label = stringResource(R.string.badge_error), containerColor = AccentRed)
+ StatusPill(label = stringResource(R.string.badge_error), containerColor = AccentRed, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)
}
if (channel.catchUpSupported) {
- StatusBadge(label = stringResource(R.string.badge_catch_up), containerColor = Primary)
+ StatusPill(label = stringResource(R.string.badge_catch_up), containerColor = Primary, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)
}
- StatusBadge(
+ StatusPill(
label = stringResource(R.string.card_live_badge),
- containerColor = AccentRed
+ containerColor = AccentRed,
+ cornerRadius = 4.dp,
+ horizontalPadding = 6.dp,
+ verticalPadding = 2.dp
)
}
}
if (isLocked) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- StatusBadge(label = stringResource(R.string.home_locked_short), containerColor = SurfaceHighlight)
+ StatusPill(label = stringResource(R.string.home_locked_short), containerColor = SurfaceHighlight, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)
}
}
}
@@ -272,9 +297,12 @@ fun MovieCard(
.background(SurfaceElevated),
contentAlignment = Alignment.Center
) {
- StatusBadge(
+ StatusPill(
label = if (isLocked) stringResource(R.string.home_locked_short) else stringResource(R.string.badge_movie),
- containerColor = SurfaceHighlight
+ containerColor = SurfaceHighlight,
+ cornerRadius = 4.dp,
+ horizontalPadding = 6.dp,
+ verticalPadding = 2.dp
)
}
}
@@ -310,7 +338,7 @@ fun MovieCard(
if (movie.isFavorite) {
Box(modifier = Modifier.align(Alignment.TopEnd).padding(8.dp)) {
- StatusBadge(label = stringResource(R.string.badge_fav), containerColor = AccentRed)
+ StatusPill(label = stringResource(R.string.badge_fav), containerColor = AccentRed, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)
}
}
}
@@ -350,9 +378,12 @@ fun SeriesCard(
.background(SurfaceElevated),
contentAlignment = Alignment.Center
) {
- StatusBadge(
+ StatusPill(
label = if (isLocked) stringResource(R.string.home_locked_short) else stringResource(R.string.badge_series),
- containerColor = SurfaceHighlight
+ containerColor = SurfaceHighlight,
+ cornerRadius = 4.dp,
+ horizontalPadding = 6.dp,
+ verticalPadding = 2.dp
)
}
}
@@ -388,28 +419,9 @@ fun SeriesCard(
if (series.isFavorite) {
Box(modifier = Modifier.align(Alignment.TopEnd).padding(8.dp)) {
- StatusBadge(label = stringResource(R.string.badge_fav), containerColor = AccentRed)
+ StatusPill(label = stringResource(R.string.badge_fav), containerColor = AccentRed, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)
}
}
}
}
}
-
-@Composable
-private fun StatusBadge(
- label: String,
- containerColor: Color,
- contentColor: Color = Color.White
-) {
- Box(
- modifier = Modifier
- .background(containerColor, RoundedCornerShape(4.dp))
- .padding(horizontal = 6.dp, vertical = 2.dp)
- ) {
- Text(
- text = label,
- style = MaterialTheme.typography.labelSmall,
- color = contentColor
- )
- }
-}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
index f5fe7d59..33eca542 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
@@ -4,23 +4,18 @@ import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
-import androidx.compose.ui.Alignment
+import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.focusRestorer
import androidx.compose.ui.unit.dp
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.tv.material3.MaterialTheme
-import androidx.tv.material3.ClickableSurfaceDefaults
-import androidx.tv.material3.Surface
-import androidx.tv.material3.Text
import com.streamvault.app.ui.theme.LocalSpacing
-import com.streamvault.app.ui.theme.Primary
-import com.streamvault.app.ui.theme.TextPrimary
-import com.streamvault.app.ui.theme.TextTertiary
import androidx.compose.ui.res.stringResource
import com.streamvault.app.R
+import com.streamvault.app.ui.components.shell.AppSectionHeader
// ── Netflix-style horizontal category row ─────────────────────────
+@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun <T : Any> CategoryRow(
title: String,
@@ -31,45 +26,23 @@ fun <T : Any> CategoryRow(
itemContent: @Composable (T) -> Unit
) {
Column(modifier = modifier.fillMaxWidth()) {
- // Row header
- Row(
+ AppSectionHeader(
+ title = title,
modifier = Modifier
.fillMaxWidth()
.padding(start = 20.dp, end = 20.dp, top = 14.dp, bottom = 6.dp),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = title,
- style = MaterialTheme.typography.titleMedium,
- color = TextPrimary
- )
- if (onSeeAll != null) {
- Surface(
- onClick = onSeeAll,
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = Primary.copy(alpha = 0.12f),
- focusedContainerColor = Primary.copy(alpha = 0.22f),
- contentColor = TextTertiary
- )
- ) {
- Text(
- text = stringResource(R.string.category_see_all),
- style = MaterialTheme.typography.labelSmall,
- modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp)
- )
- }
- }
- }
+ actionLabel = onSeeAll?.let { stringResource(R.string.category_see_all) },
+ onActionClick = onSeeAll
+ )
LazyRow(
+ modifier = Modifier.focusRestorer(),
contentPadding = PaddingValues(horizontal = 20.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
items(
items = items,
- key = keySelector ?: { it.hashCode() }
+ key = keySelector // null = index-based keys (safe default)
) { item ->
itemContent(item)
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt b/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt
index 286f132b..81ca95e6 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt
@@ -16,9 +16,11 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
+import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.focus.focusRestorer
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
@@ -29,6 +31,7 @@ import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Text
import coil3.compose.AsyncImage
import com.streamvault.app.R
+import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.theme.AccentCyan
import com.streamvault.app.ui.theme.GradientOverlayBottom
import com.streamvault.app.ui.theme.SurfaceElevated
@@ -38,6 +41,7 @@ import com.streamvault.app.ui.theme.TextTertiary
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.PlaybackHistory
+@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun ContinueWatchingRow(
items: List<PlaybackHistory>,
@@ -62,6 +66,7 @@ fun ContinueWatchingRow(
}
LazyRow(
+ modifier = Modifier.focusRestorer(),
contentPadding = PaddingValues(horizontal = 20.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
@@ -88,30 +93,30 @@ private fun ContinueWatchingTile(
width = 208.dp,
height = 117.dp
) {
- if (!history.posterUrl.isNullOrBlank()) {
- AsyncImage(
- model = history.posterUrl,
- contentDescription = history.title,
- modifier = Modifier
- .fillMaxSize()
- .clip(RoundedCornerShape(10.dp)),
- contentScale = ContentScale.Crop
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(SurfaceElevated),
+ contentAlignment = Alignment.Center
+ ) {
+ // Fallback always visible; covered by AsyncImage on successful load
+ Text(
+ text = when (history.contentType) {
+ ContentType.LIVE -> stringResource(R.string.card_live_badge)
+ ContentType.MOVIE -> stringResource(R.string.nav_movies)
+ ContentType.SERIES, ContentType.SERIES_EPISODE -> stringResource(R.string.nav_series)
+ },
+ style = MaterialTheme.typography.titleLarge,
+ color = TextSecondary
)
- } else {
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(SurfaceElevated),
- contentAlignment = Alignment.Center
- ) {
- Text(
- text = when (history.contentType) {
- ContentType.LIVE -> "LIVE"
- ContentType.MOVIE -> "MOVIE"
- ContentType.SERIES, ContentType.SERIES_EPISODE -> "SERIES"
- },
- style = MaterialTheme.typography.titleLarge,
- color = TextSecondary
+ if (!history.posterUrl.isNullOrBlank()) {
+ AsyncImage(
+ model = rememberCrossfadeImageModel(history.posterUrl),
+ contentDescription = history.title,
+ modifier = Modifier
+ .fillMaxSize()
+ .clip(RoundedCornerShape(10.dp)),
+ contentScale = ContentScale.Crop
)
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/PlaylistSwitcher.kt b/app/src/main/java/com/streamvault/app/ui/components/PlaylistSwitcher.kt
index 7975cc00..8fb79ffc 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/PlaylistSwitcher.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/PlaylistSwitcher.kt
@@ -1,5 +1,9 @@
package com.streamvault.app.ui.components
+import androidx.activity.compose.BackHandler
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.KeyboardArrowDown
+import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -19,6 +23,7 @@ import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.Icon
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
import androidx.tv.material3.SurfaceDefaults
@@ -40,6 +45,8 @@ fun PlaylistSwitcher(
var showProviderList by remember { mutableStateOf(false) }
var isFocused by remember { mutableStateOf(false) }
+ BackHandler(enabled = showProviderList) { showProviderList = false }
+
Box(modifier = modifier) {
Surface(
onClick = { showProviderList = !showProviderList },
@@ -65,10 +72,10 @@ fun PlaylistSwitcher(
style = MaterialTheme.typography.bodyMedium,
color = if (isFocused) Primary else OnBackground
)
- Text(
- text = if (showProviderList) "^" else "v",
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
+ Icon(
+ imageVector = if (showProviderList) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
+ contentDescription = null,
+ tint = OnSurfaceDim
)
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/ReorderTopBar.kt b/app/src/main/java/com/streamvault/app/ui/components/ReorderTopBar.kt
index d6038739..c44551c6 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/ReorderTopBar.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/ReorderTopBar.kt
@@ -1,5 +1,6 @@
package com.streamvault.app.ui.components
+import androidx.compose.foundation.BorderStroke
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
@@ -15,6 +16,8 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.res.stringResource
import androidx.tv.material3.*
import com.streamvault.app.R
+import com.streamvault.app.ui.design.FocusSpec
+import com.streamvault.app.ui.theme.FocusBorder
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.Primary
import com.streamvault.app.ui.theme.SurfaceElevated
@@ -26,11 +29,12 @@ fun ReorderTopBar(
categoryName: String,
onSave: () -> Unit,
onCancel: () -> Unit,
+ visible: Boolean = true,
subtitle: String? = null,
modifier: Modifier = Modifier
) {
AnimatedVisibility(
- visible = true,
+ visible = visible,
enter = slideInVertically(initialOffsetY = { -it }),
exit = slideOutVertically(targetOffsetY = { -it }),
modifier = modifier
@@ -78,8 +82,16 @@ fun ReorderTopBar(
onClick = onCancel,
colors = ButtonDefaults.colors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
- contentColor = OnSurface
- )
+ contentColor = OnSurface,
+ focusedContainerColor = MaterialTheme.colorScheme.surface,
+ focusedContentColor = OnSurface
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder)
+ )
+ ),
+ scale = ButtonDefaults.scale(focusedScale = FocusSpec.FocusedScale)
) {
Text(stringResource(R.string.action_cancel), modifier = Modifier.padding(horizontal = 8.dp))
}
@@ -88,8 +100,16 @@ fun ReorderTopBar(
onClick = onSave,
colors = ButtonDefaults.colors(
containerColor = Primary,
- contentColor = Color.White
- )
+ contentColor = Color.White,
+ focusedContainerColor = Primary.copy(alpha = 0.88f),
+ focusedContentColor = Color.White
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder)
+ )
+ ),
+ scale = ButtonDefaults.scale(focusedScale = FocusSpec.FocusedScale)
) {
Text(stringResource(R.string.action_save_order), modifier = Modifier.padding(horizontal = 8.dp))
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt
index 90185a33..629d4d53 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt
@@ -1,5 +1,6 @@
package com.streamvault.app.ui.components
+import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
@@ -18,11 +19,14 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.res.stringResource
import androidx.tv.material3.Button
import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.Border
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import com.streamvault.app.R
+import com.streamvault.app.ui.design.FocusSpec
+import com.streamvault.app.ui.theme.FocusBorder
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
@@ -95,8 +99,16 @@ fun SavedCategoryContextCard(
Button(
onClick = onManageClick,
colors = ButtonDefaults.colors(
- containerColor = Primary.copy(alpha = 0.92f)
- )
+ containerColor = Primary.copy(alpha = 0.92f),
+ focusedContainerColor = Primary,
+ focusedContentColor = androidx.compose.ui.graphics.Color.White
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder)
+ )
+ ),
+ scale = ButtonDefaults.scale(focusedScale = FocusSpec.FocusedScale)
) {
Text(stringResource(R.string.library_saved_manage_action))
}
@@ -104,8 +116,16 @@ fun SavedCategoryContextCard(
onClick = onBrowseAllClick,
colors = ButtonDefaults.colors(
containerColor = SurfaceElevated.copy(alpha = 0.78f),
- contentColor = OnSurface
- )
+ contentColor = OnSurface,
+ focusedContainerColor = SurfaceElevated,
+ focusedContentColor = OnSurface
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder)
+ )
+ ),
+ scale = ButtonDefaults.scale(focusedScale = FocusSpec.FocusedScale)
) {
Text(stringResource(R.string.library_browse_all))
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt
index ae216bfc..5a06d9d0 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt
@@ -1,5 +1,6 @@
package com.streamvault.app.ui.components
+import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
@@ -11,16 +12,22 @@ import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
+import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.focusRestorer
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.res.stringResource
+import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
+import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import com.streamvault.app.R
+import com.streamvault.app.ui.design.FocusSpec
+import com.streamvault.app.ui.theme.FocusBorder
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
@@ -31,6 +38,7 @@ data class SavedCategoryShortcut(
val count: Int
)
+@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun SavedCategoryShortcutsRow(
title: String,
@@ -77,15 +85,11 @@ fun SavedCategoryShortcutsRow(
if (shortcuts.isEmpty()) {
Surface(
- enabled = false,
- onClick = { },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp),
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = SurfaceElevated
- )
+ shape = RoundedCornerShape(14.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated)
) {
Text(
text = emptyHint,
@@ -100,6 +104,7 @@ fun SavedCategoryShortcutsRow(
}
LazyRow(
+ modifier = Modifier.focusRestorer(),
contentPadding = PaddingValues(horizontal = 20.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
@@ -115,8 +120,17 @@ fun SavedCategoryShortcutsRow(
} else {
SurfaceElevated
},
- focusedContainerColor = Primary.copy(alpha = 0.22f)
- )
+ focusedContainerColor = Primary.copy(alpha = 0.22f),
+ contentColor = if (isPrimaryShortcutSelected) Primary else OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder),
+ shape = RoundedCornerShape(14.dp)
+ )
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = FocusSpec.FocusedScale)
) {
Column(
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
@@ -150,8 +164,17 @@ fun SavedCategoryShortcutsRow(
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
- focusedContainerColor = Primary.copy(alpha = 0.22f)
- )
+ focusedContainerColor = Primary.copy(alpha = 0.22f),
+ contentColor = if (isSelected) Primary else OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder),
+ shape = RoundedCornerShape(14.dp)
+ )
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = FocusSpec.FocusedScale)
) {
Column(
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
index d939e66d..a77a27f8 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
@@ -11,6 +11,8 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
@@ -30,15 +32,26 @@ data class SelectionChip(
val supportingText: String? = null
)
+data class ChipRowItem(
+ val key: String,
+ val label: String,
+ val supportingText: String? = null,
+ val onClick: () -> Unit
+)
+
@Composable
-fun SelectionChipRow(
- title: String,
- chips: List<SelectionChip>,
+fun ChipRowSection(
+ chips: List<ChipRowItem>,
selectedKey: String?,
- onChipSelected: (String) -> Unit,
modifier: Modifier = Modifier,
+ title: String? = null,
subtitle: String? = null,
- contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp)
+ headerHorizontalPadding: Int = 24,
+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp),
+ chipHorizontalPadding: Int = 16,
+ supportingTextStyle: TextStyle = MaterialTheme.typography.bodySmall,
+ supportingTextMaxLines: Int = Int.MAX_VALUE,
+ focusedContainerBoostWhenSelected: Boolean = false
) {
if (chips.isEmpty()) return
@@ -47,18 +60,20 @@ fun SelectionChipRow(
.fillMaxWidth()
.padding(vertical = 6.dp)
) {
- Text(
- text = title,
- style = MaterialTheme.typography.labelMedium,
- color = OnSurfaceDim,
- modifier = Modifier.padding(horizontal = 24.dp)
- )
+ if (!title.isNullOrBlank()) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = headerHorizontalPadding.dp)
+ )
+ }
if (!subtitle.isNullOrBlank()) {
Text(
text = subtitle,
style = MaterialTheme.typography.bodySmall,
color = OnSurfaceDim,
- modifier = Modifier.padding(horizontal = 24.dp, vertical = 2.dp)
+ modifier = Modifier.padding(horizontal = headerHorizontalPadding.dp, vertical = 2.dp)
)
}
LazyRow(
@@ -68,11 +83,10 @@ fun SelectionChipRow(
items(chips, key = { it.key }) { chip ->
val isSelected = chip.key == selectedKey
Surface(
- onClick = { onChipSelected(chip.key) },
- modifier = Modifier,
+ onClick = chip.onClick,
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
- focusedContainerColor = SurfaceHighlight,
+ focusedContainerColor = if (isSelected && focusedContainerBoostWhenSelected) Primary.copy(alpha = 0.28f) else SurfaceHighlight,
contentColor = if (isSelected) Primary else OnSurface,
focusedContentColor = OnSurface
),
@@ -82,21 +96,26 @@ fun SelectionChipRow(
border = BorderStroke(2.dp, FocusBorder),
shape = RoundedCornerShape(999.dp)
)
- )
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
) {
Column(
- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
+ modifier = Modifier.padding(horizontal = chipHorizontalPadding.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(2.dp)
) {
Text(
text = chip.label,
- style = MaterialTheme.typography.labelLarge
+ style = MaterialTheme.typography.labelLarge,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
)
- if (!chip.supportingText.isNullOrBlank()) {
+ chip.supportingText?.takeIf { it.isNotBlank() }?.let {
Text(
- text = chip.supportingText,
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
+ text = it,
+ style = supportingTextStyle,
+ color = OnSurfaceDim,
+ maxLines = supportingTextMaxLines,
+ overflow = TextOverflow.Ellipsis
)
}
}
@@ -105,3 +124,30 @@ fun SelectionChipRow(
}
}
}
+
+@Composable
+fun SelectionChipRow(
+ title: String,
+ chips: List<SelectionChip>,
+ selectedKey: String?,
+ onChipSelected: (String) -> Unit,
+ modifier: Modifier = Modifier,
+ subtitle: String? = null,
+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp)
+) {
+ ChipRowSection(
+ title = title,
+ subtitle = subtitle,
+ chips = chips.map { chip ->
+ ChipRowItem(
+ key = chip.key,
+ label = chip.label,
+ supportingText = chip.supportingText,
+ onClick = { onChipSelected(chip.key) }
+ )
+ },
+ selectedKey = selectedKey,
+ modifier = modifier,
+ contentPadding = contentPadding
+ )
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SkeletonLoader.kt b/app/src/main/java/com/streamvault/app/ui/components/SkeletonLoader.kt
index 12240d25..cd20064a 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SkeletonLoader.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SkeletonLoader.kt
@@ -1,52 +1,110 @@
package com.streamvault.app.ui.components
-import androidx.compose.animation.core.*
+import androidx.compose.animation.core.FastOutSlowInEasing
+import androidx.compose.animation.core.animate
+import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
-import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.ContentDrawScope
+import androidx.compose.ui.node.DrawModifierNode
+import androidx.compose.ui.node.ModifierNodeElement
+import androidx.compose.ui.node.invalidateDraw
+import androidx.compose.ui.platform.InspectorInfo
import androidx.compose.ui.unit.dp
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
-fun Modifier.shimmerEffect(): Modifier = composed {
- val shimmerColors = listOf(
- Color.LightGray.copy(alpha = 0.2f),
- Color.LightGray.copy(alpha = 0.05f),
- Color.LightGray.copy(alpha = 0.2f),
- )
+fun Modifier.shimmerEffect(baseColor: Color): Modifier = this.then(ShimmerElement(baseColor))
- val transition = rememberInfiniteTransition(label = "")
- val translateAnimation = transition.animateFloat(
- initialValue = 0f,
- targetValue = 1000f,
- animationSpec = infiniteRepeatable(
- animation = tween(
- durationMillis = 1000,
- easing = FastOutSlowInEasing
- ),
- repeatMode = RepeatMode.Restart
- ),
- label = ""
- )
- background(
- brush = Brush.linearGradient(
- colors = shimmerColors,
- start = Offset.Zero,
- end = Offset(x = translateAnimation.value, y = translateAnimation.value)
+private data class ShimmerElement(
+ private val baseColor: Color
+) : ModifierNodeElement<ShimmerNode>() {
+ override fun create(): ShimmerNode = ShimmerNode(baseColor)
+
+ override fun update(node: ShimmerNode) {
+ node.updateBaseColor(baseColor)
+ }
+
+ override fun InspectorInfo.inspectableProperties() {
+ name = "shimmerEffect"
+ properties["baseColor"] = baseColor
+ }
+}
+
+private class ShimmerNode(
+ baseColor: Color
+) : Modifier.Node(), DrawModifierNode {
+ private var animationJob: Job? = null
+ private var progress: Float = -1f
+ private var shimmerBaseColor: Color = baseColor
+
+ override fun onAttach() {
+ startAnimation()
+ }
+
+ override fun onDetach() {
+ animationJob?.cancel()
+ animationJob = null
+ }
+
+ fun updateBaseColor(baseColor: Color) {
+ if (shimmerBaseColor != baseColor) {
+ shimmerBaseColor = baseColor
+ invalidateDraw()
+ }
+ }
+
+ private fun startAnimation() {
+ if (animationJob != null) return
+ animationJob = coroutineScope.launch {
+ while (isActive) {
+ animate(
+ initialValue = -1f,
+ targetValue = 1f,
+ animationSpec = tween(durationMillis = 1000, easing = FastOutSlowInEasing)
+ ) { value, _ ->
+ progress = value
+ invalidateDraw()
+ }
+ }
+ }
+ }
+
+ override fun ContentDrawScope.draw() {
+ drawContent()
+ val shimmerColors = listOf(
+ shimmerBaseColor.copy(alpha = 0.12f),
+ shimmerBaseColor.copy(alpha = 0.04f),
+ shimmerBaseColor.copy(alpha = 0.12f)
)
- )
+ val startX = size.width * progress
+ val endX = startX + size.width
+ drawRect(
+ brush = Brush.linearGradient(
+ colors = shimmerColors,
+ start = Offset(x = startX - size.width, y = 0f),
+ end = Offset(x = endX, y = size.height)
+ )
+ )
+ }
}
@Composable
fun SkeletonCard(modifier: Modifier = Modifier) {
+ val bgColor = MaterialTheme.colorScheme.surfaceVariant
+ val shimmerBaseColor = MaterialTheme.colorScheme.onSurface
Box(
modifier = modifier
- .background(Color.DarkGray, RoundedCornerShape(8.dp))
- .shimmerEffect()
+ .background(bgColor, RoundedCornerShape(8.dp))
+ .shimmerEffect(baseColor = shimmerBaseColor)
)
}
@@ -57,13 +115,15 @@ fun SkeletonRow(
cardHeight: Int = 210,
itemsCount: Int = 5
) {
+ val bgColor = MaterialTheme.colorScheme.surfaceVariant
+ val shimmerBaseColor = MaterialTheme.colorScheme.onSurface
Column(modifier = modifier.padding(vertical = 16.dp)) {
Box(
modifier = Modifier
.width(150.dp)
.height(24.dp)
- .background(Color.DarkGray, RoundedCornerShape(4.dp))
- .shimmerEffect()
+ .background(bgColor, RoundedCornerShape(4.dp))
+ .shimmerEffect(baseColor = shimmerBaseColor)
.padding(horizontal = 16.dp, vertical = 8.dp)
)
Spacer(modifier = Modifier.height(16.dp))
diff --git a/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt b/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt
deleted file mode 100644
index 4f7cbefb..00000000
--- a/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt
+++ /dev/null
@@ -1,189 +0,0 @@
-package com.streamvault.app.ui.components
-
-import androidx.compose.animation.core.animateFloatAsState
-import androidx.compose.animation.core.tween
-import androidx.compose.foundation.BorderStroke
-import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.fillMaxWidth
-import androidx.compose.foundation.layout.height
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.width
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.compose.runtime.setValue
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.focus.FocusRequester
-import androidx.compose.ui.focus.focusProperties
-import androidx.compose.ui.focus.focusRequester
-import androidx.compose.ui.focus.onFocusChanged
-import androidx.compose.ui.graphics.graphicsLayer
-import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.unit.dp
-import androidx.tv.material3.Border
-import androidx.tv.material3.ClickableSurfaceDefaults
-import androidx.tv.material3.MaterialTheme
-import androidx.tv.material3.Surface
-import androidx.tv.material3.Text
-import com.streamvault.app.R
-import com.streamvault.app.navigation.Routes
-import com.streamvault.app.ui.design.AppColors
-import com.streamvault.app.ui.design.FocusSpec
-import com.streamvault.app.ui.theme.FocusBorder
-import com.streamvault.app.ui.theme.LocalSpacing
-import com.streamvault.app.ui.theme.Primary
-import com.streamvault.app.ui.theme.SurfaceElevated
-import com.streamvault.app.ui.theme.TextPrimary
-import com.streamvault.app.ui.theme.TextSecondary
-import com.streamvault.app.ui.theme.TextTertiary
-
-@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
-@Composable
-fun TopNavBar(
- currentRoute: String,
- onNavigate: (String) -> Unit,
- modifier: Modifier = Modifier
-) {
- val tabs = listOf(
- NavTab(stringResource(id = R.string.nav_home), Routes.HOME),
- NavTab(stringResource(id = R.string.nav_live_tv), Routes.LIVE_TV),
- NavTab(stringResource(id = R.string.nav_movies), Routes.MOVIES),
- NavTab(stringResource(id = R.string.nav_series), Routes.SERIES),
- NavTab(stringResource(id = R.string.nav_epg), Routes.EPG),
- NavTab(stringResource(id = R.string.nav_settings), Routes.SETTINGS)
- )
- val subtitle = when (currentRoute) {
- Routes.FAVORITES -> stringResource(id = R.string.favorites_title)
- Routes.SEARCH -> stringResource(id = R.string.search_title)
- else -> tabs.firstOrNull { it.route == currentRoute }?.label ?: stringResource(id = R.string.app_name)
- }
-
- val focusRequesters = remember { mutableMapOf<String, FocusRequester>() }
-
- Row(
- modifier = modifier
- .fillMaxWidth()
- .height(82.dp)
- .padding(horizontal = LocalSpacing.current.safeHoriz)
- .focusProperties {
- enter = {
- val activeTabRoute = tabs.firstOrNull { it.route == currentRoute }?.route
- focusRequesters[activeTabRoute] ?: FocusRequester.Default
- }
- },
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.SpaceBetween
- ) {
- Column {
- Text(
- text = stringResource(id = R.string.app_name),
- style = MaterialTheme.typography.titleLarge,
- color = AppColors.TextPrimary
- )
- Text(
- text = subtitle,
- style = MaterialTheme.typography.labelSmall,
- color = AppColors.TextTertiary
- )
- }
-
- Spacer(modifier = Modifier.width(LocalSpacing.current.md))
-
- Row(horizontalArrangement = Arrangement.spacedBy(LocalSpacing.current.sm)) {
- tabs.forEach { tab ->
- val requester = focusRequesters.getOrPut(tab.route) { FocusRequester() }
- NavTabButton(
- text = tab.label,
- isSelected = currentRoute == tab.route,
- modifier = Modifier.focusRequester(requester),
- onClick = {
- if (currentRoute != tab.route) {
- onNavigate(tab.route)
- }
- }
- )
- }
- }
- }
-}
-
-@Composable
-private fun NavTabButton(
- text: String,
- isSelected: Boolean,
- modifier: Modifier = Modifier,
- onClick: () -> Unit
-) {
- var isFocused by remember { mutableStateOf(false) }
-
- val scale by animateFloatAsState(
- targetValue = if (isFocused) FocusSpec.FocusedScale else 1f,
- animationSpec = tween(durationMillis = 160),
- label = "tabScale"
- )
-
- val textColor = when {
- isSelected -> AppColors.Brand
- isFocused -> AppColors.TextPrimary
- else -> AppColors.TextSecondary
- }
-
- Surface(
- onClick = onClick,
- modifier = modifier
- .graphicsLayer {
- scaleX = scale
- scaleY = scale
- }
- .onFocusChanged { isFocused = it.isFocused },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (isSelected) AppColors.BrandMuted else SurfaceElevated,
- focusedContainerColor = AppColors.SurfaceEmphasis
- ),
- border = ClickableSurfaceDefaults.border(
- border = Border(
- border = BorderStroke(1.dp, AppColors.Outline),
- shape = RoundedCornerShape(12.dp)
- ),
- focusedBorder = Border(
- border = BorderStroke(2.dp, FocusBorder),
- shape = RoundedCornerShape(12.dp)
- )
- )
- ) {
- Column(
- modifier = Modifier.padding(horizontal = 22.dp, vertical = 10.dp),
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(3.dp)
- ) {
- Text(
- text = text,
- style = MaterialTheme.typography.titleSmall,
- color = textColor
- )
- Box(
- modifier = Modifier
- .width(28.dp)
- .height(3.dp)
- .background(
- color = if (isSelected) Primary else if (isFocused) FocusBorder else AppColors.Outline,
- shape = RoundedCornerShape(999.dp)
- )
- )
- }
- }
-}
-
-private data class NavTab(
- val label: String,
- val route: String
-)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/TvEmptyState.kt b/app/src/main/java/com/streamvault/app/ui/components/TvEmptyState.kt
index 60a7ff2b..03d2cb57 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/TvEmptyState.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/TvEmptyState.kt
@@ -18,6 +18,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Text
+import com.streamvault.app.ui.components.shell.AppMessageState
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
@@ -31,42 +32,23 @@ fun TvEmptyState(
modifier = modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
- Box(
- modifier = Modifier
- .fillMaxWidth(0.62f)
- .background(
- Brush.horizontalGradient(
- listOf(
- Color.White.copy(alpha = 0.05f),
- Color.White.copy(alpha = 0.02f)
- )
- ),
- RoundedCornerShape(24.dp)
+ AppMessageState(
+ title = title,
+ subtitle = subtitle,
+ modifier = Modifier.fillMaxWidth(0.62f),
+ containerBrush = Brush.horizontalGradient(
+ listOf(
+ Color.White.copy(alpha = 0.05f),
+ Color.White.copy(alpha = 0.02f)
)
- .border(
- width = 1.dp,
- color = Color.White.copy(alpha = 0.08f),
- shape = RoundedCornerShape(24.dp)
- )
- ) {
- Column(
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(12.dp),
- modifier = Modifier.padding(horizontal = 32.dp, vertical = 28.dp)
- ) {
- Text(
- text = title,
- style = MaterialTheme.typography.headlineMedium,
- color = OnSurface,
- textAlign = TextAlign.Center
- )
- Text(
- text = subtitle,
- style = MaterialTheme.typography.bodyMedium,
- color = OnSurfaceDim,
- textAlign = TextAlign.Center
- )
- }
- }
+ ),
+ borderColor = Color.White.copy(alpha = 0.08f),
+ titleStyle = androidx.tv.material3.MaterialTheme.typography.headlineMedium,
+ subtitleStyle = androidx.tv.material3.MaterialTheme.typography.bodyMedium,
+ titleColor = OnSurface,
+ subtitleColor = OnSurfaceDim,
+ titleTextAlign = androidx.compose.ui.text.style.TextAlign.Center,
+ subtitleTextAlign = androidx.compose.ui.text.style.TextAlign.Center
+ )
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt
index 251b896d..b4e7e47e 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt
@@ -10,7 +10,6 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Star
-import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -29,9 +28,7 @@ import androidx.compose.ui.input.key.*
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.foundation.shape.CircleShape
import kotlinx.coroutines.delay
-import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialog
-import com.streamvault.app.ui.screens.multiview.MultiViewViewModel
-import androidx.hilt.navigation.compose.hiltViewModel
+import androidx.tv.material3.*
@Composable
fun AddToGroupDialog(
@@ -45,41 +42,22 @@ fun AddToGroupDialog(
onAddToGroup: (Category) -> Unit,
onRemoveFromGroup: (Category) -> Unit,
onCreateGroup: (String) -> Unit,
- onNavigateToSplitScreen: (() -> Unit)? = null // navigate to MultiViewScreen when launched
+ isQueuedForSplitScreen: Boolean = false,
+ onOpenSplitScreenPlanner: (() -> Unit)? = null
) {
var showCreateGroup by remember { mutableStateOf(false) }
- val focusRequester = remember { FocusRequester() }
+ val contentFocusRequester = remember { FocusRequester() } // focuses first interactive item, not close button
// Ghost-click debounce
var canInteract by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
- focusRequester.requestFocus()
+ runCatching { contentFocusRequester.requestFocus() }
delay(500)
canInteract = true
}
val safeDismiss = { if (canInteract) onDismiss() }
- // Split screen state
- val multiViewViewModel: MultiViewViewModel = hiltViewModel()
- val slots by multiViewViewModel.slotsFlow.collectAsState()
- val isQueued = channel != null && multiViewViewModel.isQueued(channel.id)
- var showSlotPicker by remember { mutableStateOf(false) }
-
- // Show slot-picker dialog when user taps the split screen button
- if (showSlotPicker && channel != null) {
- MultiViewPlannerDialog(
- pendingChannel = channel,
- onDismiss = { showSlotPicker = false },
- onLaunch = {
- showSlotPicker = false
- onDismiss()
- onNavigateToSplitScreen?.invoke()
- },
- viewModel = multiViewViewModel
- )
- }
-
if (showCreateGroup) {
CreateGroupDialog(
onDismissRequest = { showCreateGroup = false },
@@ -90,14 +68,14 @@ fun AddToGroupDialog(
)
}
- if (!showCreateGroup && !showSlotPicker) {
+ if (!showCreateGroup) {
Dialog(
onDismissRequest = safeDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Surface(
shape = RoundedCornerShape(16.dp),
- color = AppColors.SurfaceElevated,
+ colors = SurfaceDefaults.colors(containerColor = AppColors.SurfaceElevated),
modifier = Modifier
.width(400.dp)
.padding(16.dp)
@@ -116,8 +94,7 @@ fun AddToGroupDialog(
modifier = Modifier.weight(1f)
)
IconButton(
- onClick = safeDismiss,
- modifier = Modifier.focusRequester(focusRequester)
+ onClick = safeDismiss
) {
Icon(Icons.Default.Close, contentDescription = stringResource(R.string.add_group_close_cd))
}
@@ -134,6 +111,7 @@ fun AddToGroupDialog(
onClick = onToggleFavorite,
modifier = Modifier
.fillMaxWidth()
+ .focusRequester(contentFocusRequester)
.onFocusChanged { isFocused = it.isFocused }
.background(
color = if (isFocused) AppColors.Focus else Color.Transparent,
@@ -144,7 +122,7 @@ fun AddToGroupDialog(
if (isFocused) AppColors.Focus else Color.Transparent,
CircleShape
),
- colors = ButtonDefaults.buttonColors(
+ colors = ButtonDefaults.colors(
containerColor = when {
isFocused -> AppColors.Focus
isFavorite -> AppColors.Warning
@@ -169,11 +147,11 @@ fun AddToGroupDialog(
}
// ── Split Screen ─────────────────────────────
- if (channel != null) {
+ if (channel != null && onOpenSplitScreenPlanner != null) {
item {
var isFocused by remember { mutableStateOf(false) }
Button(
- onClick = { showSlotPicker = true },
+ onClick = onOpenSplitScreenPlanner,
modifier = Modifier
.fillMaxWidth()
.onFocusChanged { isFocused = it.isFocused }
@@ -186,10 +164,10 @@ fun AddToGroupDialog(
if (isFocused) AppColors.Focus else Color.Transparent,
CircleShape
),
- colors = ButtonDefaults.buttonColors(
+ colors = ButtonDefaults.colors(
containerColor = when {
isFocused -> AppColors.Focus
- isQueued -> AppColors.Success.copy(alpha = 0.8f)
+ isQueuedForSplitScreen -> AppColors.Success.copy(alpha = 0.8f)
else -> AppColors.Success
}
)
@@ -201,7 +179,7 @@ fun AddToGroupDialog(
)
Spacer(modifier = Modifier.width(8.dp))
Text(
- text = if (isQueued) stringResource(R.string.multiview_queued)
+ text = if (isQueuedForSplitScreen) stringResource(R.string.multiview_queued)
else stringResource(R.string.multiview_add_to_split),
color = if (isFocused) Color.Black else Color.White
)
@@ -211,7 +189,13 @@ fun AddToGroupDialog(
// ── Custom Groups Section ─────────────────────
item {
- HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 8.dp)
+ .height(1.dp)
+ .background(AppColors.SurfaceAccent.copy(alpha = 0.7f))
+ )
Text(
text = stringResource(R.string.add_group_custom_groups_title),
style = MaterialTheme.typography.titleMedium,
@@ -251,7 +235,7 @@ fun AddToGroupDialog(
if (isFocused) AppColors.Focus else Color.Transparent,
CircleShape
),
- colors = ButtonDefaults.buttonColors(
+ colors = ButtonDefaults.colors(
containerColor = when {
isFocused -> AppColors.Focus
isMember -> AppColors.Live.copy(alpha = 0.2f)
@@ -285,7 +269,7 @@ fun AddToGroupDialog(
if (isFocused) AppColors.Focus else AppColors.BrandMuted.copy(alpha = 0.55f),
CircleShape
),
- colors = ButtonDefaults.outlinedButtonColors(
+ colors = ButtonDefaults.colors(
containerColor = if (isFocused) AppColors.Focus else Color.Transparent,
contentColor = if (isFocused) Color.Black else AppColors.TextPrimary
)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt
index f38c774f..6f46c652 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt
@@ -47,12 +47,15 @@ fun CreateGroupDialog(
onConfirm: (String) -> Unit
) {
var value by rememberSaveable { mutableStateOf("") }
+ var canInteract by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
val keyboardController = LocalSoftwareKeyboardController.current
LaunchedEffect(Unit) {
runCatching { focusRequester.requestFocus() }
keyboardController?.show()
+ kotlinx.coroutines.delay(500)
+ canInteract = true
}
Dialog(
@@ -126,8 +129,10 @@ fun CreateGroupDialog(
) {
Button(
onClick = {
- keyboardController?.hide()
- onDismissRequest()
+ if (canInteract) {
+ keyboardController?.hide()
+ onDismissRequest()
+ }
},
colors = ButtonDefaults.colors(
containerColor = Color.White.copy(alpha = 0.08f),
@@ -139,12 +144,12 @@ fun CreateGroupDialog(
Button(
onClick = {
val normalized = value.trim()
- if (normalized.isNotEmpty()) {
+ if (canInteract && normalized.isNotEmpty()) {
keyboardController?.hide()
onConfirm(normalized)
}
},
- enabled = value.trim().isNotEmpty(),
+ enabled = canInteract && value.trim().isNotEmpty(),
colors = ButtonDefaults.colors(
containerColor = Primary,
contentColor = Color.White
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
index 1ac53456..af88a330 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
@@ -5,9 +5,10 @@ import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.foundation.text.BasicTextField
-import androidx.compose.foundation.text.KeyboardOptions
-import androidx.compose.material3.*
+import androidx.tv.material3.Button
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -15,19 +16,24 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.platform.LocalSoftwareKeyboardController
-import androidx.compose.ui.text.input.KeyboardType
-import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.streamvault.app.ui.theme.ErrorColor
+import com.streamvault.app.ui.theme.FocusBorder
import com.streamvault.app.ui.theme.Primary
import com.streamvault.app.ui.theme.SurfaceElevated
import kotlinx.coroutines.delay
import androidx.compose.ui.res.stringResource
import com.streamvault.app.R
+import com.streamvault.app.ui.design.FocusSpec
+import androidx.tv.material3.Border
+/**
+ * PIN entry dialog with a D-pad-navigable numeric keypad — no hidden text field.
+ * Each digit button is a full TV-focusable surface, so users can navigate with
+ * the remote directional pad even without a software keyboard.
+ */
@Composable
fun PinDialog(
onDismissRequest: () -> Unit,
@@ -36,34 +42,31 @@ fun PinDialog(
error: String? = null
) {
var pin by remember { mutableStateOf("") }
- val focusRequester = remember { FocusRequester() }
- val keyboardController = LocalSoftwareKeyboardController.current
+ var canInteract by remember { mutableStateOf(false) }
+ val firstKeyFocusRequester = remember { FocusRequester() }
LaunchedEffect(Unit) {
- focusRequester.requestFocus()
- keyboardController?.show()
+ runCatching { firstKeyFocusRequester.requestFocus() }
+ delay(500)
+ canInteract = true
}
-
- // Auto-submit when length reaches 4
+
+ // Auto-submit when all 4 digits entered
LaunchedEffect(pin) {
if (pin.length == 4) {
- delay(300) // Small delay for visual feedback
- keyboardController?.hide()
+ delay(200)
onPinEntered(pin)
- pin = "" // Reset logic usually handled by parent state (error or dismiss)
+ pin = ""
}
}
Dialog(
- onDismissRequest = {
- keyboardController?.hide()
- onDismissRequest()
- },
+ onDismissRequest = { if (canInteract) onDismissRequest() },
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Box(
modifier = Modifier
- .width(320.dp)
+ .width(360.dp)
.background(SurfaceElevated, RoundedCornerShape(16.dp))
.border(1.dp, Color.White.copy(alpha = 0.1f), RoundedCornerShape(16.dp))
.padding(24.dp),
@@ -71,7 +74,7 @@ fun PinDialog(
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(24.dp)
+ verticalArrangement = Arrangement.spacedBy(20.dp)
) {
Text(
text = title ?: stringResource(R.string.pin_dialog_title),
@@ -79,7 +82,7 @@ fun PinDialog(
color = Color.White
)
- // PIN Dots
+ // PIN dot indicators
Row(
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically
@@ -90,14 +93,8 @@ fun PinDialog(
modifier = Modifier
.size(20.dp)
.clip(CircleShape)
- .background(
- if (isFilled) Primary else Color.White.copy(alpha = 0.1f)
- )
- .border(
- 1.dp,
- if (isFilled) Primary else Color.White.copy(alpha = 0.3f),
- CircleShape
- )
+ .background(if (isFilled) Primary else Color.White.copy(alpha = 0.1f))
+ .border(1.dp, if (isFilled) Primary else Color.White.copy(alpha = 0.3f), CircleShape)
)
}
}
@@ -110,28 +107,68 @@ fun PinDialog(
)
}
- // Hidden text field to capture input overlays everything but is invisible
- // We use a small size to ensure it doesn't displace layout but is focusable
- BasicTextField(
- value = pin,
- onValueChange = {
- if (it.length <= 4 && it.all { char -> char.isDigit() }) {
- pin = it
+ // D-pad numeric keypad: 1–9, then [blank] 0 [⌫]
+ val keys = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "", "0", "⌫")
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ keys.chunked(3).forEach { row ->
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ row.forEach { key ->
+ val isFirst = key == "1"
+ Box(modifier = Modifier.weight(1f)) {
+ if (key.isEmpty()) {
+ Spacer(modifier = Modifier.fillMaxWidth().height(48.dp))
+ } else {
+ Button(
+ onClick = {
+ if (!canInteract) return@Button
+ if (key == "⌫") {
+ if (pin.isNotEmpty()) pin = pin.dropLast(1)
+ } else if (pin.length < 4) {
+ pin += key
+ }
+ },
+ modifier = Modifier
+ .fillMaxWidth()
+ .then(if (isFirst) Modifier.focusRequester(firstKeyFocusRequester) else Modifier),
+ colors = ButtonDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.08f),
+ contentColor = Color.White,
+ focusedContainerColor = Primary.copy(alpha = 0.35f),
+ focusedContentColor = Color.White
+ )
+ ) {
+ Text(
+ text = key,
+ style = MaterialTheme.typography.titleMedium
+ )
+ }
+ }
+ }
+ }
}
- },
- modifier = Modifier
- .size(1.dp)
- .focusRequester(focusRequester),
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
- visualTransformation = PasswordVisualTransformation()
- )
-
- // Cancel Button
- TextButton(onClick = {
- keyboardController?.hide()
- onDismissRequest()
- }) {
- Text(stringResource(R.string.pin_dialog_cancel), color = Color.White.copy(alpha = 0.7f))
+ }
+ }
+
+ // Cancel
+ Button(
+ onClick = { if (canInteract) onDismissRequest() },
+ colors = ButtonDefaults.colors(
+ containerColor = Color.Transparent,
+ contentColor = Color.White.copy(alpha = 0.7f),
+ focusedContainerColor = Color.White.copy(alpha = 0.12f),
+ focusedContentColor = Color.White
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = androidx.compose.foundation.BorderStroke(FocusSpec.BorderWidth, FocusBorder)
+ )
+ ),
+ scale = ButtonDefaults.scale(focusedScale = FocusSpec.FocusedScale)
+ ) {
+ Text(stringResource(R.string.pin_dialog_cancel))
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt
index 8438e9ce..5a576e68 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt
@@ -11,7 +11,13 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
+import kotlinx.coroutines.delay
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@@ -36,8 +42,10 @@ fun PremiumDialog(
content: @Composable ColumnScope.() -> Unit,
footer: @Composable RowScope.() -> Unit = {}
) {
+ var canInteract by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) { delay(500); canInteract = true }
Dialog(
- onDismissRequest = onDismissRequest,
+ onDismissRequest = { if (canInteract) onDismissRequest() },
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Surface(
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt
index 5eaf1940..84108194 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt
@@ -16,17 +16,20 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
-import androidx.compose.material3.Icon
-import androidx.compose.material3.IconButton
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Surface
-import androidx.compose.material3.Text
+import androidx.tv.material3.Icon
+import androidx.tv.material3.IconButton
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.SurfaceDefaults
+import androidx.tv.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
+import kotlinx.coroutines.delay
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
@@ -40,7 +43,9 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.streamvault.app.R
import com.streamvault.domain.model.Program
-import java.text.SimpleDateFormat
+import java.time.Instant
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
import java.util.Locale
@Composable
@@ -50,17 +55,22 @@ fun ProgramHistoryDialog(
onProgramSelect: (Program) -> Unit
) {
val focusRequester = remember { FocusRequester() }
- val timeFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
- val dayFormat = remember { SimpleDateFormat("EEE, MMM d", Locale.getDefault()) }
+ var canInteract by remember { mutableStateOf(false) }
+ val locale = Locale.getDefault()
+ val zoneId = remember { ZoneId.systemDefault() }
+ val timeFormat = remember(locale) { DateTimeFormatter.ofPattern("HH:mm", locale) }
+ val dayFormat = remember(locale) { DateTimeFormatter.ofPattern("EEE, MMM d", locale) }
LaunchedEffect(Unit) {
- focusRequester.requestFocus()
+ runCatching { focusRequester.requestFocus() }
+ delay(500)
+ canInteract = true
}
- Dialog(onDismissRequest = onDismiss) {
+ Dialog(onDismissRequest = { if (canInteract) onDismiss() }) {
Surface(
shape = RoundedCornerShape(16.dp),
- color = MaterialTheme.colorScheme.surface,
+ colors = SurfaceDefaults.colors(containerColor = MaterialTheme.colorScheme.surface),
modifier = Modifier
.width(450.dp)
.heightIn(max = 600.dp)
@@ -100,6 +110,8 @@ fun ProgramHistoryDialog(
)
}
} else {
+ val unfocusedBorderColor = Color.White.copy(alpha = 0.12f)
+ val focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant
LazyColumn(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(8.dp)
@@ -108,24 +120,29 @@ fun ProgramHistoryDialog(
var isFocused by remember { mutableStateOf(false) }
Surface(
- onClick = { onProgramSelect(program) },
+ onClick = { if (canInteract) onProgramSelect(program) },
modifier = Modifier
.fillMaxWidth()
.onFocusChanged { isFocused = it.isFocused }
- .focusRequester(
- if (program == programs.first()) focusRequester else FocusRequester()
+ .then(
+ if (program == programs.first())
+ Modifier.focusRequester(focusRequester)
+ else Modifier
)
.border(
width = if (isFocused) 2.dp else 1.dp,
color = if (isFocused) {
MaterialTheme.colorScheme.primary
} else {
- MaterialTheme.colorScheme.outlineVariant
+ unfocusedBorderColor
},
shape = RoundedCornerShape(8.dp)
),
- shape = RoundedCornerShape(8.dp),
- color = if (isFocused) MaterialTheme.colorScheme.surfaceVariant else Color.Transparent
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.Transparent,
+ focusedContainerColor = focusedContainerColor
+ )
) {
Row(
modifier = Modifier.padding(12.dp),
@@ -140,7 +157,12 @@ fun ProgramHistoryDialog(
overflow = TextOverflow.Ellipsis
)
Text(
- text = stringResource(R.string.program_date_time_range, dayFormat.format(program.startTime), timeFormat.format(program.startTime), timeFormat.format(program.endTime)),
+ text = stringResource(
+ R.string.program_date_time_range,
+ Instant.ofEpochMilli(program.startTime).atZone(zoneId).format(dayFormat),
+ Instant.ofEpochMilli(program.startTime).atZone(zoneId).format(timeFormat),
+ Instant.ofEpochMilli(program.endTime).atZone(zoneId).format(timeFormat)
+ ),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt
index 9a3c33c0..b026c096 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt
@@ -1,32 +1,46 @@
package com.streamvault.app.ui.components.dialogs
import androidx.compose.foundation.background
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
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.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
+import kotlinx.coroutines.delay
+import androidx.compose.foundation.BorderStroke
import androidx.tv.material3.Button
import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.Border
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
+import com.streamvault.app.ui.design.FocusSpec
import com.streamvault.app.R
+import com.streamvault.app.ui.theme.FocusBorder
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
@@ -40,9 +54,24 @@ fun RenameGroupDialog(
onConfirm: (String) -> Unit
) {
var value by rememberSaveable(initialName) { mutableStateOf(initialName) }
+ var canInteract by remember { mutableStateOf(false) }
+ val focusRequester = remember { FocusRequester() }
+ val keyboardController = LocalSoftwareKeyboardController.current
+
+ LaunchedEffect(Unit) {
+ runCatching { focusRequester.requestFocus() }
+ keyboardController?.show()
+ delay(500)
+ canInteract = true
+ }
Dialog(
- onDismissRequest = onDismissRequest,
+ onDismissRequest = {
+ if (canInteract) {
+ keyboardController?.hide()
+ onDismissRequest()
+ }
+ },
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Surface(
@@ -76,9 +105,32 @@ fun RenameGroupDialog(
OutlinedTextField(
value = value,
onValueChange = { value = it },
- modifier = Modifier.fillMaxWidth(),
+ modifier = Modifier
+ .fillMaxWidth()
+ .focusRequester(focusRequester),
singleLine = true,
label = { Text(stringResource(R.string.add_group_name_hint)) },
+ colors = OutlinedTextFieldDefaults.colors(
+ focusedTextColor = OnSurface,
+ unfocusedTextColor = OnSurface,
+ cursorColor = Primary,
+ focusedBorderColor = Primary,
+ unfocusedBorderColor = Primary.copy(alpha = 0.55f),
+ focusedLabelColor = Primary,
+ unfocusedLabelColor = OnSurfaceDim,
+ focusedContainerColor = Color.Transparent,
+ unfocusedContainerColor = Color.Transparent
+ ),
+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
+ keyboardActions = KeyboardActions(
+ onDone = {
+ val normalized = value.trim()
+ if (canInteract && normalized.isNotEmpty()) {
+ keyboardController?.hide()
+ onConfirm(normalized)
+ }
+ }
+ ),
supportingText = errorMessage?.let { message ->
{ Text(message) }
}
@@ -88,20 +140,48 @@ fun RenameGroupDialog(
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Button(
- onClick = onDismissRequest,
+ onClick = {
+ if (canInteract) {
+ keyboardController?.hide()
+ onDismissRequest()
+ }
+ },
colors = ButtonDefaults.colors(
containerColor = Color.White.copy(alpha = 0.08f),
- contentColor = OnSurface
- )
+ contentColor = OnSurface,
+ focusedContainerColor = Color.White.copy(alpha = 0.16f),
+ focusedContentColor = OnSurface
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder)
+ )
+ ),
+ scale = ButtonDefaults.scale(focusedScale = FocusSpec.FocusedScale)
) {
Text(stringResource(R.string.add_group_cancel))
}
Button(
- onClick = { onConfirm(value) },
+ onClick = {
+ val normalized = value.trim()
+ if (canInteract && normalized.isNotEmpty()) {
+ keyboardController?.hide()
+ onConfirm(normalized)
+ }
+ },
+ enabled = canInteract && value.trim().isNotEmpty(),
colors = ButtonDefaults.colors(
containerColor = Primary,
- contentColor = Color.White
- )
+ contentColor = Color.White,
+ focusedContainerColor = Primary.copy(alpha = 0.84f),
+ focusedContentColor = Color.White
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder)
+ )
+ ),
+ scale = ButtonDefaults.scale(focusedScale = FocusSpec.FocusedScale)
) {
Text(stringResource(R.string.add_group_rename))
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
index 14464a2a..c8ddfab5 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
@@ -19,8 +19,10 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
+import kotlinx.coroutines.delay
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -40,6 +42,7 @@ import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import coil3.compose.AsyncImage
import com.streamvault.app.R
+import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.design.AppMotion
import com.streamvault.app.ui.design.FocusSpec
@@ -62,6 +65,13 @@ fun LiveChannelRowCard(
val logoPadding = if (isDense) 5.dp else if (isUltraCompact) 6.dp else 8.dp
val contentSpacing = if (isUltraCompact) 8.dp else 10.dp
val badgeSpacing = if (isUltraCompact) 3.dp else 4.dp
+ // Ticks every 30s so EPG progress bars stay accurate without busy-looping
+ val nowMs by produceState(initialValue = System.currentTimeMillis()) {
+ while (true) {
+ delay(30_000L)
+ value = System.currentTimeMillis()
+ }
+ }
Box(
modifier = modifier
@@ -85,21 +95,21 @@ fun LiveChannelRowCard(
.background(AppColors.SurfaceEmphasis),
contentAlignment = Alignment.Center
) {
+ // Fallback initials always visible; covered by AsyncImage on successful load
+ Text(
+ text = channel.name.take(2).uppercase(),
+ style = MaterialTheme.typography.titleLarge,
+ color = AppColors.TextSecondary
+ )
if (!channel.logoUrl.isNullOrBlank()) {
AsyncImage(
- model = channel.logoUrl,
+ model = rememberCrossfadeImageModel(channel.logoUrl),
contentDescription = channel.name,
modifier = Modifier
.fillMaxSize()
.padding(logoPadding),
contentScale = ContentScale.Fit
)
- } else {
- Text(
- text = channel.name.take(2).uppercase(),
- style = MaterialTheme.typography.titleLarge,
- color = AppColors.TextSecondary
- )
}
}
Column(
@@ -142,7 +152,7 @@ fun LiveChannelRowCard(
overflow = TextOverflow.Ellipsis
)
val totalDuration = (program.endTime - program.startTime).coerceAtLeast(1L)
- val elapsed = (System.currentTimeMillis() - program.startTime).coerceAtLeast(0L)
+ val elapsed = (nowMs - program.startTime).coerceAtLeast(0L)
if (!isDense) {
LinearProgressIndicator(
progress = { (elapsed.toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f) },
@@ -284,6 +294,12 @@ fun EpisodeRowCard(episode: Episode, modifier: Modifier = Modifier) {
.background(AppColors.SurfaceEmphasis),
contentAlignment = Alignment.Center
) {
+ // Fallback label always visible; covered by AsyncImage on successful load
+ Text(
+ text = stringResource(R.string.label_episode, episode.episodeNumber),
+ style = MaterialTheme.typography.titleMedium,
+ color = AppColors.TextSecondary
+ )
if (!episode.coverUrl.isNullOrBlank()) {
AsyncImage(
model = episode.coverUrl,
@@ -291,12 +307,6 @@ fun EpisodeRowCard(episode: Episode, modifier: Modifier = Modifier) {
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
- } else {
- Text(
- text = stringResource(R.string.label_episode, episode.episodeNumber),
- style = MaterialTheme.typography.titleMedium,
- color = AppColors.TextSecondary
- )
}
}
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
@@ -308,7 +318,7 @@ fun EpisodeRowCard(episode: Episode, modifier: Modifier = Modifier) {
overflow = TextOverflow.Ellipsis
)
ContentMetadataStrip(
- values = listOf("Episode ${episode.episodeNumber}", episode.duration ?: "")
+ values = listOf(stringResource(R.string.label_episode_full, episode.episodeNumber), episode.duration ?: "")
)
episode.plot?.takeIf { it.isNotBlank() }?.let { plot ->
Text(
@@ -331,33 +341,35 @@ private fun PosterCard(
subtitle: String?,
modifier: Modifier = Modifier
) {
+ val posterShape = RoundedCornerShape(20.dp)
+
Box(
modifier = modifier
- .clip(RoundedCornerShape(20.dp))
+ .clip(posterShape)
.background(AppColors.SurfaceElevated)
) {
+ // Fallback always visible; covered by AsyncImage on successful load
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(AppColors.SurfaceEmphasis),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = title.take(1).uppercase(),
+ style = MaterialTheme.typography.displaySmall,
+ color = AppColors.TextSecondary
+ )
+ }
if (!imageUrl.isNullOrBlank()) {
AsyncImage(
- model = imageUrl,
+ model = rememberCrossfadeImageModel(imageUrl),
contentDescription = title,
modifier = Modifier
.fillMaxSize()
- .clip(RoundedCornerShape(12.dp)),
+ .clip(posterShape),
contentScale = ContentScale.Fit
)
- } else {
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(AppColors.SurfaceEmphasis),
- contentAlignment = Alignment.Center
- ) {
- Text(
- text = title.take(1).uppercase(),
- style = MaterialTheme.typography.displaySmall,
- color = AppColors.TextSecondary
- )
- }
}
Box(
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
index 6a65e766..449d3dcc 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
@@ -50,7 +50,10 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
@@ -64,6 +67,7 @@ import com.streamvault.app.navigation.Routes
import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.design.AppMotion
import com.streamvault.app.ui.design.FocusSpec
+import com.streamvault.app.ui.design.LocalAppShapes
import com.streamvault.app.ui.design.LocalAppSpacing
enum class AppNavigationChrome {
@@ -231,7 +235,7 @@ private fun TopNavigationBar(
onNavigate: (String) -> Unit,
modifier: Modifier = Modifier
) {
- val items = buildDestinationItems()
+ val items = remember { buildDestinationItems() }
val scrollState = rememberScrollState()
val focusRequesters = remember { mutableMapOf<String, FocusRequester>() }
@@ -273,10 +277,10 @@ private fun TopNavigationBar(
TopNavigationButton(
label = stringResource(item.labelRes),
icon = item.icon,
- selected = currentRoute == item.route,
+ selected = currentRoute.startsWith(item.route),
modifier = Modifier.focusRequester(requester),
onClick = {
- if (currentRoute != item.route) {
+ if (!currentRoute.startsWith(item.route)) {
onNavigate(item.route)
}
}
@@ -364,9 +368,9 @@ fun AppHeroHeader(
.background(
Brush.horizontalGradient(
colors = listOf(
- Color(0xFF081624),
- Color(0xFF10223A),
- Color(0xFF18314E)
+ AppColors.Canvas,
+ AppColors.SurfaceAccent,
+ AppColors.SurfaceEmphasis
)
)
)
@@ -397,23 +401,51 @@ fun AppHeroHeader(
fun AppSectionHeader(
title: String,
subtitle: String? = null,
- modifier: Modifier = Modifier
+ modifier: Modifier = Modifier,
+ actionLabel: String? = null,
+ onActionClick: (() -> Unit)? = null,
+ actionContentColor: Color = AppColors.TextTertiary
) {
- Column(
+ val shapes = LocalAppShapes.current
+ Row(
modifier = modifier,
- verticalArrangement = Arrangement.spacedBy(4.dp)
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
) {
- Text(
- text = title,
- style = MaterialTheme.typography.titleMedium,
- color = AppColors.TextPrimary
- )
- if (!subtitle.isNullOrBlank()) {
+ Column(
+ modifier = if (onActionClick != null && !actionLabel.isNullOrBlank()) Modifier.weight(1f) else Modifier,
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
Text(
- text = subtitle,
- style = MaterialTheme.typography.bodySmall,
- color = AppColors.TextTertiary
+ text = title,
+ style = MaterialTheme.typography.titleMedium,
+ color = AppColors.TextPrimary
)
+ if (!subtitle.isNullOrBlank()) {
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextTertiary
+ )
+ }
+ }
+
+ if (onActionClick != null && !actionLabel.isNullOrBlank()) {
+ Surface(
+ onClick = onActionClick,
+ shape = ClickableSurfaceDefaults.shape(shapes.pill),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = AppColors.Brand.copy(alpha = 0.12f),
+ focusedContainerColor = AppColors.Brand.copy(alpha = 0.22f),
+ contentColor = actionContentColor
+ )
+ ) {
+ Text(
+ text = actionLabel,
+ style = MaterialTheme.typography.labelSmall,
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp)
+ )
+ }
}
}
}
@@ -423,13 +455,16 @@ fun StatusPill(
label: String,
modifier: Modifier = Modifier,
containerColor: Color = AppColors.SurfaceEmphasis,
- contentColor: Color = AppColors.TextPrimary
+ contentColor: Color = AppColors.TextPrimary,
+ cornerRadius: Dp = 999.dp,
+ horizontalPadding: Dp = 10.dp,
+ verticalPadding: Dp = 4.dp
) {
Box(
modifier = modifier
- .clip(RoundedCornerShape(999.dp))
+ .clip(RoundedCornerShape(cornerRadius))
.background(containerColor)
- .padding(horizontal = 10.dp, vertical = 4.dp)
+ .padding(horizontal = horizontalPadding, vertical = verticalPadding)
) {
Text(
text = label,
@@ -444,26 +479,49 @@ fun AppMessageState(
title: String,
subtitle: String,
modifier: Modifier = Modifier,
- action: (@Composable () -> Unit)? = null
+ action: (@Composable () -> Unit)? = null,
+ shape: RoundedCornerShape? = null,
+ containerBrush: Brush? = null,
+ borderColor: Color? = null,
+ titleStyle: TextStyle = MaterialTheme.typography.titleLarge,
+ subtitleStyle: TextStyle = MaterialTheme.typography.bodySmall,
+ titleColor: Color = AppColors.TextPrimary,
+ subtitleColor: Color = AppColors.TextSecondary,
+ titleTextAlign: TextAlign = TextAlign.Start,
+ subtitleTextAlign: TextAlign = TextAlign.Start
) {
+ val resolvedShape = shape ?: LocalAppShapes.current.large
Surface(
modifier = modifier,
- shape = RoundedCornerShape(24.dp),
+ shape = resolvedShape,
+ border = Border(
+ border = BorderStroke(
+ width = if (borderColor != null) 1.dp else 0.dp,
+ color = borderColor ?: Color.Transparent
+ ),
+ shape = resolvedShape
+ ),
colors = SurfaceDefaults.colors(containerColor = AppColors.SurfaceElevated)
) {
Column(
- modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp),
+ modifier = Modifier
+ .then(if (containerBrush != null) Modifier.background(containerBrush) else Modifier)
+ .padding(horizontal = 18.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = title,
- style = MaterialTheme.typography.titleLarge,
- color = AppColors.TextPrimary
+ style = titleStyle,
+ color = titleColor,
+ textAlign = titleTextAlign,
+ modifier = Modifier.fillMaxWidth()
)
Text(
text = subtitle,
- style = MaterialTheme.typography.bodySmall,
- color = AppColors.TextSecondary
+ style = subtitleStyle,
+ color = subtitleColor,
+ textAlign = subtitleTextAlign,
+ modifier = Modifier.fillMaxWidth()
)
if (action != null) {
Spacer(modifier = Modifier.height(8.dp))
@@ -479,10 +537,11 @@ fun LoadMoreCard(
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
+ val shapes = LocalAppShapes.current
Surface(
onClick = onClick,
modifier = modifier,
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(18.dp)),
+ shape = ClickableSurfaceDefaults.shape(shapes.medium),
colors = ClickableSurfaceDefaults.colors(
containerColor = AppColors.SurfaceElevated,
focusedContainerColor = AppColors.SurfaceEmphasis
@@ -490,7 +549,7 @@ fun LoadMoreCard(
border = ClickableSurfaceDefaults.border(
focusedBorder = Border(
border = BorderStroke(FocusSpec.BorderWidth, AppColors.Focus),
- shape = RoundedCornerShape(18.dp)
+ shape = shapes.medium
)
)
) {
@@ -543,6 +602,7 @@ fun ContentMetadataStrip(
}
}
+@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
private fun DestinationRail(
currentRoute: String,
@@ -550,7 +610,8 @@ private fun DestinationRail(
modifier: Modifier = Modifier
) {
val spacing = LocalAppSpacing.current
- val items = buildDestinationItems()
+ val items = remember { buildDestinationItems() }
+ val focusRequesters = remember { mutableMapOf<String, FocusRequester>() }
Box(
modifier = modifier
@@ -564,6 +625,12 @@ private fun DestinationRail(
)
)
)
+ .focusProperties {
+ enter = {
+ val activeItem = items.firstOrNull { it.route == currentRoute }
+ focusRequesters[activeItem?.route] ?: FocusRequester.Default
+ }
+ }
) {
Column(
modifier = Modifier
@@ -583,12 +650,14 @@ private fun DestinationRail(
)
Spacer(modifier = Modifier.height(10.dp))
items.forEach { item ->
+ val requester = focusRequesters.getOrPut(item.route) { FocusRequester() }
RailButton(
label = stringResource(item.labelRes),
icon = item.icon,
- selected = currentRoute == item.route,
+ selected = currentRoute.startsWith(item.route),
+ modifier = Modifier.focusRequester(requester),
onClick = {
- if (currentRoute != item.route) {
+ if (!currentRoute.startsWith(item.route)) {
onNavigate(item.route)
}
}
@@ -603,7 +672,8 @@ private fun RailButton(
label: String,
icon: ImageVector,
selected: Boolean,
- onClick: () -> Unit
+ onClick: () -> Unit,
+ modifier: Modifier = Modifier
) {
var isFocused by remember { mutableStateOf(false) }
val scale by animateFloatAsState(
@@ -614,7 +684,7 @@ private fun RailButton(
Surface(
onClick = onClick,
- modifier = Modifier
+ modifier = modifier
.fillMaxWidth()
.graphicsLayer {
scaleX = scale
@@ -663,7 +733,6 @@ private data class DestinationItem(
val icon: ImageVector
)
-@Composable
private fun buildDestinationItems(): List<DestinationItem> = listOf(
DestinationItem(Routes.HOME, R.string.nav_home, Icons.Default.Home),
DestinationItem(Routes.LIVE_TV, R.string.nav_live_tv, Icons.Default.PlayArrow),
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/LibraryBrowseScaffold.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/LibraryBrowseScaffold.kt
index 37214e03..51b1d077 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/LibraryBrowseScaffold.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/LibraryBrowseScaffold.kt
@@ -36,6 +36,7 @@ import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import coil3.compose.AsyncImage
import com.streamvault.app.ui.components.SearchInput
+import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.design.FocusSpec
import com.streamvault.app.ui.design.LocalAppSpacing
@@ -208,27 +209,27 @@ fun BrowseHeroPanel(
)
) {
Box(modifier = Modifier.fillMaxSize()) {
+ // Gradient fallback always visible; covered by AsyncImage on successful load
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(
+ Brush.horizontalGradient(
+ colors = listOf(
+ AppColors.Canvas,
+ AppColors.CanvasElevated,
+ AppColors.SurfaceEmphasis
+ )
+ )
+ )
+ )
if (!imageUrl.isNullOrBlank()) {
AsyncImage(
- model = imageUrl,
+ model = rememberCrossfadeImageModel(imageUrl),
contentDescription = title,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
- } else {
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(
- Brush.horizontalGradient(
- colors = listOf(
- AppColors.Canvas,
- AppColors.CanvasElevated,
- AppColors.SurfaceEmphasis
- )
- )
- )
- )
}
Box(
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt
index 19b79655..ecacf695 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt
@@ -10,7 +10,6 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
-import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
@@ -20,8 +19,10 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
+import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRestorer
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -33,12 +34,14 @@ import androidx.tv.material3.Surface
import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import com.streamvault.app.ui.design.AppColors
-import com.streamvault.app.ui.theme.FocusBorder
-import com.streamvault.app.ui.theme.OnSurfaceDim
-import com.streamvault.app.ui.theme.Primary
-import com.streamvault.app.ui.theme.SurfaceElevated
-import com.streamvault.app.ui.theme.SurfaceHighlight
-import com.streamvault.app.ui.theme.TextPrimary
+import com.streamvault.app.ui.components.ChipRowItem
+import com.streamvault.app.ui.components.ChipRowSection
+import com.streamvault.app.ui.design.AppColors.Brand as Primary
+import com.streamvault.app.ui.design.AppColors.Focus as FocusBorder
+import com.streamvault.app.ui.design.AppColors.SurfaceElevated as SurfaceElevated
+import com.streamvault.app.ui.design.AppColors.SurfaceEmphasis as SurfaceHighlight
+import com.streamvault.app.ui.design.AppColors.TextPrimary as TextPrimary
+import com.streamvault.app.ui.design.AppColors.TextTertiary as OnSurfaceDim
import androidx.compose.foundation.BorderStroke
import com.streamvault.app.R
import com.streamvault.app.ui.components.SearchInput
@@ -51,90 +54,41 @@ fun VodSectionHeader(
onSeeAll: (() -> Unit)? = null,
seeAllLabel: String = stringResource(R.string.action_see_all)
) {
- Row(
+ AppSectionHeader(
+ title = title,
modifier = Modifier
.fillMaxWidth()
.padding(start = 20.dp, end = 20.dp, top = 14.dp, bottom = 8.dp),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = title,
- style = MaterialTheme.typography.titleMedium,
- color = TextPrimary
- )
- if (onSeeAll != null) {
- Surface(
- onClick = onSeeAll,
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = Primary.copy(alpha = 0.12f),
- focusedContainerColor = Primary.copy(alpha = 0.22f),
- contentColor = AppColors.TextSecondary
- )
- ) {
- Text(
- text = seeAllLabel,
- style = MaterialTheme.typography.labelSmall,
- modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp)
- )
- }
- }
- }
+ actionLabel = onSeeAll?.let { seeAllLabel },
+ onActionClick = onSeeAll,
+ actionContentColor = AppColors.TextSecondary
+ )
}
+@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun VodActionChipRow(
actions: List<VodActionChip>,
selectedKey: String? = null,
modifier: Modifier = Modifier
) {
- LazyRow(
- modifier = modifier.fillMaxWidth(),
+ ChipRowSection(
+ chips = actions.map { action ->
+ ChipRowItem(
+ key = action.key,
+ label = action.label,
+ supportingText = action.detail,
+ onClick = action.onClick
+ )
+ },
+ selectedKey = selectedKey,
+ modifier = modifier.focusRestorer(),
contentPadding = PaddingValues(horizontal = 20.dp),
- horizontalArrangement = Arrangement.spacedBy(10.dp)
- ) {
- items(actions, key = { it.key }) { action ->
- val isSelected = selectedKey == action.key
- Surface(
- onClick = action.onClick,
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
- focusedContainerColor = if (isSelected) Primary.copy(alpha = 0.28f) else SurfaceHighlight
- ),
- border = ClickableSurfaceDefaults.border(
- focusedBorder = Border(
- border = BorderStroke(2.dp, FocusBorder),
- shape = RoundedCornerShape(999.dp)
- )
- ),
- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
- ) {
- Column(
- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
- verticalArrangement = Arrangement.spacedBy(2.dp)
- ) {
- Text(
- text = action.label,
- style = MaterialTheme.typography.labelLarge,
- color = if (isSelected) Primary else TextPrimary,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- action.detail?.takeIf { it.isNotBlank() }?.let {
- Text(
- text = it,
- style = MaterialTheme.typography.labelSmall,
- color = OnSurfaceDim,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- }
- }
- }
- }
- }
+ chipHorizontalPadding = 14,
+ supportingTextStyle = MaterialTheme.typography.labelSmall,
+ supportingTextMaxLines = 1,
+ focusedContainerBoostWhenSelected = true
+ )
}
@Composable
diff --git a/app/src/main/java/com/streamvault/app/ui/design/AppShapes.kt b/app/src/main/java/com/streamvault/app/ui/design/AppShapes.kt
index 29b2d497..e11d2712 100644
--- a/app/src/main/java/com/streamvault/app/ui/design/AppShapes.kt
+++ b/app/src/main/java/com/streamvault/app/ui/design/AppShapes.kt
@@ -8,6 +8,8 @@ data class AppShapes(
val small: RoundedCornerShape = RoundedCornerShape(12.dp),
val medium: RoundedCornerShape = RoundedCornerShape(18.dp),
val large: RoundedCornerShape = RoundedCornerShape(24.dp),
+ val xSmall: RoundedCornerShape = RoundedCornerShape(8.dp),
+ val xLarge: RoundedCornerShape = RoundedCornerShape(28.dp),
val pill: RoundedCornerShape = RoundedCornerShape(999.dp)
)
diff --git a/app/src/main/java/com/streamvault/app/ui/design/AppSpacing.kt b/app/src/main/java/com/streamvault/app/ui/design/AppSpacing.kt
index 2257fed7..b5465e75 100644
--- a/app/src/main/java/com/streamvault/app/ui/design/AppSpacing.kt
+++ b/app/src/main/java/com/streamvault/app/ui/design/AppSpacing.kt
@@ -17,7 +17,8 @@ data class AppSpacing(
val cardGap: Dp = 16.dp,
val chipGap: Dp = 10.dp,
val safeTop: Dp = 32.dp,
- val safeBottom: Dp = 32.dp
+ val safeBottom: Dp = 32.dp,
+ val safeHoriz: Dp = 56.dp
)
val LocalAppSpacing = staticCompositionLocalOf { AppSpacing() }
diff --git a/app/src/main/java/com/streamvault/app/ui/design/FocusHelpers.kt b/app/src/main/java/com/streamvault/app/ui/design/FocusHelpers.kt
index 7d6e6fa6..34f77da3 100644
--- a/app/src/main/java/com/streamvault/app/ui/design/FocusHelpers.kt
+++ b/app/src/main/java/com/streamvault/app/ui/design/FocusHelpers.kt
@@ -1,19 +1,18 @@
package com.streamvault.app.ui.design
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
import androidx.compose.ui.focus.FocusRequester
-
-data class FocusMemoryKey(
- val screen: String,
- val slot: String
-)
-
-@Composable
-fun rememberFocusMemoryKey(screen: String, slot: String): FocusMemoryKey {
- return remember(screen, slot) { FocusMemoryKey(screen = screen, slot = slot) }
-}
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
@Composable
fun TvInitialFocus(
@@ -28,6 +27,42 @@ fun TvInitialFocus(
}
@Composable
-fun FocusRestoreHost(content: @Composable () -> Unit) {
+fun FocusRestoreHost(
+ enabled: Boolean = true,
+ onRestore: suspend () -> Unit = {},
+ content: @Composable () -> Unit
+) {
+ val lifecycleOwner = LocalLifecycleOwner.current
+ val latestOnRestore by rememberUpdatedState(onRestore)
+ var restoreTick by remember { mutableIntStateOf(0) }
+ var hasComposed by remember { mutableStateOf(false) }
+
+ DisposableEffect(lifecycleOwner, enabled) {
+ if (!enabled) {
+ onDispose { }
+ } else {
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME && hasComposed) {
+ restoreTick++
+ }
+ }
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
+ }
+ }
+
+ LaunchedEffect(enabled) {
+ if (enabled) {
+ hasComposed = true
+ restoreTick++
+ }
+ }
+
+ LaunchedEffect(enabled, restoreTick) {
+ if (enabled) {
+ latestOnRestore()
+ }
+ }
+
content()
}
diff --git a/app/src/main/java/com/streamvault/app/ui/model/LiveTvChannelMode.kt b/app/src/main/java/com/streamvault/app/ui/model/LiveTvChannelMode.kt
index a49397ef..777d8866 100644
--- a/app/src/main/java/com/streamvault/app/ui/model/LiveTvChannelMode.kt
+++ b/app/src/main/java/com/streamvault/app/ui/model/LiveTvChannelMode.kt
@@ -7,6 +7,6 @@ enum class LiveTvChannelMode {
companion object {
fun fromStorage(value: String?): LiveTvChannelMode =
- entries.firstOrNull { it.name == value } ?: COMPACT
+ entries.firstOrNull { it.name == value } ?: COMFORTABLE
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
index b86b62ac..a83e060d 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
@@ -45,20 +45,21 @@ import com.streamvault.app.ui.components.CategoryRow
import com.streamvault.app.ui.components.ChannelCard
import com.streamvault.app.ui.components.ContinueWatchingRow
import com.streamvault.app.ui.components.MovieCard
+import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.components.SeriesCard
import com.streamvault.app.ui.components.shell.AppNavigationChrome
import com.streamvault.app.ui.components.shell.AppHeroHeader
import com.streamvault.app.ui.components.shell.AppScreenScaffold
import com.streamvault.app.ui.components.shell.StatusPill
import com.streamvault.app.ui.design.AppColors
-import com.streamvault.app.ui.theme.FocusBorder
-import com.streamvault.app.ui.theme.OnBackground
-import com.streamvault.app.ui.theme.OnSurfaceDim
-import com.streamvault.app.ui.theme.Primary
-import com.streamvault.app.ui.theme.SurfaceElevated
-import com.streamvault.app.ui.theme.SurfaceHighlight
-import com.streamvault.app.ui.theme.TextPrimary
-import com.streamvault.app.ui.theme.TextTertiary
+import com.streamvault.app.ui.design.AppColors.Brand as Primary
+import com.streamvault.app.ui.design.AppColors.Focus as FocusBorder
+import com.streamvault.app.ui.design.AppColors.SurfaceElevated as SurfaceElevated
+import com.streamvault.app.ui.design.AppColors.SurfaceEmphasis as SurfaceHighlight
+import com.streamvault.app.ui.design.AppColors.TextPrimary as OnBackground
+import com.streamvault.app.ui.design.AppColors.TextPrimary as TextPrimary
+import com.streamvault.app.ui.design.AppColors.TextTertiary as OnSurfaceDim
+import com.streamvault.app.ui.design.AppColors.TextTertiary as TextTertiary
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.PlaybackHistory
@@ -209,7 +210,7 @@ private fun DashboardHero(
) {
if (!feature.artworkUrl.isNullOrBlank()) {
AsyncImage(
- model = feature.artworkUrl,
+ model = rememberCrossfadeImageModel(feature.artworkUrl),
contentDescription = feature.title,
contentScale = ContentScale.Crop,
modifier = Modifier
@@ -776,7 +777,7 @@ private fun FavoriteChannelLogoCard(
) {
if (!channel.logoUrl.isNullOrBlank()) {
AsyncImage(
- model = channel.logoUrl,
+ model = rememberCrossfadeImageModel(channel.logoUrl),
contentDescription = channel.name,
contentScale = ContentScale.Fit,
modifier = Modifier
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt
index a334d255..ba899981 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt
@@ -59,12 +59,12 @@ import com.streamvault.app.ui.components.shell.AppHeroHeader
import com.streamvault.app.ui.components.shell.AppScreenScaffold
import com.streamvault.app.ui.components.shell.AppSectionHeader
import com.streamvault.app.ui.components.shell.StatusPill
-import com.streamvault.app.ui.theme.CardBackground
import com.streamvault.app.ui.theme.OnBackground
import com.streamvault.app.ui.theme.OnPrimary
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.Surface
import com.streamvault.app.ui.theme.SurfaceElevated
import com.streamvault.app.ui.theme.SurfaceHighlight
import com.streamvault.domain.model.ContentType
@@ -789,7 +789,7 @@ private fun SavedHistoryRow(
onClick = { onItemClick(item) },
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
colors = ClickableSurfaceDefaults.colors(
- containerColor = CardBackground,
+ containerColor = Surface,
focusedContainerColor = SurfaceHighlight,
contentColor = OnSurface,
focusedContentColor = OnSurface
@@ -852,7 +852,7 @@ private fun SavedGroupManagementRow(
onLongClick = { onGroupLongClick(group) },
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
colors = ClickableSurfaceDefaults.colors(
- containerColor = CardBackground,
+ containerColor = Surface,
focusedContainerColor = SurfaceHighlight
),
modifier = Modifier.width(240.dp)
@@ -1132,7 +1132,7 @@ private fun ReorderPanel(
.width(250.dp)
.heightIn(max = 300.dp)
.background(
- color = CardBackground.copy(alpha = 0.97f),
+ color = Surface.copy(alpha = 0.97f),
shape = RoundedCornerShape(topStart = 12.dp, bottomStart = 12.dp)
)
.padding(16.dp),
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
index e987f71e..431de55e 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
@@ -55,6 +55,7 @@ import com.streamvault.app.ui.components.SkeletonCard
import com.streamvault.app.ui.components.shimmerEffect
import com.streamvault.app.ui.components.shell.AppNavigationChrome
import com.streamvault.app.ui.components.shell.AppScreenScaffold
+import com.streamvault.app.ui.design.FocusRestoreHost
import androidx.activity.compose.BackHandler
import com.streamvault.app.ui.theme.*
import com.streamvault.domain.model.Category
@@ -70,9 +71,7 @@ import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialog
import com.streamvault.app.navigation.Routes
import com.streamvault.domain.model.VirtualCategoryIds
import androidx.compose.ui.viewinterop.AndroidView
-import androidx.media3.common.Player
-import androidx.media3.ui.AspectRatioFrameLayout
-import androidx.media3.ui.PlayerView
+import com.streamvault.player.PlayerSurfaceResizeMode
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -121,6 +120,7 @@ fun HomeScreen(
val splitSlots by multiViewViewModel.slotsFlow.collectAsState()
val hasSplitChannels = splitSlots.any { it != null }
var showSplitManagerDialog by rememberSaveable { mutableStateOf(false) }
+ var pendingSplitPlannerChannel by remember { mutableStateOf<Channel?>(null) }
// Parental Control State
var showPinDialog by rememberSaveable { mutableStateOf(false) }
@@ -142,7 +142,7 @@ fun HomeScreen(
}
}
- val hasOverlay = showPinDialog || showSplitManagerDialog ||
+ val hasOverlay = showPinDialog || showSplitManagerDialog || pendingSplitPlannerChannel != null ||
uiState.showDialog || uiState.showDeleteGroupDialog ||
uiState.showRenameGroupDialog || uiState.selectedCategoryForOptions != null ||
uiState.isChannelReorderMode
@@ -155,6 +155,7 @@ fun HomeScreen(
pendingUnlockCategory = null
pendingUnlockChannel = null
}
+ pendingSplitPlannerChannel != null -> pendingSplitPlannerChannel = null
uiState.showDeleteGroupDialog -> viewModel.cancelDeleteGroup()
uiState.showRenameGroupDialog -> viewModel.cancelRenameGroup()
uiState.selectedCategoryForOptions != null -> viewModel.dismissCategoryOptions()
@@ -268,7 +269,7 @@ fun HomeScreen(
.height(48.dp)
.padding(vertical = 4.dp)
.background(Color.DarkGray, RoundedCornerShape(8.dp))
- .shimmerEffect()
+ .shimmerEffect(baseColor = MaterialTheme.colorScheme.onSurface)
)
}
}
@@ -361,6 +362,43 @@ fun HomeScreen(
shouldRestoreCategoryFocus = false
}
+ FocusRestoreHost(
+ enabled = !hasOverlay && !uiState.isLoading && uiState.categories.isNotEmpty(),
+ onRestore = {
+ kotlinx.coroutines.delay(80)
+ val restoreTarget = runCatching {
+ FocusRestoreTarget.valueOf(preferredRestoreTarget)
+ }.getOrDefault(FocusRestoreTarget.CHANNEL)
+
+ val canRestoreChannel = lastFocusedChannelId != null &&
+ uiState.filteredChannels.any { it.id == lastFocusedChannelId }
+ val canRestoreCategory = lastFocusedCategoryId != null &&
+ uiState.categories.any { it.id == lastFocusedCategoryId }
+
+ when {
+ restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory -> {
+ runCatching { categoryFocusRequesters[lastFocusedCategoryId]?.requestFocus() }
+ }
+ canRestoreChannel -> {
+ val restored = runCatching {
+ channelFocusRequesters[lastFocusedChannelId]?.requestFocus()
+ }.isSuccess
+ if (!restored) {
+ val fallbackId = uiState.filteredChannels.firstOrNull()?.id
+ fallbackId?.let { runCatching { channelFocusRequesters[it]?.requestFocus() } }
+ }
+ }
+ canRestoreCategory -> {
+ runCatching { categoryFocusRequesters[lastFocusedCategoryId]?.requestFocus() }
+ }
+ else -> {
+ uiState.categories.firstOrNull()?.id?.let { firstCategoryId ->
+ runCatching { categoryFocusRequesters[firstCategoryId]?.requestFocus() }
+ }
+ }
+ }
+ }
+ ) {
Row(modifier = Modifier.fillMaxSize()) {
// Sidebar - Categories
val categorySearchFocusRequester = remember { FocusRequester() }
@@ -792,6 +830,7 @@ fun HomeScreen(
)
}
}
+ }
}
}
}
@@ -804,7 +843,20 @@ fun HomeScreen(
)
}
- if (uiState.showDialog && uiState.selectedChannelForDialog != null) {
+ if (pendingSplitPlannerChannel != null) {
+ MultiViewPlannerDialog(
+ pendingChannel = pendingSplitPlannerChannel,
+ onDismiss = { pendingSplitPlannerChannel = null },
+ onLaunch = {
+ pendingSplitPlannerChannel = null
+ viewModel.onDismissDialog()
+ onNavigate(Routes.MULTI_VIEW)
+ },
+ viewModel = multiViewViewModel
+ )
+ }
+
+ if (uiState.showDialog && uiState.selectedChannelForDialog != null && pendingSplitPlannerChannel == null) {
val channel = uiState.selectedChannelForDialog!!
com.streamvault.app.ui.components.dialogs.AddToGroupDialog(
contentTitle = channel.name,
@@ -819,7 +871,8 @@ fun HomeScreen(
onAddToGroup = { group -> viewModel.addToGroup(channel, group) },
onRemoveFromGroup = { group -> viewModel.removeFromGroup(channel, group) },
onCreateGroup = { name -> viewModel.createCustomGroup(name) },
- onNavigateToSplitScreen = { onNavigate(Routes.MULTI_VIEW) }
+ isQueuedForSplitScreen = multiViewViewModel.isQueued(channel.id),
+ onOpenSplitScreenPlanner = { pendingSplitPlannerChannel = channel }
)
}
@@ -878,6 +931,7 @@ fun HomeScreen(
}
)
}
+
}
@Composable
@@ -912,21 +966,19 @@ private fun LivePreviewPane(
.background(Color.Black, RoundedCornerShape(16.dp)),
contentAlignment = Alignment.Center
) {
- val player = playerEngine?.getPlayerView()
- if (channel != null && player is Player && errorMessage == null) {
+ if (channel != null && playerEngine != null && errorMessage == null) {
AndroidView(
factory = { context ->
- PlayerView(context).apply {
- this.player = player
- useController = false
- resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT
- setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER)
- }
+ playerEngine.createRenderView(
+ context = context,
+ resizeMode = PlayerSurfaceResizeMode.FIT
+ )
},
- update = { view ->
- if (view.player != player) {
- view.player = player
- }
+ update = { renderView ->
+ playerEngine.bindRenderView(
+ renderView = renderView,
+ resizeMode = PlayerSurfaceResizeMode.FIT
+ )
},
modifier = Modifier.fillMaxSize()
)
@@ -1023,6 +1075,7 @@ private fun LivePreviewPane(
}
}
}
+
}
private fun formatProgramTime(timestampMs: Long): String {
@@ -1249,6 +1302,7 @@ fun ReorderSidePanel(
}
}
}
+ }
}
// Helper Text
@@ -1261,4 +1315,3 @@ fun ReorderSidePanel(
)
}
}
-}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
index c4199af1..0ec1dec7 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
@@ -2,6 +2,7 @@ package com.streamvault.app.ui.screens.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.app.di.AuxiliaryPlayerEngine
import com.streamvault.app.ui.model.LiveTvChannelMode
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.domain.manager.ParentalControlManager
@@ -47,6 +48,7 @@ class HomeViewModel @Inject constructor(
private val playbackHistoryRepository: PlaybackHistoryRepository,
private val getCustomCategories: GetCustomCategories,
private val parentalControlManager: ParentalControlManager,
+ @AuxiliaryPlayerEngine
private val playerEngineProvider: InjectProvider<PlayerEngine>
) : ViewModel() {
private val appContext = application
@@ -899,7 +901,7 @@ data class HomeUiState(
val selectedCategoryForOptions: Category? = null,
val isChannelReorderMode: Boolean = false,
val reorderCategory: Category? = null,
- val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.COMPACT,
+ val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.COMFORTABLE,
val previewChannelId: Long? = null,
val previewPlayerEngine: PlayerEngine? = null,
val isPreviewLoading: Boolean = false,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
index eafeb84f..e7f24b72 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
@@ -46,8 +46,6 @@ import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.util.UnstableApi
-import androidx.media3.ui.AspectRatioFrameLayout
-import androidx.media3.ui.PlayerView
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
import androidx.tv.material3.Button
@@ -58,6 +56,7 @@ import com.streamvault.app.ui.components.dialogs.PremiumDialog
import com.streamvault.app.ui.components.dialogs.PremiumDialogActionButton
import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton
import com.streamvault.app.ui.theme.Primary
+import com.streamvault.player.PlayerSurfaceResizeMode
@Composable
fun MultiViewScreen(
@@ -316,27 +315,25 @@ private fun PlayerCell(
else -> {
val engine = slot.playerEngine
if (engine != null) {
- val exoPlayer = engine.getPlayerView()
- if (exoPlayer is androidx.media3.common.Player) {
- AndroidView(
- factory = { ctx ->
- PlayerView(ctx).apply {
- player = exoPlayer
- useController = false
- resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL
- isFocusable = false
- isFocusableInTouchMode = false
- importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
- }
- },
- update = { view ->
- if (view.player != exoPlayer) {
- view.player = exoPlayer
- }
- },
- modifier = Modifier.fillMaxSize()
- )
- }
+ AndroidView(
+ factory = { ctx ->
+ engine.createRenderView(
+ context = ctx,
+ resizeMode = PlayerSurfaceResizeMode.FILL
+ ).apply {
+ isFocusable = false
+ isFocusableInTouchMode = false
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
+ }
+ },
+ update = { renderView ->
+ engine.bindRenderView(
+ renderView = renderView,
+ resizeMode = PlayerSurfaceResizeMode.FILL
+ )
+ },
+ modifier = Modifier.fillMaxSize()
+ )
}
// Buffering indicator for active streams
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
index c1afdb5c..44cbc1bc 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
@@ -6,8 +6,11 @@ import android.os.Build
import android.os.PowerManager
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.app.di.AuxiliaryPlayerEngine
+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
@@ -28,11 +31,13 @@ import javax.inject.Provider
class MultiViewViewModel @Inject constructor(
@ApplicationContext private val context: Context,
val multiViewManager: MultiViewManager,
+ @AuxiliaryPlayerEngine
private val playerEngineProvider: Provider<PlayerEngine>,
private val preferencesRepository: PreferencesRepository,
private val channelRepository: ChannelRepository,
private val favoriteRepository: FavoriteRepository,
- private val playbackHistoryRepository: PlaybackHistoryRepository
+ private val playbackHistoryRepository: PlaybackHistoryRepository,
+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : ViewModel() {
private val _uiState = MutableStateFlow(MultiViewUiState())
@@ -168,14 +173,24 @@ class MultiViewViewModel @Inject constructor(
if (initVersion != slotInitVersion) return@launch
try {
val engine = playerEngineProvider.get()
+ // Cap each multi-view slot to 720p so slots don't compete for 4K bandwidth
+ (engine as? com.streamvault.player.Media3PlayerEngine)
+ ?.let { it.constrainResolutionForMultiView = true }
if (initVersion != slotInitVersion) {
engine.release()
return@launch
}
playerEngines[index] = engine
-
+
+ val resolvedUrl = xtreamStreamUrlResolver.resolve(
+ url = slot.streamUrl,
+ fallbackProviderId = slot.channel?.providerId,
+ fallbackStreamId = slot.channel?.streamId,
+ fallbackContentType = ContentType.LIVE
+ ) ?: throw IllegalStateException("No playable URL for ${slot.title}")
+
engine.prepare(
- com.streamvault.domain.model.StreamInfo(url = slot.streamUrl)
+ com.streamvault.domain.model.StreamInfo(url = resolvedUrl)
)
engine.play()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
index 81c31770..130fe0eb 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
@@ -1,5 +1,6 @@
package com.streamvault.app.ui.screens.player
+import android.app.Activity
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
@@ -32,8 +33,6 @@ import androidx.compose.foundation.focusable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.media3.common.util.UnstableApi
-import androidx.media3.exoplayer.ExoPlayer
-import androidx.media3.ui.PlayerView
import androidx.tv.material3.*
import com.streamvault.app.ui.theme.*
import com.streamvault.domain.model.DecoderMode
@@ -44,6 +43,7 @@ import com.streamvault.domain.repository.EpgRepository
import com.streamvault.player.PlaybackState
import com.streamvault.player.PlayerEngine
import com.streamvault.player.PlayerError
+import com.streamvault.player.PlayerSurfaceResizeMode
import com.streamvault.player.PlayerTrack
import com.streamvault.player.TrackType
import dagger.hilt.android.lifecycle.HiltViewModel
@@ -63,6 +63,7 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.streamvault.app.R
+import com.streamvault.app.MainActivity
import com.streamvault.app.ui.screens.player.overlay.ChannelInfoOverlay
import com.streamvault.app.ui.screens.player.overlay.CategoryListOverlay
import com.streamvault.app.ui.screens.player.overlay.ChannelListOverlay
@@ -103,6 +104,12 @@ fun PlayerScreen(
viewModel: PlayerViewModel = hiltViewModel(),
multiViewViewModel: MultiViewViewModel = hiltViewModel()
) {
+ val mainActivity = LocalContext.current.findMainActivity()
+ val isInPictureInPictureMode = mainActivity
+ ?.pictureInPictureModeFlow
+ ?.collectAsState(initial = mainActivity.isInPictureInPictureMode)
+ ?.value
+ ?: false
val playbackState by viewModel.playerEngine.playbackState.collectAsState()
val isPlaying by viewModel.playerEngine.isPlaying.collectAsState()
val showControls by viewModel.showControls.collectAsState()
@@ -132,7 +139,6 @@ fun PlayerScreen(
val availableVideoQualities by viewModel.availableVideoQualities.collectAsState()
val aspectRatio by viewModel.aspectRatio.collectAsState()
val showDiagnostics by viewModel.showDiagnostics.collectAsState()
- val playerStats by viewModel.playerStats.collectAsState()
val playerDiagnostics by viewModel.playerDiagnostics.collectAsState()
val currentPosition by viewModel.playerEngine.currentPosition.collectAsState()
val duration by viewModel.playerEngine.duration.collectAsState()
@@ -154,22 +160,48 @@ fun PlayerScreen(
val layoutDirection = LocalLayoutDirection.current
val isRtl = layoutDirection == LayoutDirection.Rtl
val lifecycleOwner = LocalLifecycleOwner.current
+ val currentPictureInPictureMode by rememberUpdatedState(isInPictureInPictureMode)
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
- DisposableEffect(lifecycleOwner) {
+ LaunchedEffect(mainActivity, streamUrl, playbackState, isPlaying, videoFormat.width, videoFormat.height) {
+ mainActivity?.updatePlayerPictureInPictureState(
+ enabled = streamUrl.isNotBlank() && playbackState != PlaybackState.ERROR,
+ isPlaying = isPlaying,
+ videoWidth = videoFormat.width,
+ videoHeight = videoFormat.height
+ )
+ }
+
+ LaunchedEffect(isInPictureInPictureMode) {
+ if (isInPictureInPictureMode) {
+ viewModel.closeOverlays()
+ if (showControls) {
+ viewModel.toggleControls()
+ }
+ }
+ }
+
+ DisposableEffect(lifecycleOwner, mainActivity) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_START -> viewModel.onAppForegrounded()
- Lifecycle.Event.ON_STOP -> viewModel.onAppBackgrounded()
+ Lifecycle.Event.ON_STOP -> {
+ if (currentPictureInPictureMode) {
+ viewModel.closeOverlays()
+ } else {
+ viewModel.onAppBackgrounded()
+ }
+ }
else -> Unit
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
+ mainActivity?.clearPlayerPictureInPictureState()
viewModel.onPlayerScreenDisposed()
}
}
@@ -206,7 +238,7 @@ fun PlayerScreen(
}
}
- if (showProgramHistory) {
+ if (!isInPictureInPictureMode && showProgramHistory) {
ProgramHistoryDialog(
programs = programHistory,
onDismiss = { showProgramHistory = false },
@@ -464,26 +496,21 @@ fun PlayerScreen(
}
) {
// ExoPlayer Video Surface
- val player = viewModel.playerEngine.getPlayerView()
- if (player is androidx.media3.common.Player) {
- AndroidView<androidx.media3.ui.PlayerView>(
- factory = { context ->
- androidx.media3.ui.PlayerView(context).apply {
- this.player = player
- useController = false
- setShowBuffering(androidx.media3.ui.PlayerView.SHOW_BUFFERING_NEVER)
- }
- },
- update = { playerView ->
- playerView.resizeMode = when (aspectRatio) {
- AspectRatio.FIT -> androidx.media3.ui.AspectRatioFrameLayout.RESIZE_MODE_FIT
- AspectRatio.FILL -> androidx.media3.ui.AspectRatioFrameLayout.RESIZE_MODE_FILL
- AspectRatio.ZOOM -> androidx.media3.ui.AspectRatioFrameLayout.RESIZE_MODE_ZOOM
- }
- },
- modifier = Modifier.fillMaxSize()
- )
- }
+ AndroidView(
+ factory = { context ->
+ viewModel.playerEngine.createRenderView(
+ context = context,
+ resizeMode = aspectRatio.toPlayerSurfaceResizeMode()
+ )
+ },
+ update = { renderView ->
+ viewModel.playerEngine.bindRenderView(
+ renderView = renderView,
+ resizeMode = aspectRatio.toPlayerSurfaceResizeMode()
+ )
+ },
+ modifier = Modifier.fillMaxSize()
+ )
// Buffering indicator
if (playbackState == PlaybackState.BUFFERING) {
@@ -598,7 +625,7 @@ fun PlayerScreen(
)
// Resume Prompt Dialog
- if (resumePrompt.show) {
+ if (!isInPictureInPictureMode && resumePrompt.show) {
PlayerResumePrompt(
title = resumePrompt.title,
onStartOver = { viewModel.dismissResumePrompt(resume = false) },
@@ -607,19 +634,22 @@ fun PlayerScreen(
}
// Track Selection Dialog
- PlayerTrackSelectionDialog(
- trackType = showTrackSelection,
- audioTracks = availableAudioTracks,
- subtitleTracks = availableSubtitleTracks,
- videoTracks = availableVideoQualities,
- onDismiss = { showTrackSelection = null },
- onSelectAudio = viewModel::selectAudioTrack,
- onSelectVideo = viewModel::selectVideoQuality,
- onSelectSubtitle = viewModel::selectSubtitleTrack
- )
+ if (!isInPictureInPictureMode) {
+ PlayerTrackSelectionDialog(
+ trackType = showTrackSelection,
+ audioTracks = availableAudioTracks,
+ subtitleTracks = availableSubtitleTracks,
+ videoTracks = availableVideoQualities,
+ onDismiss = { showTrackSelection = null },
+ onSelectAudio = viewModel::selectAudioTrack,
+ onSelectVideo = viewModel::selectVideoQuality,
+ onSelectSubtitle = viewModel::selectSubtitleTrack
+ )
+ }
// --- Overlays ---
- if (showDiagnostics) {
+ if (!isInPictureInPictureMode && showDiagnostics) {
+ val playerStats by viewModel.playerStats.collectAsState()
DiagnosticsOverlay(
stats = playerStats,
diagnostics = playerDiagnostics,
@@ -744,3 +774,15 @@ fun PlayerScreen(
}
}
}
+
+private fun AspectRatio.toPlayerSurfaceResizeMode(): PlayerSurfaceResizeMode = when (this) {
+ AspectRatio.FIT -> PlayerSurfaceResizeMode.FIT
+ AspectRatio.FILL -> PlayerSurfaceResizeMode.FILL
+ AspectRatio.ZOOM -> PlayerSurfaceResizeMode.ZOOM
+}
+
+private tailrec fun android.content.Context.findMainActivity(): MainActivity? = when (this) {
+ is MainActivity -> this
+ is android.content.ContextWrapper -> baseContext.findMainActivity()
+ else -> null
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index 96a4b32f..fde84fb0 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -2,6 +2,8 @@ package com.streamvault.app.ui.screens.player
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.app.di.MainPlayerEngine
+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.domain.manager.RecordingManager
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Program
@@ -16,6 +18,7 @@ import com.streamvault.domain.model.VideoFormat
import com.streamvault.domain.usecase.GetCustomCategories
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.player.PlaybackState
import com.streamvault.player.PlayerEngine
@@ -85,15 +88,18 @@ enum class AspectRatio(val modeName: String) {
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class)
class PlayerViewModel @Inject constructor(
+ @MainPlayerEngine
val playerEngine: PlayerEngine,
private val epgRepository: EpgRepository,
private val channelRepository: ChannelRepository,
+ private val movieRepository: MovieRepository,
private val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,
private val playbackHistoryRepository: PlaybackHistoryRepository,
private val providerRepository: com.streamvault.domain.repository.ProviderRepository,
private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,
private val getCustomCategories: GetCustomCategories,
- private val recordingManager: RecordingManager
+ private val recordingManager: RecordingManager,
+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : ViewModel() {
private val _showControls = MutableStateFlow(false)
@@ -180,6 +186,7 @@ class PlayerViewModel @Inject constructor(
private var hasRetriedWithSoftwareDecoder = false
private var lastRecordedLivePlaybackKey: Pair<Long, Long>? = null
private var currentStreamClassLabel: String = "Primary"
+ private var prepareRequestVersion: Long = 0L
init {
viewModelScope.launch {
@@ -441,6 +448,7 @@ class PlayerViewModel @Inject constructor(
archiveEndMs: Long? = null,
archiveTitle: String? = null
) {
+ val requestVersion = ++prepareRequestVersion
currentStreamUrl = streamUrl
currentProviderId = providerId
currentContentId = internalChannelId
@@ -462,12 +470,21 @@ class PlayerViewModel @Inject constructor(
// Reset tried streams for manual switch
triedAlternativeStreams.clear()
triedAlternativeStreams.add(streamUrl)
-
- val streamInfo = com.streamvault.domain.model.StreamInfo(
- url = streamUrl,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
- )
- playerEngine.prepare(streamInfo)
+
+ viewModelScope.launch {
+ val resolvedUrl = resolvePlaybackUrl(streamUrl, internalChannelId, providerId, currentContentType)
+ if (requestVersion != prepareRequestVersion) return@launch
+ if (resolvedUrl.isNullOrBlank()) {
+ showPlayerNotice(message = "No playable stream URL was available.", recoveryType = PlayerRecoveryType.SOURCE)
+ return@launch
+ }
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = resolvedUrl,
+ title = currentTitle,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ playerEngine.prepare(streamInfo)
+ }
// Show context info on entry for both Live and VOD
openChannelInfoOverlay()
@@ -543,6 +560,7 @@ class PlayerViewModel @Inject constructor(
appendRecoveryAction("Opened catch-up stream")
val catchupStream = com.streamvault.domain.model.StreamInfo(
url = catchUpUrl,
+ title = currentTitle,
streamType = com.streamvault.domain.model.StreamType.UNKNOWN
)
playerEngine.prepare(catchupStream)
@@ -997,14 +1015,18 @@ class PlayerViewModel @Inject constructor(
refreshCurrentChannelRecording()
_displayChannelNumber.value = resolveChannelNumber(channel, index)
_recentChannels.update { channels -> channels.filterNot { it.id == channel.id } }
-
- // Prepare player
- val streamInfo = com.streamvault.domain.model.StreamInfo(
- url = channel.streamUrl,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
- )
- playerEngine.prepare(streamInfo)
- playerEngine.play()
+
+ viewModelScope.launch {
+ val resolvedUrl = resolvePlaybackUrl(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)
+ ?: return@launch
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = resolvedUrl,
+ title = currentTitle,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ playerEngine.prepare(streamInfo)
+ playerEngine.play()
+ }
fetchEpg(currentProviderId, channel.epgChannelId)
@@ -1162,12 +1184,17 @@ class PlayerViewModel @Inject constructor(
triedAlternativeStreams.add(nextStream)
currentStreamUrl = nextStream
updateStreamClass("Alternate")
- val streamInfo = com.streamvault.domain.model.StreamInfo(
- url = nextStream,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
- )
- playerEngine.prepare(streamInfo)
- playerEngine.play()
+ viewModelScope.launch {
+ val resolvedUrl = resolvePlaybackUrl(nextStream, channel.id, channel.providerId, ContentType.LIVE)
+ ?: return@launch
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = resolvedUrl,
+ title = currentTitle,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ playerEngine.prepare(streamInfo)
+ playerEngine.play()
+ }
return true
}
@@ -1289,6 +1316,7 @@ class PlayerViewModel @Inject constructor(
val streamInfo = com.streamvault.domain.model.StreamInfo(
url = catchUpUrl,
+ title = currentTitle,
streamType = com.streamvault.domain.model.StreamType.UNKNOWN
)
playerEngine.prepare(streamInfo)
@@ -1509,6 +1537,33 @@ class PlayerViewModel @Inject constructor(
prepare(streamUrl, epgChannelId, currentId, currentCategoryId, currentProviderId, isVirtualCategory, currentContentType.name, currentTitle)
}
+ private suspend fun resolvePlaybackUrl(
+ logicalUrl: String,
+ internalContentId: Long,
+ providerId: Long,
+ contentType: ContentType
+ ): String? {
+ xtreamStreamUrlResolver.resolve(
+ url = logicalUrl,
+ fallbackProviderId = providerId.takeIf { it > 0 },
+ fallbackContentType = contentType
+ )?.let { return it }
+
+ if (providerId <= 0L || internalContentId <= 0L) {
+ return logicalUrl.takeIf { it.isNotBlank() }
+ }
+
+ return when (contentType) {
+ ContentType.LIVE -> channelRepository.getChannel(internalContentId)?.let { channel ->
+ channelRepository.getStreamUrl(channel).getOrNull()
+ }
+ ContentType.MOVIE -> movieRepository.getMovie(internalContentId)?.let { movie ->
+ movieRepository.getStreamUrl(movie).getOrNull()
+ }
+ ContentType.SERIES, ContentType.SERIES_EPISODE -> logicalUrl.takeIf { it.isNotBlank() }
+ }
+ }
+
fun dismissResumePrompt(resume: Boolean) {
val prompt = _resumePrompt.value
_resumePrompt.value = ResumePromptState() // hide
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
index 8f79e14e..85d46791 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
@@ -58,7 +58,6 @@ import com.streamvault.app.ui.screens.player.NumericChannelInputState
import com.streamvault.app.ui.theme.ErrorColor
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
-import com.streamvault.app.ui.theme.PrimaryVariant
import com.streamvault.domain.model.Program
import com.streamvault.domain.model.RecordingStatus
import kotlinx.coroutines.delay
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
index 0ccc0ec9..b56af6f7 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
@@ -62,14 +62,15 @@ import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import coil3.compose.AsyncImage
import com.streamvault.app.R
+import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.components.shell.StatusPill
import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.screens.player.PlayerDiagnosticsUiState
import com.streamvault.domain.model.RecordingStatus
-import com.streamvault.app.ui.theme.OnSurfaceDim
-import com.streamvault.app.ui.theme.Primary
-import com.streamvault.app.ui.theme.SurfaceVariant
-import com.streamvault.app.ui.theme.TextSecondary
+import com.streamvault.app.ui.design.AppColors.Brand as Primary
+import com.streamvault.app.ui.design.AppColors.SurfaceElevated as SurfaceVariant
+import com.streamvault.app.ui.design.AppColors.TextSecondary as TextSecondary
+import com.streamvault.app.ui.design.AppColors.TextTertiary as OnSurfaceDim
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Program
import com.streamvault.player.PlayerStats
@@ -205,7 +206,7 @@ fun ChannelInfoOverlay(
) {
if (!currentChannel.logoUrl.isNullOrBlank()) {
AsyncImage(
- model = currentChannel.logoUrl,
+ model = rememberCrossfadeImageModel(currentChannel.logoUrl),
contentDescription = currentChannel.name,
modifier = Modifier
.fillMaxSize()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
index b69965b1..2c5bbadb 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
@@ -35,10 +35,9 @@ import com.streamvault.app.ui.theme.OnBackground
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
-import com.streamvault.app.ui.theme.PrimaryVariant
import com.streamvault.app.ui.theme.SurfaceElevated
import com.streamvault.app.ui.theme.SurfaceHighlight
-import com.streamvault.app.ui.theme.SurfaceVariant
+import com.streamvault.app.ui.theme.PrimaryLight
import com.streamvault.app.ui.theme.TextSecondary
import com.streamvault.player.PlayerError
import com.streamvault.player.PlayerTrack
@@ -142,7 +141,7 @@ fun PlayerErrorOverlay(
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (action == PlayerNoticeAction.RETRY) Primary else Color.White.copy(alpha = 0.08f),
- focusedContainerColor = if (action == PlayerNoticeAction.RETRY) PrimaryVariant else Color.White.copy(alpha = 0.18f)
+ focusedContainerColor = if (action == PlayerNoticeAction.RETRY) PrimaryLight else Color.White.copy(alpha = 0.18f)
)
) {
Text(
@@ -317,7 +316,7 @@ fun PlayerResumePrompt(
onClick = onStartOver,
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
colors = ClickableSurfaceDefaults.colors(
- containerColor = SurfaceVariant,
+ containerColor = SurfaceElevated,
focusedContainerColor = SurfaceHighlight
),
modifier = Modifier.weight(1f)
@@ -337,7 +336,7 @@ fun PlayerResumePrompt(
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = Primary,
- focusedContainerColor = PrimaryVariant
+ focusedContainerColor = PrimaryLight
),
modifier = Modifier.weight(1f)
) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
index fe0b2498..73bbb5bc 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
@@ -32,6 +32,7 @@ import androidx.hilt.navigation.compose.hiltViewModel
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.ui.platform.LocalContext
+import com.streamvault.data.util.ProviderInputSanitizer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -39,7 +40,6 @@ import androidx.tv.material3.*
import com.streamvault.app.ui.components.shell.AppSectionHeader
import com.streamvault.app.ui.components.shell.StatusPill
import com.streamvault.app.ui.components.dialogs.PremiumDialog
-import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.theme.*
import androidx.compose.ui.res.stringResource
import com.streamvault.app.R
@@ -95,7 +95,9 @@ fun ProviderSetupScreen(
withContext(Dispatchers.Main) {
m3uUrl = "file://${outFile.absolutePath}"
- if (name.isEmpty()) name = fileName
+ if (name.isEmpty()) {
+ name = ProviderInputSanitizer.sanitizeProviderNameForEditing(fileName)
+ }
fileImportError = null
}
} else {
@@ -228,11 +230,11 @@ fun ProviderSetupScreen(
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
StatusPill(
label = stringResource(R.string.setup_xtream),
- containerColor = AppColors.BrandMuted
+ containerColor = PrimaryGlow
)
StatusPill(
label = stringResource(R.string.setup_m3u),
- containerColor = AppColors.SurfaceEmphasis
+ containerColor = SurfaceHighlight
)
}
@@ -284,7 +286,7 @@ fun ProviderSetupScreen(
Text(
text = stringResource(R.string.setup_source_type_label),
style = MaterialTheme.typography.labelMedium,
- color = AppColors.TextTertiary
+ color = TextTertiary
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -306,7 +308,7 @@ fun ProviderSetupScreen(
TvTextField(
value = name,
- onValueChange = { name = it },
+ onValueChange = { name = ProviderInputSanitizer.sanitizeProviderNameForEditing(it) },
label = stringResource(R.string.setup_name_hint),
focusRequester = providerNameFocusRequester,
onMoveUp = { false },
@@ -328,17 +330,17 @@ fun ProviderSetupScreen(
0 -> {
TvTextField(
value = serverUrl,
- onValueChange = { serverUrl = it },
+ onValueChange = { serverUrl = ProviderInputSanitizer.sanitizeUrlForEditing(it) },
label = stringResource(R.string.setup_server_hint)
)
TvTextField(
value = username,
- onValueChange = { username = it },
+ onValueChange = { username = ProviderInputSanitizer.sanitizeUsernameForEditing(it) },
label = stringResource(R.string.setup_user_hint)
)
TvTextField(
value = password,
- onValueChange = { password = it },
+ onValueChange = { password = ProviderInputSanitizer.sanitizePasswordForEditing(it) },
label = stringResource(R.string.setup_pass_hint),
isPassword = true
)
@@ -397,7 +399,7 @@ fun ProviderSetupScreen(
if (uiState.m3uTab == 0) {
TvTextField(
value = m3uUrl,
- onValueChange = { m3uUrl = it },
+ onValueChange = { m3uUrl = ProviderInputSanitizer.sanitizeUrlForEditing(it) },
label = stringResource(R.string.setup_m3u_hint),
focusRequester = m3uValueFocusRequester,
onMoveUp = {
@@ -516,10 +518,11 @@ fun SyncProgressDialog(message: String) {
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- CircularProgressIndicator(color = AppColors.Brand)
+ CircularProgressIndicator(color = Primary)
+
StatusPill(
label = stringResource(R.string.settings_syncing_btn),
- containerColor = AppColors.BrandMuted
+ containerColor = PrimaryGlow
)
Text(
text = message,
@@ -648,10 +651,10 @@ private fun ActionButton(
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (enabled) Primary else SurfaceHighlight,
- focusedContainerColor = if (enabled) PrimaryVariant else SurfaceHighlight
+ focusedContainerColor = if (enabled) PrimaryLight else SurfaceHighlight
),
border = ClickableSurfaceDefaults.border(
- border = Border(BorderStroke(1.dp, if (enabled) PrimaryDark else SurfaceHighlight)),
+ border = Border(BorderStroke(1.dp, if (enabled) PrimaryLight else SurfaceHighlight)),
focusedBorder = Border(BorderStroke(2.dp, FocusBorder))
)
) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
index e98a8561..ff696b27 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
@@ -2,6 +2,7 @@ package com.streamvault.app.ui.screens.provider
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.data.util.ProviderInputSanitizer
import com.streamvault.data.util.UrlSecurityPolicy
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.Result
@@ -69,15 +70,23 @@ class ProviderSetupViewModel @Inject constructor(
fun loginXtream(serverUrl: String, username: String, password: String, name: String) {
_uiState.update { it.copy(validationError = null, error = null) }
- if (serverUrl.isBlank()) {
+ val normalizedServerUrl = ProviderInputSanitizer.normalizeUrl(serverUrl)
+ val normalizedUsername = ProviderInputSanitizer.normalizeUsername(username)
+ val normalizedName = ProviderInputSanitizer.normalizeProviderName(name)
+
+ if (normalizedServerUrl.isBlank()) {
_uiState.update { it.copy(validationError = "Please enter server URL") }
return
}
- UrlSecurityPolicy.validateXtreamServerUrl(serverUrl)?.let { message ->
+ ProviderInputSanitizer.validateUrl(normalizedServerUrl)?.let { message ->
+ _uiState.update { it.copy(validationError = message) }
+ return
+ }
+ UrlSecurityPolicy.validateXtreamServerUrl(normalizedServerUrl)?.let { message ->
_uiState.update { it.copy(validationError = message) }
return
}
- if (username.isBlank()) {
+ if (normalizedUsername.isBlank()) {
_uiState.update { it.copy(validationError = "Please enter username") }
return
}
@@ -86,7 +95,7 @@ class ProviderSetupViewModel @Inject constructor(
_uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...") }
val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null
- when (val result = providerRepository.loginXtream(serverUrl, username, password, name, onProgress = { msg ->
+ when (val result = providerRepository.loginXtream(normalizedServerUrl, normalizedUsername, password, normalizedName, onProgress = { msg ->
_uiState.update { it.copy(syncProgress = msg) }
}, id = existingId)) {
is Result.Success -> {
@@ -96,6 +105,9 @@ class ProviderSetupViewModel @Inject constructor(
}
is Result.Error -> {
val userMessage = when {
+ result.message.contains("certificate", ignoreCase = true) ||
+ result.message.contains("trust", ignoreCase = true) ->
+ "Secure connection failed — the server's TLS certificate is not trusted on this device"
result.message.contains("authentication failed", ignoreCase = true) ||
result.message.contains("auth", ignoreCase = true) ->
"Login failed — please check your credentials and server URL"
@@ -117,11 +129,18 @@ class ProviderSetupViewModel @Inject constructor(
fun addM3u(url: String, name: String) {
_uiState.update { it.copy(validationError = null, error = null) }
- if (url.isBlank()) {
+ val normalizedUrl = ProviderInputSanitizer.normalizeUrl(url)
+ val normalizedName = ProviderInputSanitizer.normalizeProviderName(name)
+
+ if (normalizedUrl.isBlank()) {
_uiState.update { it.copy(validationError = if (_uiState.value.m3uTab == 0) "Please enter M3U URL" else "Please select a file") }
return
}
- UrlSecurityPolicy.validatePlaylistSourceUrl(url)?.let { message ->
+ ProviderInputSanitizer.validateUrl(normalizedUrl)?.let { message ->
+ _uiState.update { it.copy(validationError = message) }
+ return
+ }
+ UrlSecurityPolicy.validatePlaylistSourceUrl(normalizedUrl)?.let { message ->
_uiState.update { it.copy(validationError = message) }
return
}
@@ -130,7 +149,7 @@ class ProviderSetupViewModel @Inject constructor(
_uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Validating...") }
val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null
- when (val result = providerRepository.validateM3u(url, name, onProgress = { msg ->
+ when (val result = providerRepository.validateM3u(normalizedUrl, normalizedName, onProgress = { msg ->
_uiState.update { it.copy(syncProgress = msg) }
}, id = existingId)) {
is Result.Success -> {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
index d0624413..fe51d20a 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
@@ -35,7 +35,6 @@ import com.streamvault.app.ui.components.SeriesCard
import com.streamvault.app.ui.components.TvEmptyState
import com.streamvault.app.ui.components.shell.AppNavigationChrome
import com.streamvault.app.ui.components.shell.AppScreenScaffold
-import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.theme.*
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Movie
@@ -271,7 +270,7 @@ fun SearchScreen(
Text(
text = stringResource(R.string.search_title),
style = MaterialTheme.typography.headlineSmall,
- color = AppColors.TextPrimary
+ color = TextPrimary
)
}
@@ -279,7 +278,7 @@ fun SearchScreen(
Text(
text = stringResource(R.string.search_command_subtitle),
style = MaterialTheme.typography.bodySmall,
- color = AppColors.TextSecondary,
+ color = TextSecondary,
modifier = Modifier.widthIn(max = 640.dp)
)
}
@@ -482,7 +481,7 @@ fun SectionHeader(title: String) {
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
- color = AppColors.Brand,
+ color = Primary,
modifier = Modifier.padding(vertical = 8.dp)
)
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt
index 4e4b917d..94c52bb5 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt
@@ -27,7 +27,6 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
-import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -41,8 +40,8 @@ import androidx.tv.material3.Surface
import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import coil3.compose.AsyncImage
-import coil3.request.ImageRequest
import com.streamvault.app.R
+import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.components.shell.ContentMetadataStrip
import com.streamvault.app.ui.components.shell.EpisodeRowCard
import com.streamvault.app.ui.components.shell.StatusPill
@@ -107,9 +106,7 @@ private fun SeriesDetailContent(
.background(AppColors.Canvas)
) {
AsyncImage(
- model = ImageRequest.Builder(LocalContext.current)
- .data(series.backdropUrl ?: series.posterUrl)
- .build(),
+ model = rememberCrossfadeImageModel(series.backdropUrl ?: series.posterUrl),
contentDescription = series.name,
modifier = Modifier
.fillMaxWidth()
@@ -166,7 +163,7 @@ private fun SeriesDetailContent(
.background(AppColors.SurfaceElevated)
) {
AsyncImage(
- model = series.posterUrl ?: series.backdropUrl,
+ model = rememberCrossfadeImageModel(series.posterUrl ?: series.backdropUrl),
contentDescription = series.name,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
index cd2994db..dc9e643b 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
@@ -52,6 +52,7 @@ import androidx.compose.ui.window.Dialog
import androidx.compose.ui.text.style.TextAlign
import com.streamvault.app.R
import java.util.Locale
+import com.streamvault.app.BuildConfig
@Composable
@@ -88,6 +89,7 @@ fun SettingsScreen(
var showClearHistoryDialog by rememberSaveable { mutableStateOf(false) }
var pinError by rememberSaveable { mutableStateOf<String?>(null) }
var pendingAction by remember { mutableStateOf<ParentalAction?>(null) }
+ var pendingProtectionLevel by rememberSaveable { mutableStateOf<Int?>(null) }
val createDocumentLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.CreateDocument("application/json")
@@ -234,13 +236,24 @@ fun SettingsScreen(
)
ParentalControlCard(
level = uiState.parentalControlLevel,
+ hasParentalPin = uiState.hasParentalPin,
hasActiveProvider = uiState.activeProviderId != null,
- onChangeLevel = {
- pendingAction = ParentalAction.ChangeLevel
- showPinDialog = true
+ onChangeLevel = {
+ pendingProtectionLevel = null
+ if (uiState.hasParentalPin) {
+ pendingAction = ParentalAction.ChangeLevel
+ showPinDialog = true
+ } else {
+ showLevelDialog = true
+ }
},
onChangePin = {
- pendingAction = ParentalAction.ChangePin
+ pendingProtectionLevel = null
+ pendingAction = if (uiState.hasParentalPin) {
+ ParentalAction.ChangePin
+ } else {
+ ParentalAction.SetNewPin
+ }
showPinDialog = true
},
onManageProtectedGroups = {
@@ -376,7 +389,8 @@ fun SettingsScreen(
RecordingItemCard(
item = item,
onStop = { viewModel.stopRecording(item.id) },
- onCancel = { viewModel.cancelRecording(item.id) }
+ onCancel = { viewModel.cancelRecording(item.id) },
+ onDelete = { viewModel.deleteRecording(item.id) }
)
}
}
@@ -488,7 +502,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_about),
subtitle = stringResource(R.string.settings_about_subtitle)
)
- SettingsRow(label = stringResource(R.string.settings_app_version), value = "1.0.0")
+ SettingsRow(label = stringResource(R.string.settings_app_version), value = "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")
SettingsRow(label = stringResource(R.string.settings_build), value = stringResource(R.string.settings_build_desc))
SettingsRow(label = stringResource(R.string.settings_developed_by), value = stringResource(R.string.settings_developer_name))
ClickableSettingsRow(
@@ -563,12 +577,18 @@ fun SettingsScreen(
PinDialog(
onDismissRequest = {
showPinDialog = false
- pinError = null
+ pinError = null
+ if (pendingAction == ParentalAction.SetNewPin) {
+ pendingAction = null
+ pendingProtectionLevel = null
+ }
},
onPinEntered = { pin ->
scope.launch {
if (pendingAction == ParentalAction.SetNewPin) {
viewModel.changePin(pin)
+ pendingProtectionLevel?.let(viewModel::setParentalControlLevel)
+ pendingProtectionLevel = null
showPinDialog = false
pendingAction = null
} else {
@@ -604,11 +624,23 @@ fun SettingsScreen(
showLevelDialog = false
}
LevelOption(1, stringResource(R.string.settings_level_locked_desc), uiState.parentalControlLevel) {
- viewModel.setParentalControlLevel(1)
+ if (uiState.hasParentalPin) {
+ viewModel.setParentalControlLevel(1)
+ } else {
+ pendingProtectionLevel = 1
+ pendingAction = ParentalAction.SetNewPin
+ showPinDialog = true
+ }
showLevelDialog = false
}
LevelOption(2, stringResource(R.string.settings_level_hidden_desc), uiState.parentalControlLevel) {
- viewModel.setParentalControlLevel(2)
+ if (uiState.hasParentalPin) {
+ viewModel.setParentalControlLevel(2)
+ } else {
+ pendingProtectionLevel = 2
+ pendingAction = ParentalAction.SetNewPin
+ showPinDialog = true
+ }
showLevelDialog = false
}
}
@@ -673,7 +705,7 @@ fun SettingsScreen(
},
containerColor = SurfaceElevated,
titleContentColor = OnSurface,
- textContentColor = OnSurfaceVariant
+ textContentColor = TextSecondary
)
}
}
@@ -759,6 +791,7 @@ private fun LevelOption(level: Int, text: String, currentLevel: Int, onSelect: (
@Composable
private fun ParentalControlCard(
level: Int,
+ hasParentalPin: Boolean,
hasActiveProvider: Boolean,
onChangeLevel: () -> Unit,
onChangePin: () -> Unit,
@@ -830,7 +863,7 @@ private fun ParentalControlCard(
)
) {
Text(
- text = stringResource(R.string.settings_change_pin),
+ text = stringResource(if (hasParentalPin) R.string.settings_change_pin else R.string.settings_set_pin),
style = MaterialTheme.typography.labelMedium,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)
)
@@ -1721,7 +1754,8 @@ private fun RecordingOverviewCard(
private fun RecordingItemCard(
item: RecordingItem,
onStop: () -> Unit,
- onCancel: () -> Unit
+ onCancel: () -> Unit,
+ onDelete: () -> Unit
) {
Surface(
modifier = Modifier.fillMaxWidth(),
@@ -1804,6 +1838,22 @@ private fun RecordingItemCard(
)
}
}
+ if (item.status == RecordingStatus.COMPLETED || item.status == RecordingStatus.FAILED || item.status == RecordingStatus.CANCELLED) {
+ Surface(
+ onClick = onDelete,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceHighlight,
+ focusedContainerColor = Primary.copy(alpha = 0.2f)
+ )
+ ) {
+ Text(
+ text = stringResource(R.string.settings_recording_delete),
+ color = OnBackground,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
+ )
+ }
+ }
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
index de813d78..947cce7f 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
@@ -38,6 +38,7 @@ private data class SettingsPreferenceSnapshot(
val providers: List<Provider>,
val activeProviderId: Long?,
val parentalControlLevel: Int,
+ val hasParentalPin: Boolean,
val appLanguage: String,
val isIncognitoMode: Boolean,
val liveTvChannelMode: LiveTvChannelMode
@@ -66,17 +67,21 @@ class SettingsViewModel @Inject constructor(
providerRepository.getProviders(),
preferencesRepository.lastActiveProviderId,
preferencesRepository.parentalControlLevel,
- preferencesRepository.appLanguage,
- preferencesRepository.isIncognitoMode
- ) { providers, activeId, level, language, incognito ->
+ preferencesRepository.hasParentalPin
+ ) { providers, activeId, level, hasParentalPin ->
SettingsPreferenceSnapshot(
providers = providers,
activeProviderId = activeId,
parentalControlLevel = level,
- appLanguage = language,
- isIncognitoMode = incognito,
- liveTvChannelMode = LiveTvChannelMode.COMPACT
+ hasParentalPin = hasParentalPin,
+ appLanguage = "system",
+ isIncognitoMode = false,
+ liveTvChannelMode = LiveTvChannelMode.COMFORTABLE
)
+ }.combine(preferencesRepository.appLanguage) { snapshot, language ->
+ snapshot.copy(appLanguage = language)
+ }.combine(preferencesRepository.isIncognitoMode) { snapshot, incognito ->
+ snapshot.copy(isIncognitoMode = incognito)
}.combine(preferencesRepository.liveTvChannelMode) { snapshot, liveTvChannelMode ->
snapshot.copy(liveTvChannelMode = LiveTvChannelMode.fromStorage(liveTvChannelMode))
}.collect { snapshot ->
@@ -85,6 +90,7 @@ class SettingsViewModel @Inject constructor(
providers = snapshot.providers,
activeProviderId = snapshot.activeProviderId,
parentalControlLevel = snapshot.parentalControlLevel,
+ hasParentalPin = snapshot.hasParentalPin,
appLanguage = snapshot.appLanguage,
isIncognitoMode = snapshot.isIncognitoMode,
liveTvChannelMode = snapshot.liveTvChannelMode
@@ -413,6 +419,15 @@ class SettingsViewModel @Inject constructor(
}
}
+ fun deleteRecording(recordingId: String) {
+ viewModelScope.launch {
+ val result = recordingManager.deleteRecording(recordingId)
+ _uiState.update {
+ it.copy(userMessage = if (result is Result.Error) "Delete failed: ${result.message}" else "Recording deleted")
+ }
+ }
+ }
+
private fun buildCapabilitySummary(provider: Provider): String {
return when (provider.type) {
ProviderType.XTREAM_CODES -> {
@@ -458,6 +473,7 @@ data class SettingsUiState(
val syncWarningsByProvider: Map<Long, List<String>> = emptyMap(),
val diagnosticsByProvider: Map<Long, ProviderDiagnosticsUiModel> = emptyMap(),
val parentalControlLevel: Int = 0,
+ val hasParentalPin: Boolean = false,
val appLanguage: String = "system",
val backupPreview: BackupPreview? = null,
val pendingBackupUri: String? = null,
@@ -465,5 +481,5 @@ data class SettingsUiState(
val recordingItems: List<RecordingItem> = emptyList(),
val recordingStorageState: RecordingStorageState = RecordingStorageState(),
val isIncognitoMode: Boolean = false,
- val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.COMPACT
+ val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.COMFORTABLE
)
diff --git a/app/src/main/java/com/streamvault/app/ui/theme/Color.kt b/app/src/main/java/com/streamvault/app/ui/theme/Color.kt
index ef2af9d2..e4c0fca7 100644
--- a/app/src/main/java/com/streamvault/app/ui/theme/Color.kt
+++ b/app/src/main/java/com/streamvault/app/ui/theme/Color.kt
@@ -5,8 +5,6 @@ import com.streamvault.app.ui.design.AppColors
val Primary = AppColors.Brand
val PrimaryLight = AppColors.BrandStrong
-val PrimaryVariant = PrimaryLight
-val PrimaryDark = Color(0xFF356CB7)
val PrimaryGlow = AppColors.BrandMuted
val BackgroundDeep = AppColors.Canvas
@@ -14,7 +12,6 @@ val Background = AppColors.CanvasElevated
val Surface = AppColors.Surface
val SurfaceElevated = AppColors.SurfaceElevated
val SurfaceHighlight = AppColors.SurfaceEmphasis
-val SurfaceVariant = SurfaceElevated
val TextPrimary = AppColors.TextPrimary
val TextSecondary = AppColors.TextSecondary
@@ -22,8 +19,7 @@ val TextTertiary = AppColors.TextTertiary
val TextDisabled = AppColors.TextDisabled
val OnBackground = TextPrimary
-val OnSurface = TextSecondary
-val OnSurfaceVariant = TextSecondary
+val OnSurface = TextPrimary
val OnSurfaceDim = TextTertiary
val AccentRed = AppColors.Live
@@ -34,14 +30,9 @@ val AccentCyan = AppColors.Info
val OnPrimary = Color(0xFFFFFFFF)
val Secondary = AppColors.Success
val ErrorColor = AccentRed
-val SuccessColor = AccentGreen
-val LiveIndicator = AccentRed
-val WarningColor = AccentAmber
val GradientOverlayTop = AppColors.HeroTop
val GradientOverlayBottom = AppColors.HeroBottom
val FocusBorder = AppColors.Focus
-val CardBackground = Surface
-val ProgressBar = Primary
val ProgressBarBackground = AppColors.SurfaceAccent
diff --git a/app/src/main/java/com/streamvault/app/ui/theme/Spacing.kt b/app/src/main/java/com/streamvault/app/ui/theme/Spacing.kt
index 6cb127e1..7456c6a1 100644
--- a/app/src/main/java/com/streamvault/app/ui/theme/Spacing.kt
+++ b/app/src/main/java/com/streamvault/app/ui/theme/Spacing.kt
@@ -1,34 +1,10 @@
package com.streamvault.app.ui.theme
-import androidx.compose.runtime.staticCompositionLocalOf
-import androidx.compose.ui.unit.Dp
import com.streamvault.app.ui.design.AppSpacing
+import com.streamvault.app.ui.design.LocalAppSpacing
-data class Spacing(
- val xs: Dp,
- val sm: Dp,
- val md: Dp,
- val lg: Dp,
- val xl: Dp,
- val xxl: Dp,
- val safeTop: Dp,
- val safeBottom: Dp,
- val safeHoriz: Dp
-)
+typealias Spacing = AppSpacing
-val LocalSpacing = staticCompositionLocalOf { defaultSpacing() }
+val LocalSpacing = LocalAppSpacing
-fun defaultSpacing(): Spacing {
- val spacing = AppSpacing()
- return Spacing(
- xs = spacing.xs,
- sm = spacing.md,
- md = spacing.lg,
- lg = spacing.xl,
- xl = spacing.screenGutter,
- xxl = spacing.screenGutter + spacing.md,
- safeTop = spacing.safeTop,
- safeBottom = spacing.safeBottom,
- safeHoriz = spacing.screenGutter
- )
-}
+fun defaultSpacing(): Spacing = AppSpacing()
diff --git a/app/src/main/java/com/streamvault/app/ui/theme/Theme.kt b/app/src/main/java/com/streamvault/app/ui/theme/Theme.kt
index e95e01ce..5881f1ab 100644
--- a/app/src/main/java/com/streamvault/app/ui/theme/Theme.kt
+++ b/app/src/main/java/com/streamvault/app/ui/theme/Theme.kt
@@ -4,31 +4,34 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.darkColorScheme
+import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.design.AppShapes
+import com.streamvault.app.ui.design.AppTypography
import com.streamvault.app.ui.design.LocalAppShapes
import com.streamvault.app.ui.design.LocalAppSpacing
private val DarkColorScheme = darkColorScheme(
- primary = Primary,
+ primary = AppColors.Brand,
onPrimary = OnPrimary,
- surface = Surface,
- onSurface = TextSecondary,
- background = Background,
- onBackground = TextPrimary,
- error = ErrorColor,
+ surface = AppColors.Surface,
+ onSurface = AppColors.TextPrimary,
+ surfaceVariant = AppColors.SurfaceElevated,
+ onSurfaceVariant = AppColors.TextSecondary,
+ background = AppColors.CanvasElevated,
+ onBackground = AppColors.TextPrimary,
+ error = AppColors.Live,
onError = OnPrimary
)
@Composable
fun StreamVaultTheme(content: @Composable () -> Unit) {
CompositionLocalProvider(
- LocalSpacing provides defaultSpacing(),
LocalAppSpacing provides com.streamvault.app.ui.design.AppSpacing(),
LocalAppShapes provides AppShapes()
) {
MaterialTheme(
colorScheme = DarkColorScheme,
- typography = StreamVaultTypography,
+ typography = AppTypography,
content = content
)
}
diff --git a/app/src/main/java/com/streamvault/app/ui/theme/Type.kt b/app/src/main/java/com/streamvault/app/ui/theme/Type.kt
deleted file mode 100644
index 8df9ff14..00000000
--- a/app/src/main/java/com/streamvault/app/ui/theme/Type.kt
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.streamvault.app.ui.theme
-
-import androidx.tv.material3.Typography
-import com.streamvault.app.ui.design.AppTypography
-import com.streamvault.app.ui.design.InterFamily
-
-val Inter = InterFamily
-val StreamVaultTypography: Typography = AppTypography
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 08c8b06e..63cc0d27 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -278,6 +278,7 @@
<string name="settings_change">Change</string>
<string name="settings_parental_pin">Parental PIN</string>
<string name="settings_change_pin">Change PIN</string>
+ <string name="settings_set_pin">Set PIN</string>
<string name="settings_expiration_unknown">Expiration: Unknown</string>
<string name="settings_expiration_never">Expiration: Never</string>
<string name="settings_expires">Expires: %1$s</string>
@@ -358,6 +359,7 @@
<string name="settings_recording_time_window">%1$s → %2$s</string>
<string name="settings_recording_stop">Stop</string>
<string name="settings_recording_cancel">Cancel</string>
+ <string name="settings_recording_delete">Delete</string>
<!-- Favorites -->
<string name="favorites_title">Saved</string>
@@ -763,6 +765,7 @@
<string name="label_slots_count">%1$d/4 slots</string>
<string name="label_rating">RTG %1$s</string>
<string name="label_episode">E%1$d</string>
+ <string name="label_episode_full">Episode %1$d</string>
<string name="label_duration_min">%1$d min</string>
<string name="label_tv">TV</string>
<string name="badge_saved">SAVED</string>
@@ -818,6 +821,6 @@
<string name="home_removed_from_favorites">Removed %1$s from Favorites</string>
<string name="home_error_load_failed">Failed to load channels. Please check your connection and try again.</string>
<string name="settings_history_cleared">Watch history and recents cleared</string>
- <string name="settings_pin_changed">PIN changed successfully</string>
+ <string name="settings_pin_changed">PIN saved successfully</string>
<string name="home_reorder_channels">Reorder Channels</string>
</resources>
diff --git a/app/src/main/res/xml/network_security_config.xml b/app/src/main/res/xml/network_security_config.xml
index 61159508..701c32a9 100644
--- a/app/src/main/res/xml/network_security_config.xml
+++ b/app/src/main/res/xml/network_security_config.xml
@@ -1,4 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
- <base-config cleartextTrafficPermitted="false" />
+ <!-- Allow cleartext (HTTP) for IPTV streams — most providers serve over HTTP -->
+ <base-config cleartextTrafficPermitted="true">
+ <trust-anchors>
+ <certificates src="system" />
+ </trust-anchors>
+ </base-config>
</network-security-config>
diff --git a/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt b/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt
index 3db949af..2ebde5e3 100644
--- a/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt
+++ b/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt
@@ -17,7 +17,7 @@ class RoutesTest {
@Test
fun `livePlayer preserves playback context`() {
- val route = Routes.livePlayer(
+ val request = Routes.livePlayer(
channel = Channel(
id = 42L,
name = "News HD",
@@ -31,17 +31,17 @@ class RoutesTest {
isVirtual = false
)
- assertThat(route).contains("internalId=42")
- assertThat(route).contains("categoryId=9")
- assertThat(route).contains("providerId=7")
- assertThat(route).contains("channelId=news.hd")
- assertThat(route).contains("contentType=LIVE")
- assertThat(route).contains("isVirtual=false")
+ assertThat(request.internalId).isEqualTo(42L)
+ assertThat(request.categoryId).isEqualTo(9L)
+ assertThat(request.providerId).isEqualTo(7L)
+ assertThat(request.channelId).isEqualTo("news.hd")
+ assertThat(request.contentType).isEqualTo("LIVE")
+ assertThat(request.isVirtual).isFalse()
}
@Test
fun `livePlayer falls back to all channels when category is missing`() {
- val route = Routes.livePlayer(
+ val request = Routes.livePlayer(
channel = Channel(
id = 8L,
name = "Sports",
@@ -52,13 +52,13 @@ class RoutesTest {
providerId = 3L
)
- assertThat(route).contains("categoryId=${ChannelRepository.ALL_CHANNELS_ID}")
- assertThat(route).contains("providerId=3")
+ assertThat(request.categoryId).isEqualTo(ChannelRepository.ALL_CHANNELS_ID)
+ assertThat(request.providerId).isEqualTo(3L)
}
@Test
fun `moviePlayer preserves provider and category context`() {
- val route = Routes.moviePlayer(
+ val request = Routes.moviePlayer(
Movie(
id = 15L,
name = "Film",
@@ -68,15 +68,15 @@ class RoutesTest {
)
)
- assertThat(route).contains("internalId=15")
- assertThat(route).contains("categoryId=21")
- assertThat(route).contains("providerId=5")
- assertThat(route).contains("contentType=MOVIE")
+ assertThat(request.internalId).isEqualTo(15L)
+ assertThat(request.categoryId).isEqualTo(21L)
+ assertThat(request.providerId).isEqualTo(5L)
+ assertThat(request.contentType).isEqualTo("MOVIE")
}
@Test
fun `episodePlayer preserves episode playback context`() {
- val route = Routes.episodePlayer(
+ val request = Routes.episodePlayer(
Episode(
id = 33L,
title = "Pilot",
@@ -87,14 +87,14 @@ class RoutesTest {
)
)
- assertThat(route).contains("internalId=33")
- assertThat(route).contains("providerId=11")
- assertThat(route).contains("contentType=SERIES_EPISODE")
+ assertThat(request.internalId).isEqualTo(33L)
+ assertThat(request.providerId).isEqualTo(11L)
+ assertThat(request.contentType).isEqualTo("SERIES_EPISODE")
}
@Test
fun `player route supports archive playback context`() {
- val route = Routes.player(
+ val request = Routes.player(
streamUrl = "https://example.com/live.m3u8",
title = "News HD",
internalId = 42L,
@@ -105,9 +105,9 @@ class RoutesTest {
archiveTitle = "News HD: Morning Show"
)
- assertThat(route).contains("archiveStartMs=1700000000000")
- assertThat(route).contains("archiveEndMs=1700000360000")
- assertThat(route).contains("archiveTitle=News+HD%3A+Morning+Show")
+ assertThat(request.archiveStartMs).isEqualTo(1_700_000_000_000L)
+ assertThat(request.archiveEndMs).isEqualTo(1_700_000_360_000L)
+ assertThat(request.archiveTitle).isEqualTo("News HD: Morning Show")
}
@Test
@@ -130,7 +130,7 @@ class RoutesTest {
anchorTime = 1_700_000_360_000L,
favoritesOnly = false
)
- val route = Routes.livePlayer(
+ val request = Routes.livePlayer(
channel = Channel(
id = 42L,
name = "News HD",
@@ -144,8 +144,6 @@ class RoutesTest {
returnRoute = returnRoute
)
- assertThat(route).contains(
- "returnRoute=epg%3FcategoryId%3D9%26anchorTime%3D1700000360000%26favoritesOnly%3Dfalse"
- )
+ assertThat(request.returnRoute).isEqualTo(returnRoute)
}
}
diff --git a/build.gradle.kts b/build.gradle.kts
index 8b7e9200..84e9dcd9 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -4,6 +4,7 @@ plugins {
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.jvm) apply false
alias(libs.plugins.kotlin.compose) apply false
+ alias(libs.plugins.kotlin.serialization) apply false
alias(libs.plugins.ksp) apply false
alias(libs.plugins.hilt) apply false
alias(libs.plugins.room) apply false
diff --git a/build.log b/build.log
deleted file mode 100644
index 23adf279..00000000
Binary files a/build.log and /dev/null differ
diff --git a/build2.log b/build2.log
deleted file mode 100644
index f1d0059e..00000000
--- a/build2.log
+++ /dev/null
@@ -1,71 +0,0 @@
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:kspDebugKotlin
-
-> Task :app:compileDebugKotlin
-w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt:159:26 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
-w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt:171:26 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
-w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt:225:26 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
-w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt:233:26 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
-w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt:77:7 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
-w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt:59:36 'val Icons.Filled.ArrowBack: ImageVector' is deprecated. Use the AutoMirrored version at Icons.AutoMirrored.Filled.ArrowBack.
-
-BUILD SUCCESSFUL in 35s
-47 actionable tasks: 2 executed, 45 up-to-date
diff --git a/build_err.txt b/build_err.txt
deleted file mode 100644
index fac4d7ef..00000000
Binary files a/build_err.txt and /dev/null differ
diff --git a/build_error.txt b/build_error.txt
deleted file mode 100644
index 1ebe7d6f..00000000
Binary files a/build_error.txt and /dev/null differ
diff --git a/build_errors.txt b/build_errors.txt
deleted file mode 100644
index b5f3d07c..00000000
Binary files a/build_errors.txt and /dev/null differ
diff --git a/build_log.txt b/build_log.txt
deleted file mode 100644
index fa83c07c..00000000
Binary files a/build_log.txt and /dev/null differ
diff --git a/build_log_phase5.txt b/build_log_phase5.txt
deleted file mode 100644
index f4a3da62..00000000
Binary files a/build_log_phase5.txt and /dev/null differ
diff --git a/build_output.txt b/build_output.txt
deleted file mode 100644
index 56491e3f..00000000
Binary files a/build_output.txt and /dev/null differ
diff --git a/compile.log b/compile.log
deleted file mode 100644
index c303f490..00000000
--- a/compile.log
+++ /dev/null
@@ -1,93 +0,0 @@
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-
-> Task :app:kspDebugKotlin FAILED
-e: [ksp] C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt: (362, 72): Function declaration must have a name
-e: Error occurred in KSP, check log for detail
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:5 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:8 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:9 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:16 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:17 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:28 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:31 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:38 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:39 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:63 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:66 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:70 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:362:72 Expecting a top level declaration
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt:378:1 Expecting a top level declaration
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':app:kspDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 2s
-46 actionable tasks: 1 executed, 45 up-to-date
diff --git a/compile2.log b/compile2.log
deleted file mode 100644
index 10e6c618..00000000
--- a/compile2.log
+++ /dev/null
@@ -1,63 +0,0 @@
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:kspDebugKotlin UP-TO-DATE
-
-BUILD SUCCESSFUL in 5s
-46 actionable tasks: 46 up-to-date
diff --git a/compile3.log b/compile3.log
deleted file mode 100644
index 9b1b9224..00000000
--- a/compile3.log
+++ /dev/null
@@ -1,63 +0,0 @@
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:kspDebugKotlin UP-TO-DATE
-
-BUILD SUCCESSFUL in 3s
-46 actionable tasks: 46 up-to-date
diff --git a/compile4.log b/compile4.log
deleted file mode 100644
index 9b1b9224..00000000
--- a/compile4.log
+++ /dev/null
@@ -1,63 +0,0 @@
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:kspDebugKotlin UP-TO-DATE
-
-BUILD SUCCESSFUL in 3s
-46 actionable tasks: 46 up-to-date
diff --git a/compile5.log b/compile5.log
deleted file mode 100644
index 4d6de7a9..00000000
--- a/compile5.log
+++ /dev/null
@@ -1,80 +0,0 @@
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:kspDebugKotlin UP-TO-DATE
-
-> Task :app:compileDebugKotlin FAILED
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt:42:63 Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'com.streamvault.domain.model.Provider?'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt:72:88 Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'com.streamvault.domain.model.Provider?'.
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':app:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 4s
-47 actionable tasks: 1 executed, 46 up-to-date
diff --git a/compile_errors.log b/compile_errors.log
deleted file mode 100644
index 2c1f8d39..00000000
--- a/compile_errors.log
+++ /dev/null
@@ -1,80 +0,0 @@
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :data:kspDebugKotlin
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:kspDebugKotlin UP-TO-DATE
-
-> Task :app:compileDebugKotlin FAILED
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt:84:41 No value passed for parameter 'contentType'.
-e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt:255:44 No value passed for parameter 'contentType'.
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':app:compileDebugKotlin'.
-> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
- > Compilation error. See log for more details
-
-* Try:
-> Run with --stacktrace option to get the stack trace.
-> Run with --info or --debug option to get more log output.
-> Run with --scan to get full insights.
-> Get more help at https://help.gradle.org.
-
-BUILD FAILED in 35s
-47 actionable tasks: 3 executed, 44 up-to-date
diff --git a/compile_log.txt b/compile_log.txt
deleted file mode 100644
index b541ef92..00000000
Binary files a/compile_log.txt and /dev/null differ
diff --git a/data/build.gradle.kts b/data/build.gradle.kts
index 741c0c73..7754cb00 100644
--- a/data/build.gradle.kts
+++ b/data/build.gradle.kts
@@ -1,6 +1,7 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
+ alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.ksp)
alias(libs.plugins.hilt)
alias(libs.plugins.room)
@@ -51,6 +52,7 @@ dependencies {
implementation(libs.okhttp)
implementation(libs.okhttp.logging)
implementation(libs.gson)
+ implementation(libs.kotlinx.serialization.json)
// Hilt
implementation(libs.hilt.android)
@@ -77,9 +79,9 @@ dependencies {
testImplementation(libs.mockito.kotlin)
// Android instrumentation tests
- androidTestImplementation("androidx.room:room-testing:2.6.1")
- androidTestImplementation("androidx.test:runner:1.6.2")
- androidTestImplementation("androidx.test.ext:junit:1.2.1")
+ androidTestImplementation(libs.room.testing)
+ androidTestImplementation(libs.androidx.test.runner)
+ androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.truth)
androidTestImplementation(libs.coroutines.test)
}
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/12.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/12.json
new file mode 100644
index 00000000..ae1fe80a
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/12.json
@@ -0,0 +1,1558 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 12,
+ "identityHash": "8a555be5278a4f9f88bf16bd9f7ac010",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ],
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ],
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ],
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ }
+ ],
+ "views": [],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '8a555be5278a4f9f88bf16bd9f7ac010')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/13.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/13.json
new file mode 100644
index 00000000..f77db3e1
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/13.json
@@ -0,0 +1,1618 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 13,
+ "identityHash": "22723b1614721511e0fa2b5cefc5af5a",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ],
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ],
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ],
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ }
+ ],
+ "views": [],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '22723b1614721511e0fa2b5cefc5af5a')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt
new file mode 100644
index 00000000..2b790cac
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt
@@ -0,0 +1,26 @@
+package com.streamvault.data.local
+
+import androidx.room.TypeConverter
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.ProviderType
+
+class RoomEnumConverters {
+ @TypeConverter
+ fun fromProviderType(value: ProviderType?): String? = value?.name
+
+ @TypeConverter
+ fun toProviderType(value: String?): ProviderType? = value?.let(ProviderType::valueOf)
+
+ @TypeConverter
+ fun fromProviderStatus(value: ProviderStatus?): String? = value?.name
+
+ @TypeConverter
+ fun toProviderStatus(value: String?): ProviderStatus? = value?.let(ProviderStatus::valueOf)
+
+ @TypeConverter
+ fun fromContentType(value: ContentType?): String? = value?.name
+
+ @TypeConverter
+ fun toContentType(value: String?): ContentType? = value?.let(ContentType::valueOf)
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
index 453d6a85..fcc1685c 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
@@ -2,6 +2,7 @@ package com.streamvault.data.local
import androidx.room.Database
import androidx.room.RoomDatabase
+import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.streamvault.data.local.dao.*
@@ -11,6 +12,7 @@ import com.streamvault.data.local.entity.*
entities = [
ProviderEntity::class,
ChannelEntity::class,
+ ChannelPreferenceEntity::class,
ChannelFtsEntity::class,
MovieEntity::class,
MovieFtsEntity::class,
@@ -24,12 +26,14 @@ import com.streamvault.data.local.entity.*
PlaybackHistoryEntity::class,
SyncMetadataEntity::class
],
- version = 11,
+ version = 13,
exportSchema = true // ← was false; schema JSON now tracked in version control
)
+@TypeConverters(RoomEnumConverters::class)
abstract class StreamVaultDatabase : RoomDatabase() {
abstract fun providerDao(): ProviderDao
abstract fun channelDao(): ChannelDao
+ abstract fun channelPreferenceDao(): ChannelPreferenceDao
abstract fun movieDao(): MovieDao
abstract fun seriesDao(): SeriesDao
abstract fun episodeDao(): EpisodeDao
@@ -41,6 +45,17 @@ abstract class StreamVaultDatabase : RoomDatabase() {
abstract fun syncMetadataDao(): SyncMetadataDao
companion object {
+ /**
+ * Migration 1 → 2: no-op stub.
+ * v1 databases had the same table structure as v2; this migration prevents Room
+ * from crashing with an "unsatisfied migration" exception on very early installs.
+ */
+ val MIGRATION_1_2 = object : Migration(1, 2) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ // Schema was identical between v1 and v2; nothing to alter.
+ }
+ }
+
/**
* Migration 2 → 3: added parental-control protection columns.
*/
@@ -844,5 +859,75 @@ abstract class StreamVaultDatabase : RoomDatabase() {
database.execSQL("CREATE INDEX index_favorites_group_id_position ON favorites(group_id, position)")
}
}
+ /**
+ * Migration 11 → 12: adds series_id FK to episodes.
+ * Episodes whose series_id has no matching row in the series table are silently
+ * removed — they are unreachable orphans and would violate the new constraint.
+ */
+ val MIGRATION_11_12 = object : Migration(11, 12) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ // Create new episodes table with both FK constraints
+ database.execSQL("""
+ CREATE TABLE episodes_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ episode_id INTEGER NOT NULL DEFAULT 0,
+ title TEXT NOT NULL,
+ episode_number INTEGER NOT NULL,
+ season_number INTEGER NOT NULL,
+ stream_url TEXT NOT NULL DEFAULT '',
+ container_extension TEXT,
+ cover_url TEXT,
+ plot TEXT,
+ duration TEXT,
+ duration_seconds INTEGER NOT NULL DEFAULT 0,
+ rating REAL NOT NULL DEFAULT 0,
+ release_date TEXT,
+ series_id INTEGER NOT NULL DEFAULT 0,
+ provider_id INTEGER NOT NULL DEFAULT 0,
+ watch_progress INTEGER NOT NULL DEFAULT 0,
+ last_watched_at INTEGER NOT NULL DEFAULT 0,
+ is_adult INTEGER NOT NULL DEFAULT 0,
+ is_user_protected INTEGER NOT NULL DEFAULT 0,
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,
+ FOREIGN KEY(series_id) REFERENCES series(id) ON DELETE CASCADE
+ )
+ """.trimIndent())
+ // Migrate only episodes with a valid series parent; orphans are discarded
+ database.execSQL("""
+ INSERT INTO episodes_new
+ SELECT * FROM episodes
+ WHERE series_id IN (SELECT id FROM series)
+ """.trimIndent())
+ database.execSQL("DROP TABLE episodes")
+ database.execSQL("ALTER TABLE episodes_new RENAME TO episodes")
+ database.execSQL("CREATE INDEX index_episodes_series_id ON episodes(series_id)")
+ database.execSQL("CREATE INDEX index_episodes_provider_id ON episodes(provider_id)")
+ database.execSQL("CREATE UNIQUE INDEX index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")
+ }
+ }
+
+ /**
+ * Migration 12 → 13: move high-cardinality per-channel UI state into Room.
+ * Existing DataStore aspect-ratio entries are read lazily as a legacy fallback and
+ * get replaced in Room on the next write for each channel.
+ */
+ val MIGRATION_12_13 = object : Migration(12, 13) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS channel_preferences (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ channel_id INTEGER NOT NULL,
+ aspect_ratio TEXT,
+ updated_at INTEGER NOT NULL DEFAULT 0,
+ FOREIGN KEY(channel_id) REFERENCES channels(id) ON DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL(
+ "CREATE UNIQUE INDEX IF NOT EXISTS index_channel_preferences_channel_id ON channel_preferences(channel_id)"
+ )
+ }
+ }
}
-}
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
index 6ab10b2a..71ca9cb0 100644
--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
@@ -10,39 +10,46 @@ data class RemoteIdMapping(
)
@Dao
-interface ProviderDao {
+abstract class ProviderDao {
@Query("SELECT * FROM providers ORDER BY created_at DESC")
- fun getAll(): Flow<List<ProviderEntity>>
+ abstract fun getAll(): Flow<List<ProviderEntity>>
@Query("SELECT * FROM providers WHERE is_active = 1 LIMIT 1")
- fun getActive(): Flow<ProviderEntity?>
+ abstract fun getActive(): Flow<ProviderEntity?>
@Query("SELECT * FROM providers WHERE server_url = :serverUrl AND username = :username")
- suspend fun getByUrlAndUser(serverUrl: String, username: String): ProviderEntity?
+ abstract suspend fun getByUrlAndUser(serverUrl: String, username: String): ProviderEntity?
@Query("SELECT * FROM providers WHERE id = :id")
- suspend fun getById(id: Long): ProviderEntity?
+ abstract suspend fun getById(id: Long): ProviderEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
- suspend fun insert(provider: ProviderEntity): Long
+ abstract suspend fun insert(provider: ProviderEntity): Long
@Update
- suspend fun update(provider: ProviderEntity)
+ abstract suspend fun update(provider: ProviderEntity)
@Query("DELETE FROM providers WHERE id = :id")
- suspend fun delete(id: Long)
+ abstract suspend fun delete(id: Long)
@Query("UPDATE providers SET is_active = 0")
- suspend fun deactivateAll()
+ abstract suspend fun deactivateAll()
@Query("UPDATE providers SET is_active = 1 WHERE id = :id")
- suspend fun activate(id: Long)
+ abstract suspend fun activate(id: Long)
@Query("UPDATE providers SET last_synced_at = :timestamp WHERE id = :id")
- suspend fun updateSyncTime(id: Long, timestamp: Long)
+ abstract suspend fun updateSyncTime(id: Long, timestamp: Long)
@Query("UPDATE providers SET epg_url = :epgUrl WHERE id = :id")
- suspend fun updateEpgUrl(id: Long, epgUrl: String)
+ abstract suspend fun updateEpgUrl(id: Long, epgUrl: String)
+
+ /** Atomically deactivates all providers then activates the given one. */
+ @Transaction
+ open suspend fun setActive(id: Long) {
+ deactivateAll()
+ activate(id)
+ }
}
@Dao
@@ -50,9 +57,15 @@ interface ChannelDao {
@Query("SELECT * FROM channels WHERE provider_id = :providerId ORDER BY number ASC")
fun getByProvider(providerId: Long): Flow<List<ChannelEntity>>
+ @Query("SELECT * FROM channels WHERE provider_id = :providerId ORDER BY number ASC LIMIT :limit OFFSET :offset")
+ fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<ChannelEntity>>
+
@Query("SELECT * FROM channels WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY number ASC")
fun getByCategory(providerId: Long, categoryId: Long): Flow<List<ChannelEntity>>
+ @Query("SELECT * FROM channels WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY number ASC LIMIT :limit OFFSET :offset")
+ fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<ChannelEntity>>
+
@Query(
"""
SELECT c.* FROM channels c
@@ -60,7 +73,6 @@ interface ChannelDao {
WHERE c.provider_id = :providerId
AND channels_fts MATCH :query
ORDER BY c.name ASC
- LIMIT 1000
"""
)
fun search(providerId: Long, query: String): Flow<List<ChannelEntity>>
@@ -73,7 +85,6 @@ interface ChannelDao {
AND c.category_id = :categoryId
AND channels_fts MATCH :query
ORDER BY c.name ASC
- LIMIT 1000
"""
)
fun searchByCategory(providerId: Long, categoryId: Long, query: String): Flow<List<ChannelEntity>>
@@ -122,17 +133,37 @@ interface ChannelDao {
suspend fun resetErrorCount(id: Long)
}
+@Dao
+interface ChannelPreferenceDao {
+ @Query("SELECT aspect_ratio FROM channel_preferences WHERE channel_id = :channelId LIMIT 1")
+ fun observeAspectRatio(channelId: Long): Flow<String?>
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(preference: ChannelPreferenceEntity)
+
+ @Query("DELETE FROM channel_preferences")
+ suspend fun deleteAll()
+}
+
@Dao
interface MovieDao {
@Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY name ASC")
fun getByProvider(providerId: Long): Flow<List<MovieEntity>>
+ /** SQL-level parental filter — avoids loading protected items into memory. */
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND is_user_protected = 0 ORDER BY name ASC")
+ fun getByProviderUnprotected(providerId: Long): Flow<List<MovieEntity>>
+
@Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY name ASC LIMIT :limit OFFSET :offset")
fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieEntity>>
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")
fun getByCategory(providerId: Long, categoryId: Long): Flow<List<MovieEntity>>
+ /** SQL-level parental filter per category. */
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND is_user_protected = 0 ORDER BY name ASC")
+ fun getByCategoryUnprotected(providerId: Long, categoryId: Long): Flow<List<MovieEntity>>
+
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit OFFSET :offset")
fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieEntity>>
@@ -152,7 +183,6 @@ interface MovieDao {
WHERE m.provider_id = :providerId
AND movies_fts MATCH :query
ORDER BY m.name ASC
- LIMIT 1000
"""
)
fun search(providerId: Long, query: String): Flow<List<MovieEntity>>
@@ -255,7 +285,6 @@ interface SeriesDao {
WHERE s.provider_id = :providerId
AND series_fts MATCH :query
ORDER BY s.name ASC
- LIMIT 1000
"""
)
fun search(providerId: Long, query: String): Flow<List<SeriesEntity>>
@@ -328,6 +357,9 @@ interface EpisodeDao {
@Query("DELETE FROM episodes WHERE series_id = :seriesId")
suspend fun deleteBySeries(seriesId: Long)
+ @Query("DELETE FROM episodes WHERE series_id NOT IN (SELECT id FROM series)")
+ suspend fun deleteOrphans(): Int
+
@Query("""
UPDATE episodes
SET watch_progress = (
@@ -405,7 +437,7 @@ interface ProgramDao {
suspend fun insertAll(programs: List<ProgramEntity>)
@Query("DELETE FROM programs WHERE end_time < :beforeTime")
- suspend fun deleteOld(beforeTime: Long)
+ suspend fun deleteOld(beforeTime: Long): Int
@Query("DELETE FROM programs WHERE provider_id = :providerId")
suspend fun deleteByProvider(providerId: Long)
@@ -455,6 +487,15 @@ interface FavoriteDao {
@Query("DELETE FROM favorites WHERE content_id = :contentId AND content_type = :contentType AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId)")
suspend fun delete(contentId: Long, contentType: String, groupId: Long?)
+ @Query("DELETE FROM favorites WHERE content_type = 'LIVE' AND content_id NOT IN (SELECT id FROM channels)")
+ suspend fun deleteMissingLiveFavorites(): Int
+
+ @Query("DELETE FROM favorites WHERE content_type = 'MOVIE' AND content_id NOT IN (SELECT id FROM movies)")
+ suspend fun deleteMissingMovieFavorites(): Int
+
+ @Query("DELETE FROM favorites WHERE content_type = 'SERIES' AND content_id NOT IN (SELECT id FROM series)")
+ suspend fun deleteMissingSeriesFavorites(): Int
+
@Query("UPDATE favorites SET group_id = :groupId WHERE id = :favoriteId")
suspend fun updateGroup(favoriteId: Long, groupId: Long?)
}
diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
index b912a3aa..cfb779c9 100644
--- a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
+++ b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
@@ -6,6 +6,9 @@ import androidx.room.ForeignKey
import androidx.room.Fts4
import androidx.room.Index
import androidx.room.PrimaryKey
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.ProviderType
@Entity(
tableName = "providers",
@@ -15,7 +18,7 @@ data class ProviderEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val name: String,
- val type: String, // XTREAM_CODES, M3U
+ val type: ProviderType,
@ColumnInfo(name = "server_url") val serverUrl: String,
val username: String = "",
val password: String = "",
@@ -24,7 +27,7 @@ data class ProviderEntity(
@ColumnInfo(name = "is_active") val isActive: Boolean = true,
@ColumnInfo(name = "max_connections") val maxConnections: Int = 1,
@ColumnInfo(name = "expiration_date") val expirationDate: Long? = null,
- val status: String = "UNKNOWN",
+ val status: ProviderStatus = ProviderStatus.UNKNOWN,
@ColumnInfo(name = "last_synced_at") val lastSyncedAt: Long = 0,
@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis()
)
@@ -66,6 +69,24 @@ data class ChannelEntity(
@ColumnInfo(name = "error_count") val errorCount: Int = 0
)
+@Entity(
+ tableName = "channel_preferences",
+ foreignKeys = [ForeignKey(
+ entity = ChannelEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["channel_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [Index(value = ["channel_id"], unique = true)]
+)
+data class ChannelPreferenceEntity(
+ @PrimaryKey(autoGenerate = true)
+ val id: Long = 0,
+ @ColumnInfo(name = "channel_id") val channelId: Long,
+ @ColumnInfo(name = "aspect_ratio") val aspectRatio: String? = null,
+ @ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis()
+)
+
@Entity(
tableName = "movies",
foreignKeys = [ForeignKey(
@@ -167,12 +188,20 @@ data class SeriesFtsEntity(
@Entity(
tableName = "episodes",
- foreignKeys = [ForeignKey(
- entity = ProviderEntity::class,
- parentColumns = ["id"],
- childColumns = ["provider_id"],
- onDelete = ForeignKey.CASCADE
- )],
+ foreignKeys = [
+ ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ ),
+ ForeignKey(
+ entity = SeriesEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["series_id"],
+ onDelete = ForeignKey.CASCADE
+ )
+ ],
indices = [
Index(value = ["series_id"]),
Index(value = ["provider_id"]),
@@ -221,7 +250,7 @@ data class CategoryEntity(
@ColumnInfo(name = "category_id") val categoryId: Long = 0,
val name: String,
@ColumnInfo(name = "parent_id") val parentId: Long? = null,
- val type: String = "LIVE", // LIVE, MOVIE, SERIES
+ val type: ContentType = ContentType.LIVE,
@ColumnInfo(name = "provider_id") val providerId: Long = 0,
@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false
@@ -268,7 +297,7 @@ data class FavoriteEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
@ColumnInfo(name = "content_id") val contentId: Long,
- @ColumnInfo(name = "content_type") val contentType: String, // LIVE, MOVIE, SERIES
+ @ColumnInfo(name = "content_type") val contentType: ContentType,
val position: Int = 0,
@ColumnInfo(name = "group_id") val groupId: Long? = null,
@ColumnInfo(name = "added_at") val addedAt: Long = System.currentTimeMillis()
@@ -285,7 +314,7 @@ data class VirtualGroupEntity(
@ColumnInfo(name = "icon_emoji") val iconEmoji: String? = null,
val position: Int = 0,
@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis(),
- @ColumnInfo(name = "content_type") val contentType: String = "LIVE"
+ @ColumnInfo(name = "content_type") val contentType: ContentType = ContentType.LIVE
)
data class CategoryCount(
@@ -311,7 +340,7 @@ data class PlaybackHistoryEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
@ColumnInfo(name = "content_id") val contentId: Long,
- @ColumnInfo(name = "content_type") val contentType: String, // LIVE, MOVIE, SERIES_EPISODE
+ @ColumnInfo(name = "content_type") val contentType: ContentType,
@ColumnInfo(name = "provider_id") val providerId: Long,
val title: String = "",
@ColumnInfo(name = "poster_url") val posterUrl: String? = null,
@@ -325,7 +354,15 @@ data class PlaybackHistoryEntity(
@ColumnInfo(name = "episode_number") val episodeNumber: Int? = null
)
-@Entity(tableName = "sync_metadata")
+@Entity(
+ tableName = "sync_metadata",
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )]
+)
data class SyncMetadataEntity(
@PrimaryKey
@ColumnInfo(name = "provider_id") val providerId: Long,
diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
index 7799b13f..b2d8641b 100644
--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
@@ -24,10 +24,12 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import java.io.InputStreamReader
import java.io.OutputStreamWriter
+import java.security.MessageDigest
import java.util.zip.CRC32
import javax.inject.Inject
import javax.inject.Singleton
+@Singleton
class BackupManagerImpl @Inject constructor(
@ApplicationContext private val context: Context,
private val preferencesRepository: PreferencesRepository,
@@ -92,9 +94,7 @@ class BackupManagerImpl @Inject constructor(
// Compute checksum over the data without checksum field
val jsonWithoutChecksum = gson.toJson(backupData)
- val crc = CRC32()
- crc.update(jsonWithoutChecksum.toByteArray(Charsets.UTF_8))
- val backupWithChecksum = backupData.copy(checksum = crc.value.toString(16))
+ val backupWithChecksum = backupData.copy(checksum = buildSha256Checksum(jsonWithoutChecksum))
// 2. Serialize and write to URI
context.contentResolver.openOutputStream(uri)?.use { outputStream ->
@@ -137,19 +137,19 @@ class BackupManagerImpl @Inject constructor(
existingProviders.any { it.serverUrl == incoming.serverUrl && it.username == incoming.username }
}
val groupConflicts = backupData.virtualGroups.orEmpty().count { incoming ->
- existingGroups.any { it.name.equals(incoming.name, ignoreCase = true) && it.contentType == incoming.contentType.name }
+ existingGroups.any { it.name.equals(incoming.name, ignoreCase = true) && it.contentType == incoming.contentType }
}
val favoriteConflicts = backupData.favorites.orEmpty().count { incoming ->
existingFavorites.any {
it.contentId == incoming.contentId &&
- it.contentType == incoming.contentType.name &&
+ it.contentType == incoming.contentType &&
it.groupId == incoming.groupId
}
}
val historyConflicts = backupData.playbackHistory.orEmpty().count { incoming ->
existingHistory.any {
it.contentId == incoming.contentId &&
- it.contentType == incoming.contentType.name &&
+ it.contentType == incoming.contentType &&
it.providerId == incoming.providerId
}
}
@@ -222,7 +222,7 @@ class BackupManagerImpl @Inject constructor(
return@forEach
}
val entity = provider.copy(
- id = existing?.id ?: provider.id
+ id = existing?.id ?: 0L // 0 = let Room auto-assign PK; avoids ID collision on import
).toSecureEntityForBackup()
providerDao.insert(entity)
}
@@ -231,8 +231,7 @@ class BackupManagerImpl @Inject constructor(
?.toLongOrNull()
?.takeIf { it > 0L }
?.let { activeId ->
- providerDao.deactivateAll()
- providerDao.activate(activeId)
+ providerDao.setActive(activeId)
}
importedSections += "Providers"
} ?: run { skippedSections += "Providers" }
@@ -251,7 +250,7 @@ class BackupManagerImpl @Inject constructor(
groups.forEach { group ->
val conflict = existingGroups.firstOrNull {
it.name.equals(group.name, ignoreCase = true) &&
- it.contentType == group.contentType.name
+ it.contentType == group.contentType
}
if (conflict != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {
return@forEach
@@ -327,9 +326,23 @@ class BackupManagerImpl @Inject constructor(
val storedChecksum = backupData.checksum ?: return true // no checksum = legacy backup, skip verification
val dataWithoutChecksum = backupData.copy(checksum = null)
val json = gson.toJson(dataWithoutChecksum)
+
+ return if (storedChecksum.startsWith(SHA256_PREFIX)) {
+ buildSha256Checksum(json) == storedChecksum
+ } else {
+ verifyLegacyCrc32Checksum(json, storedChecksum)
+ }
+ }
+
+ private fun buildSha256Checksum(json: String): String {
+ val digest = MessageDigest.getInstance("SHA-256").digest(json.toByteArray(Charsets.UTF_8))
+ return SHA256_PREFIX + digest.joinToString(separator = "") { "%02x".format(it) }
+ }
+
+ private fun verifyLegacyCrc32Checksum(json: String, checksum: String): Boolean {
val crc = CRC32()
crc.update(json.toByteArray(Charsets.UTF_8))
- return crc.value.toString(16) == storedChecksum
+ return crc.value.toString(16) == checksum
}
private fun readBackupData(uriString: String): BackupData? {
@@ -344,3 +357,5 @@ class BackupManagerImpl @Inject constructor(
private fun com.streamvault.domain.model.Provider.toSecureEntityForBackup() =
copy(password = CredentialCrypto.encryptIfNeeded(password)).toEntity()
+
+private const val SHA256_PREFIX = "sha256:"
diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt
index a4b1af87..ba30f132 100644
--- a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt
@@ -4,7 +4,9 @@ import android.content.Context
import android.os.StatFs
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.domain.manager.RecordingManager
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.RecordingItem
import com.streamvault.domain.model.RecordingRequest
import com.streamvault.domain.model.RecordingStatus
@@ -23,6 +25,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
@@ -44,7 +47,8 @@ import kotlin.coroutines.coroutineContext
class RecordingManagerImpl @Inject constructor(
@ApplicationContext private val context: Context,
private val gson: Gson,
- private val okHttpClient: OkHttpClient
+ private val okHttpClient: OkHttpClient,
+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : RecordingManager {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -55,11 +59,18 @@ class RecordingManagerImpl @Inject constructor(
private val storageState = MutableStateFlow(readStorageState())
private val stateMutex = Mutex()
private val activeJobs = mutableMapOf<String, Job>()
+ private var lastRetentionSweepMs = 0L
+
+ /** Cancels the background polling coroutine. Call when the manager is no longer needed. */
+ fun cancel() {
+ scope.cancel()
+ }
init {
scope.launch {
while (isActive) {
processSchedules()
+ runRetentionSweepIfDue()
storageState.value = readStorageState()
delay(15_000L)
}
@@ -71,7 +82,9 @@ class RecordingManagerImpl @Inject constructor(
override fun observeStorageState(): Flow<RecordingStorageState> = storageState.asStateFlow()
override suspend fun startManualRecording(request: RecordingRequest): Result<RecordingItem> = withContext(Dispatchers.IO) {
- if (isAdaptiveStream(request.streamUrl)) {
+ val effectiveStreamUrl = resolveRecordingStreamUrl(request.providerId, request.channelId, request.streamUrl)
+ ?: return@withContext Result.error("Recording stream URL could not be resolved.")
+ if (isAdaptiveStream(effectiveStreamUrl)) {
return@withContext Result.error("Live recording currently supports direct stream URLs only. Adaptive streams are not recordable yet.")
}
if (!storageState.value.isWritable) {
@@ -117,11 +130,13 @@ class RecordingManagerImpl @Inject constructor(
removeActiveJob(recordingId)?.cancel()
val item = getItem(recordingId)
?: return@withContext Result.error("Recording not found")
+ val now = System.currentTimeMillis()
val fileLength = item.outputPath?.let { path -> File(path).takeIf { it.exists() }?.length() } ?: 0L
updateItem(recordingId) {
it.copy(
status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,
- scheduledEndMs = System.currentTimeMillis()
+ scheduledEndMs = now,
+ terminalAtMs = now
)
}
Result.success(Unit)
@@ -129,7 +144,26 @@ class RecordingManagerImpl @Inject constructor(
override suspend fun cancelRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {
removeActiveJob(recordingId)?.cancel()
- updateItem(recordingId) { it.copy(status = RecordingStatus.CANCELLED) }
+ val now = System.currentTimeMillis()
+ updateItem(recordingId) {
+ it.copy(
+ status = RecordingStatus.CANCELLED,
+ terminalAtMs = now
+ )
+ }
+ Result.success(Unit)
+ }
+
+ override suspend fun deleteRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {
+ removeActiveJob(recordingId)?.cancel()
+ val item = getItem(recordingId)
+ ?: return@withContext Result.error("Recording not found")
+ if (item.status == RecordingStatus.RECORDING || item.status == RecordingStatus.SCHEDULED) {
+ return@withContext Result.error("Only finished recordings can be deleted.")
+ }
+ deleteOutputFile(item.outputPath)
+ removeItem(recordingId)
+ storageState.value = readStorageState()
Result.success(Unit)
}
@@ -140,11 +174,23 @@ class RecordingManagerImpl @Inject constructor(
snapshot
.filter { it.status == RecordingStatus.SCHEDULED && it.scheduledStartMs <= now }
.forEach { scheduled ->
- if (isAdaptiveStream(scheduled.streamUrl)) {
+ val effectiveStreamUrl = resolveRecordingStreamUrl(scheduled.providerId, scheduled.channelId, scheduled.streamUrl)
+ if (effectiveStreamUrl == null) {
+ val failureTime = System.currentTimeMillis()
updateItemIf(scheduled.id, expectedStatus = RecordingStatus.SCHEDULED) {
it.copy(
status = RecordingStatus.FAILED,
- failureReason = "Scheduled recording supports direct stream URLs only."
+ failureReason = "Recording stream URL could not be resolved.",
+ terminalAtMs = failureTime
+ )
+ }
+ } else if (isAdaptiveStream(effectiveStreamUrl)) {
+ val failureTime = System.currentTimeMillis()
+ updateItemIf(scheduled.id, expectedStatus = RecordingStatus.SCHEDULED) {
+ it.copy(
+ status = RecordingStatus.FAILED,
+ failureReason = "Scheduled recording supports direct stream URLs only.",
+ terminalAtMs = failureTime
)
}
} else {
@@ -165,7 +211,8 @@ class RecordingManagerImpl @Inject constructor(
updateItemIf(stopCandidate.id, expectedStatus = RecordingStatus.RECORDING) {
it.copy(
status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,
- scheduledEndMs = now
+ scheduledEndMs = now,
+ terminalAtMs = now
)
}
}
@@ -178,18 +225,28 @@ class RecordingManagerImpl @Inject constructor(
runCatching {
captureStreamToFile(item, outputFile)
}.onSuccess {
+ val completedAt = System.currentTimeMillis()
updateItemIf(item.id, expectedStatus = RecordingStatus.RECORDING) { current ->
- current.copy(status = RecordingStatus.COMPLETED)
+ current.copy(status = RecordingStatus.COMPLETED, terminalAtMs = completedAt)
}
}.onFailure { error ->
if (error is CancellationException) {
+ val cancelledAt = System.currentTimeMillis()
val fileLength = outputFile.takeIf { it.exists() }?.length() ?: 0L
updateItemIf(item.id, expectedStatus = RecordingStatus.RECORDING) { current ->
- current.copy(status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED)
+ current.copy(
+ status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,
+ terminalAtMs = cancelledAt
+ )
}
} else {
+ val failureTime = System.currentTimeMillis()
updateItemIf(item.id, expectedStatus = RecordingStatus.RECORDING) { current ->
- current.copy(status = RecordingStatus.FAILED, failureReason = error.message)
+ current.copy(
+ status = RecordingStatus.FAILED,
+ failureReason = error.message,
+ terminalAtMs = failureTime
+ )
}
}
}
@@ -205,12 +262,14 @@ class RecordingManagerImpl @Inject constructor(
}
private suspend fun captureStreamToFile(item: RecordingItem, outputFile: File) {
+ val resolvedUrl = resolveRecordingStreamUrl(item.providerId, item.channelId, item.streamUrl)
+ ?: throw IOException("Recording stream URL could not be resolved")
var attempt = 0
var retryDelayMs = 1_000L
while (true) {
currentCoroutineContext().ensureActive()
try {
- streamResponseBody(item.streamUrl, outputFile)
+ streamResponseBody(resolvedUrl, outputFile)
return
} catch (error: Throwable) {
if (error is CancellationException || !isRetryableRecordingError(error) || attempt >= MAX_RECORDING_RETRIES) {
@@ -240,7 +299,9 @@ class RecordingManagerImpl @Inject constructor(
private fun persistStateLocked() {
stateFile.parentFile?.mkdirs()
- stateFile.writeText(gson.toJson(itemsState.value))
+ val tmpFile = File(stateFile.parentFile, "${stateFile.name}.tmp")
+ tmpFile.writeText(gson.toJson(itemsState.value))
+ tmpFile.renameTo(stateFile)
}
private fun loadState(): List<RecordingItem> {
@@ -256,6 +317,15 @@ class RecordingManagerImpl @Inject constructor(
return lower.contains(".m3u8") || lower.contains(".mpd")
}
+ private suspend fun resolveRecordingStreamUrl(providerId: Long, channelId: Long, logicalUrl: String): String? {
+ return xtreamStreamUrlResolver.resolve(
+ url = logicalUrl,
+ fallbackProviderId = providerId,
+ fallbackStreamId = channelId,
+ fallbackContentType = ContentType.LIVE
+ )
+ }
+
private suspend fun appendItem(item: RecordingItem) {
stateMutex.withLock {
itemsState.value = itemsState.value + item
@@ -263,6 +333,13 @@ class RecordingManagerImpl @Inject constructor(
}
}
+ private suspend fun removeItem(recordingId: String): RecordingItem? = stateMutex.withLock {
+ val existing = itemsState.value.firstOrNull { it.id == recordingId } ?: return@withLock null
+ itemsState.value = itemsState.value.filterNot { it.id == recordingId }
+ persistStateLocked()
+ existing
+ }
+
private suspend fun getItem(recordingId: String): RecordingItem? =
stateMutex.withLock { itemsState.value.firstOrNull { it.id == recordingId } }
@@ -306,6 +383,40 @@ class RecordingManagerImpl @Inject constructor(
private suspend fun removeActiveJob(recordingId: String): Job? =
stateMutex.withLock { activeJobs.remove(recordingId) }
+ private suspend fun runRetentionSweepIfDue() {
+ val now = System.currentTimeMillis()
+ if (now - lastRetentionSweepMs < RETENTION_SWEEP_INTERVAL_MS) {
+ return
+ }
+ lastRetentionSweepMs = now
+
+ val expiredIds = stateMutex.withLock {
+ itemsState.value
+ .filter { item ->
+ item.status.isTerminal() &&
+ item.terminalAtMs?.let { terminalAt -> now - terminalAt >= FINISHED_RECORDING_RETENTION_MS } == true
+ }
+ .map(RecordingItem::id)
+ }
+ if (expiredIds.isEmpty()) {
+ return
+ }
+ expiredIds.forEach { recordingId ->
+ val removed = removeItem(recordingId)
+ deleteOutputFile(removed?.outputPath)
+ }
+ }
+
+ private fun deleteOutputFile(path: String?) {
+ if (path.isNullOrBlank()) return
+ runCatching {
+ val file = File(path)
+ if (file.exists()) {
+ file.delete()
+ }
+ }
+ }
+
private suspend fun streamResponseBody(url: String, outputFile: File) {
val request = Request.Builder().url(url).get().build()
val call = okHttpClient.newCall(request)
@@ -319,7 +430,7 @@ class RecordingManagerImpl @Inject constructor(
ensureSuccessfulRecordingResponse(response)
val body = response.body ?: throw IOException("Recording stream returned an empty body")
body.byteStream().use { input ->
- FileOutputStream(outputFile, true).use { output ->
+ FileOutputStream(outputFile, false).use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
currentCoroutineContext().ensureActive()
@@ -361,5 +472,15 @@ class RecordingManagerImpl @Inject constructor(
private companion object {
const val MAX_RECORDING_RETRIES = 3
+ const val FINISHED_RECORDING_RETENTION_MS = 30L * 24L * 60L * 60L * 1000L
+ const val RETENTION_SWEEP_INTERVAL_MS = 60L * 60L * 1000L
}
}
+
+private fun RecordingStatus.isTerminal(): Boolean = when (this) {
+ RecordingStatus.SCHEDULED,
+ RecordingStatus.RECORDING -> false
+ RecordingStatus.COMPLETED,
+ RecordingStatus.FAILED,
+ RecordingStatus.CANCELLED -> true
+}
diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
index 84b48a9e..ecffcd0b 100644
--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
@@ -8,7 +8,7 @@ import com.streamvault.domain.model.*
fun ProviderEntity.toDomain() = Provider(
id = id,
name = name,
- type = ProviderType.valueOf(type),
+ type = type,
serverUrl = serverUrl,
username = username,
password = password,
@@ -17,7 +17,7 @@ fun ProviderEntity.toDomain() = Provider(
isActive = isActive,
maxConnections = maxConnections,
expirationDate = expirationDate,
- status = try { ProviderStatus.valueOf(status) } catch (_: Exception) { ProviderStatus.UNKNOWN },
+ status = status,
lastSyncedAt = lastSyncedAt,
createdAt = createdAt
)
@@ -25,7 +25,7 @@ fun ProviderEntity.toDomain() = Provider(
fun Provider.toEntity() = ProviderEntity(
id = id,
name = name,
- type = type.name,
+ type = type,
serverUrl = serverUrl,
username = username,
password = password,
@@ -34,7 +34,7 @@ fun Provider.toEntity() = ProviderEntity(
isActive = isActive,
maxConnections = maxConnections,
expirationDate = expirationDate,
- status = status.name,
+ status = status,
lastSyncedAt = lastSyncedAt,
createdAt = createdAt
)
@@ -239,9 +239,10 @@ fun Episode.toEntity() = EpisodeEntity(
fun CategoryEntity.toDomain() = com.streamvault.domain.model.Category(
id = categoryId,
+ roomId = id,
name = name,
parentId = parentId,
- type = try { ContentType.valueOf(type) } catch (_: Exception) { ContentType.LIVE },
+ type = type,
isAdult = isAdult,
isUserProtected = isUserProtected
)
@@ -250,7 +251,7 @@ fun com.streamvault.domain.model.Category.toEntity(providerId: Long) = CategoryE
categoryId = id,
name = name,
parentId = parentId,
- type = type.name,
+ type = type,
providerId = providerId,
isAdult = isAdult,
isUserProtected = isUserProtected
@@ -287,7 +288,7 @@ fun Program.toEntity() = ProgramEntity(
fun FavoriteEntity.toDomain() = Favorite(
id = id,
contentId = contentId,
- contentType = try { ContentType.valueOf(contentType) } catch (_: Exception) { ContentType.LIVE },
+ contentType = contentType,
position = position,
groupId = groupId,
addedAt = addedAt
@@ -296,7 +297,7 @@ fun FavoriteEntity.toDomain() = Favorite(
fun Favorite.toEntity() = FavoriteEntity(
id = id,
contentId = contentId,
- contentType = contentType.name,
+ contentType = contentType,
position = position,
groupId = groupId,
addedAt = addedAt
@@ -310,7 +311,7 @@ fun VirtualGroupEntity.toDomain() = VirtualGroup(
iconEmoji = iconEmoji,
position = position,
createdAt = createdAt,
- contentType = try { ContentType.valueOf(contentType) } catch (_: Exception) { ContentType.LIVE }
+ contentType = contentType
)
fun VirtualGroup.toEntity() = VirtualGroupEntity(
@@ -319,7 +320,7 @@ fun VirtualGroup.toEntity() = VirtualGroupEntity(
iconEmoji = iconEmoji,
position = position,
createdAt = createdAt,
- contentType = contentType.name
+ contentType = contentType
)
// ── Playback History ───────────────────────────────────────────────
@@ -327,7 +328,7 @@ fun VirtualGroup.toEntity() = VirtualGroupEntity(
fun PlaybackHistoryEntity.toDomain() = PlaybackHistory(
id = id,
contentId = contentId,
- contentType = try { ContentType.valueOf(contentType) } catch (_: Exception) { ContentType.MOVIE },
+ contentType = contentType,
providerId = providerId,
title = title,
posterUrl = posterUrl,
@@ -344,7 +345,7 @@ fun PlaybackHistoryEntity.toDomain() = PlaybackHistory(
fun PlaybackHistory.toEntity() = PlaybackHistoryEntity(
id = id,
contentId = contentId,
- contentType = contentType.name,
+ contentType = contentType,
providerId = providerId,
title = title,
posterUrl = posterUrl,
diff --git a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
index 761e996d..e470bede 100644
--- a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
+++ b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
@@ -74,7 +74,9 @@ class M3uParser {
pendingExtinf = parseExtinf(line)
}
line.startsWith("#") -> {
- pendingExtinf = null
+ // Preserve pendingExtinf across known directives that appear
+ // between #EXTINF and the stream URL (e.g. #EXTVLCOPT, #EXTGRP,
+ // #KODIPROP, #EXTATTRPARAM). Only reset on another #EXTINF.
}
pendingExtinf != null -> {
val extinf = pendingExtinf
@@ -84,7 +86,7 @@ class M3uParser {
pendingExtinf = null
}
else -> {
- pendingExtinf = null
+ // Non-comment, non-URL line with no pending EXTINF — skip
}
}
}
@@ -119,7 +121,9 @@ class M3uParser {
pendingExtinf = parseExtinf(line)
}
line.startsWith("#") -> {
- pendingExtinf = null
+ // Preserve pendingExtinf across known directives that appear
+ // between #EXTINF and the stream URL (e.g. #EXTVLCOPT, #EXTGRP,
+ // #KODIPROP, #EXTATTRPARAM). Only reset on another #EXTINF.
}
pendingExtinf != null -> {
val extinf = pendingExtinf
@@ -129,7 +133,7 @@ class M3uParser {
pendingExtinf = null
}
else -> {
- pendingExtinf = null
+ // Non-comment, non-URL line with no pending EXTINF — skip
}
}
}
@@ -365,7 +369,7 @@ class M3uParser {
return attributes
}
- private fun isVodEntry(entry: M3uEntry): Boolean {
+ internal fun isVodEntry(entry: M3uEntry): Boolean {
val url = entry.url.lowercase()
val group = entry.groupTitle.lowercase()
@@ -387,7 +391,10 @@ class M3uParser {
return allowedPrefixes.any { lower.startsWith(it) }
}
- private companion object {
+ companion object {
+ /** Exposed for callers outside M3uParser (e.g. SyncManager) to avoid duplicate logic. */
+ fun isVodEntry(entry: M3uEntry): Boolean = M3uParser().isVodEntry(entry)
+
val knownAttributes = setOf(
"tvg-id",
"tvg-name",
diff --git a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt b/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt
index 8de7e7ac..96ab6860 100644
--- a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt
+++ b/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt
@@ -34,6 +34,10 @@ class XmltvParser {
SimpleDateFormat("yyyyMMdd", Locale.US)
).onEach { it.timeZone = TimeZone.getTimeZone("UTC") }
+ @Deprecated(
+ message = "Loads all programs into memory. Use parseStreaming() for large EPG files.",
+ replaceWith = ReplaceWith("parseStreaming(inputStream, onProgram)")
+ )
fun parse(inputStream: InputStream): List<Program> {
val programs = mutableListOf<Program>()
diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
index 0d531dde..23cca611 100644
--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
@@ -9,11 +9,16 @@ import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
+import com.streamvault.data.local.dao.ChannelPreferenceDao
+import com.streamvault.data.local.entity.ChannelPreferenceEntity
import java.security.SecureRandom
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
@@ -24,7 +29,8 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(na
@Singleton
class PreferencesRepository @Inject constructor(
- @ApplicationContext private val context: Context
+ @ApplicationContext private val context: Context,
+ private val channelPreferenceDao: ChannelPreferenceDao
) {
companion object {
private const val PIN_SALT_BYTES = 16
@@ -72,6 +78,8 @@ class PreferencesRepository @Inject constructor(
preferences[PreferencesKeys.PARENTAL_CONTROL_LEVEL] ?: 1 // Default to 1 = LOCKED
}
+ val hasParentalPin: Flow<Boolean> = context.dataStore.data.map(::hasStoredParentalPin)
+
suspend fun setLastActiveProviderId(id: Long) {
context.dataStore.edit { preferences ->
preferences[PreferencesKeys.LAST_ACTIVE_PROVIDER_ID] = id
@@ -120,14 +128,10 @@ class PreferencesRepository @Inject constructor(
}
val legacyPin = preferences[PreferencesKeys.LEGACY_PARENTAL_PIN]
- val valid = if (!legacyPin.isNullOrBlank()) {
- pin == legacyPin
- } else {
- pin == "0000"
- }
+ val valid = !legacyPin.isNullOrBlank() && pin == legacyPin
if (valid) {
- // One-way migrate legacy/default behavior to hashed PIN storage.
+ // One-way migrate legacy PIN storage to hashed PIN storage.
setParentalPin(pin)
}
@@ -281,21 +285,36 @@ class PreferencesRepository @Inject constructor(
}
}
+ @OptIn(ExperimentalCoroutinesApi::class)
fun getAspectRatioForChannel(channelId: Long): Flow<String?> {
- val key = stringPreferencesKey("aspect_ratio_$channelId")
- return context.dataStore.data.map { preferences ->
- preferences[key]
+ return channelPreferenceDao.observeAspectRatio(channelId).flatMapLatest { persistedRatio ->
+ if (persistedRatio != null) {
+ flowOf(persistedRatio)
+ } else {
+ val legacyKey = stringPreferencesKey("aspect_ratio_$channelId")
+ context.dataStore.data.map { preferences ->
+ preferences[legacyKey]
+ }
+ }
}
}
suspend fun setAspectRatioForChannel(channelId: Long, ratio: String) {
+ channelPreferenceDao.upsert(
+ ChannelPreferenceEntity(
+ channelId = channelId,
+ aspectRatio = ratio,
+ updatedAt = System.currentTimeMillis()
+ )
+ )
val key = stringPreferencesKey("aspect_ratio_$channelId")
context.dataStore.edit { preferences ->
- preferences[key] = ratio
+ preferences.remove(key)
}
}
suspend fun clearAllRecentData() {
+ channelPreferenceDao.deleteAll()
context.dataStore.edit { preferences ->
val keysToRemove = preferences.asMap().keys.filter { key ->
key.name.startsWith("last_live_category_id_") ||
@@ -313,4 +332,14 @@ class PreferencesRepository @Inject constructor(
val secret = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec)
return java.util.Base64.getEncoder().encodeToString(secret.encoded)
}
+
+ private fun hasStoredParentalPin(preferences: Preferences): Boolean {
+ val storedHash = preferences[PreferencesKeys.PARENTAL_PIN_HASH]
+ val storedSaltBase64 = preferences[PreferencesKeys.PARENTAL_PIN_SALT]
+ if (!storedHash.isNullOrBlank() && !storedSaltBase64.isNullOrBlank()) {
+ return true
+ }
+
+ return !preferences[PreferencesKeys.LEGACY_PARENTAL_PIN].isNullOrBlank()
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt b/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt
new file mode 100644
index 00000000..7cd40efc
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt
@@ -0,0 +1,7 @@
+package com.streamvault.data.remote
+
+object NetworkTimeoutConfig {
+ const val CONNECT_TIMEOUT_SECONDS = 30L
+ const val READ_TIMEOUT_SECONDS = 30L
+ const val WRITE_TIMEOUT_SECONDS = 30L
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt b/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt
new file mode 100644
index 00000000..eb2eef28
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt
@@ -0,0 +1,79 @@
+package com.streamvault.data.remote.dto
+
+import kotlinx.serialization.ExperimentalSerializationApi
+import kotlinx.serialization.KSerializer
+import kotlinx.serialization.SerializationException
+import kotlinx.serialization.descriptors.PrimitiveKind
+import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
+import kotlinx.serialization.descriptors.SerialDescriptor
+import kotlinx.serialization.encoding.Decoder
+import kotlinx.serialization.encoding.Encoder
+import kotlinx.serialization.json.JsonDecoder
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonPrimitive
+
+@OptIn(ExperimentalSerializationApi::class)
+object LenientIntSerializer : KSerializer<Int> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LenientInt", PrimitiveKind.INT)
+
+ override fun deserialize(decoder: Decoder): Int = decodePrimitive(decoder)?.toIntOrNull() ?: 0
+
+ override fun serialize(encoder: Encoder, value: Int) {
+ encoder.encodeInt(value)
+ }
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+object LenientNullableIntSerializer : KSerializer<Int?> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LenientNullableInt", PrimitiveKind.INT)
+
+ override fun deserialize(decoder: Decoder): Int? = decodePrimitive(decoder)?.toIntOrNull()
+
+ override fun serialize(encoder: Encoder, value: Int?) {
+ if (value == null) {
+ encoder.encodeNull()
+ } else {
+ encoder.encodeInt(value)
+ }
+ }
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+object LenientLongSerializer : KSerializer<Long> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LenientLong", PrimitiveKind.LONG)
+
+ override fun deserialize(decoder: Decoder): Long = decodePrimitive(decoder)?.toLongOrNull() ?: 0L
+
+ override fun serialize(encoder: Encoder, value: Long) {
+ encoder.encodeLong(value)
+ }
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+object LenientNullableLongSerializer : KSerializer<Long?> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LenientNullableLong", PrimitiveKind.LONG)
+
+ override fun deserialize(decoder: Decoder): Long? = decodePrimitive(decoder)?.toLongOrNull()
+
+ override fun serialize(encoder: Encoder, value: Long?) {
+ if (value == null) {
+ encoder.encodeNull()
+ } else {
+ encoder.encodeLong(value)
+ }
+ }
+}
+
+private fun decodePrimitive(decoder: Decoder): String? {
+ return when (decoder) {
+ is JsonDecoder -> decoder.decodeJsonElement().primitiveContentOrNull()
+ else -> runCatching { decoder.decodeString() }.getOrNull()
+ }
+}
+
+private fun JsonElement.primitiveContentOrNull(): String? {
+ if (this == JsonNull) return null
+ val primitive = this as? JsonPrimitive ?: throw SerializationException("Expected JSON primitive")
+ return if (primitive.isString) primitive.content else primitive.toString()
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt b/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
index 0106cf42..2078f2bf 100644
--- a/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
+++ b/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
@@ -1,163 +1,179 @@
package com.streamvault.data.remote.dto
-import com.google.gson.annotations.SerializedName
+import kotlinx.serialization.SerialName
+import kotlinx.serialization.Serializable
+@Serializable
data class XtreamAuthResponse(
- @SerializedName("user_info") val userInfo: XtreamUserInfo,
- @SerializedName("server_info") val serverInfo: XtreamServerInfo
+ @SerialName("user_info") val userInfo: XtreamUserInfo,
+ @SerialName("server_info") val serverInfo: XtreamServerInfo
)
+@Serializable
data class XtreamUserInfo(
- @SerializedName("username") val username: String = "",
- @SerializedName("password") val password: String = "",
- @SerializedName("message") val message: String = "",
- @SerializedName("auth") val auth: Int = 0,
- @SerializedName("status") val status: String = "",
- @SerializedName("exp_date") val expDate: String? = null,
- @SerializedName("is_trial") val isTrial: String = "0",
- @SerializedName("active_cons") val activeConnections: String = "0",
- @SerializedName("created_at") val createdAt: String = "",
- @SerializedName("max_connections") val maxConnections: String = "1",
- @SerializedName("allowed_output_formats") val allowedOutputFormats: List<String> = emptyList()
+ @SerialName("username") val username: String = "",
+ @SerialName("password") val password: String = "",
+ @SerialName("message") val message: String = "",
+ @SerialName("auth") @Serializable(with = LenientIntSerializer::class) val auth: Int = 0,
+ @SerialName("status") val status: String = "",
+ @SerialName("exp_date") val expDate: String? = null,
+ @SerialName("is_trial") val isTrial: String = "0",
+ @SerialName("active_cons") val activeConnections: String = "0",
+ @SerialName("created_at") val createdAt: String = "",
+ @SerialName("max_connections") val maxConnections: String = "1",
+ @SerialName("allowed_output_formats") val allowedOutputFormats: List<String> = emptyList()
)
+@Serializable
data class XtreamServerInfo(
- @SerializedName("url") val url: String = "",
- @SerializedName("port") val port: String = "",
- @SerializedName("https_port") val httpsPort: String = "",
- @SerializedName("server_protocol") val serverProtocol: String = "http",
- @SerializedName("rtmp_port") val rtmpPort: String = "",
- @SerializedName("timezone") val timezone: String = "",
- @SerializedName("timestamp_now") val timestampNow: Long = 0,
- @SerializedName("time_now") val timeNow: String = ""
+ @SerialName("url") val url: String = "",
+ @SerialName("port") val port: String = "",
+ @SerialName("https_port") val httpsPort: String = "",
+ @SerialName("server_protocol") val serverProtocol: String = "http",
+ @SerialName("rtmp_port") val rtmpPort: String = "",
+ @SerialName("timezone") val timezone: String = "",
+ @SerialName("timestamp_now") @Serializable(with = LenientLongSerializer::class) val timestampNow: Long = 0,
+ @SerialName("time_now") val timeNow: String = ""
)
+@Serializable
data class XtreamCategory(
- @SerializedName("category_id") val categoryId: String = "0",
- @SerializedName("category_name") val categoryName: String = "",
- @SerializedName("parent_id") val parentId: Int = 0
+ @SerialName("category_id") val categoryId: String = "0",
+ @SerialName("category_name") val categoryName: String = "",
+ @SerialName("parent_id") @Serializable(with = LenientIntSerializer::class) val parentId: Int = 0
)
+@Serializable
data class XtreamStream(
- @SerializedName("num") val num: Int = 0,
- @SerializedName("name") val name: String = "",
- @SerializedName("stream_type") val streamType: String = "",
- @SerializedName("stream_id") val streamId: Long = 0,
- @SerializedName("stream_icon") val streamIcon: String? = null,
- @SerializedName("epg_channel_id") val epgChannelId: String? = null,
- @SerializedName("added") val added: String? = null,
- @SerializedName("category_id") val categoryId: String? = null,
- @SerializedName("category_name") val categoryName: String? = null,
- @SerializedName("custom_sid") val customSid: String? = null,
- @SerializedName("tv_archive") val tvArchive: Int = 0,
- @SerializedName("direct_source") val directSource: String? = null,
- @SerializedName("tv_archive_duration") val tvArchiveDuration: Int? = null,
- @SerializedName("container_extension") val containerExtension: String? = null,
- @SerializedName("rating") val rating: String? = null,
- @SerializedName("rating_5based") val rating5based: String? = null
+ @SerialName("num") @Serializable(with = LenientIntSerializer::class) val num: Int = 0,
+ @SerialName("name") val name: String = "",
+ @SerialName("stream_type") val streamType: String = "",
+ @SerialName("stream_id") @Serializable(with = LenientLongSerializer::class) val streamId: Long = 0,
+ @SerialName("stream_icon") val streamIcon: String? = null,
+ @SerialName("epg_channel_id") val epgChannelId: String? = null,
+ @SerialName("added") val added: String? = null,
+ @SerialName("category_id") val categoryId: String? = null,
+ @SerialName("category_name") val categoryName: String? = null,
+ @SerialName("custom_sid") val customSid: String? = null,
+ @SerialName("tv_archive") @Serializable(with = LenientIntSerializer::class) val tvArchive: Int = 0,
+ @SerialName("direct_source") val directSource: String? = null,
+ @SerialName("tv_archive_duration") @Serializable(with = LenientNullableIntSerializer::class) val tvArchiveDuration: Int? = null,
+ @SerialName("container_extension") val containerExtension: String? = null,
+ @SerialName("rating") val rating: String? = null,
+ @SerialName("rating_5based") val rating5based: String? = null
)
+@Serializable
data class XtreamSeriesItem(
- @SerializedName("series_id") val seriesId: Long = 0,
- @SerializedName("name") val name: String = "",
- @SerializedName("cover") val cover: String? = null,
- @SerializedName("plot") val plot: String? = null,
- @SerializedName("cast") val cast: String? = null,
- @SerializedName("director") val director: String? = null,
- @SerializedName("genre") val genre: String? = null,
- @SerializedName("releaseDate") val releaseDate: String? = null,
- @SerializedName("rating") val rating: String? = null,
- @SerializedName("rating_5based") val rating5based: String? = null,
- @SerializedName("backdrop_path") val backdropPath: List<String>? = null,
- @SerializedName("youtube_trailer") val youtubeTrailer: String? = null,
- @SerializedName("episode_run_time") val episodeRunTime: String? = null,
- @SerializedName("category_id") val categoryId: String? = null,
- @SerializedName("last_modified") val lastModified: String? = null
+ @SerialName("series_id") @Serializable(with = LenientLongSerializer::class) val seriesId: Long = 0,
+ @SerialName("name") val name: String = "",
+ @SerialName("cover") val cover: String? = null,
+ @SerialName("plot") val plot: String? = null,
+ @SerialName("cast") val cast: String? = null,
+ @SerialName("director") val director: String? = null,
+ @SerialName("genre") val genre: String? = null,
+ @SerialName("releaseDate") val releaseDate: String? = null,
+ @SerialName("rating") val rating: String? = null,
+ @SerialName("rating_5based") val rating5based: String? = null,
+ @SerialName("backdrop_path") val backdropPath: List<String>? = null,
+ @SerialName("youtube_trailer") val youtubeTrailer: String? = null,
+ @SerialName("episode_run_time") val episodeRunTime: String? = null,
+ @SerialName("category_id") val categoryId: String? = null,
+ @SerialName("last_modified") val lastModified: String? = null
)
+@Serializable
data class XtreamSeriesInfoResponse(
- @SerializedName("info") val info: XtreamSeriesItem? = null,
- @SerializedName("episodes") val episodes: Map<String, List<XtreamEpisode>> = emptyMap(),
- @SerializedName("seasons") val seasons: List<XtreamSeason> = emptyList()
+ @SerialName("info") val info: XtreamSeriesItem? = null,
+ @SerialName("episodes") val episodes: Map<String, List<XtreamEpisode>> = emptyMap(),
+ @SerialName("seasons") val seasons: List<XtreamSeason> = emptyList()
)
+@Serializable
data class XtreamSeason(
- @SerializedName("season_number") val seasonNumber: Int = 0,
- @SerializedName("name") val name: String = "",
- @SerializedName("cover") val cover: String? = null,
- @SerializedName("air_date") val airDate: String? = null,
- @SerializedName("episode_count") val episodeCount: Int = 0
+ @SerialName("season_number") @Serializable(with = LenientIntSerializer::class) val seasonNumber: Int = 0,
+ @SerialName("name") val name: String = "",
+ @SerialName("cover") val cover: String? = null,
+ @SerialName("air_date") val airDate: String? = null,
+ @SerialName("episode_count") @Serializable(with = LenientIntSerializer::class) val episodeCount: Int = 0
)
+@Serializable
data class XtreamEpisode(
- @SerializedName("id") val id: String = "",
- @SerializedName("episode_num") val episodeNum: Int = 0,
- @SerializedName("title") val title: String = "",
- @SerializedName("container_extension") val containerExtension: String? = null,
- @SerializedName("custom_sid") val customSid: String? = null,
- @SerializedName("added") val added: String? = null,
- @SerializedName("season") val season: Int = 0,
- @SerializedName("direct_source") val directSource: String? = null,
- @SerializedName("info") val info: XtreamEpisodeInfo? = null
+ @SerialName("id") val id: String = "",
+ @SerialName("episode_num") @Serializable(with = LenientIntSerializer::class) val episodeNum: Int = 0,
+ @SerialName("title") val title: String = "",
+ @SerialName("container_extension") val containerExtension: String? = null,
+ @SerialName("custom_sid") val customSid: String? = null,
+ @SerialName("added") val added: String? = null,
+ @SerialName("season") @Serializable(with = LenientIntSerializer::class) val season: Int = 0,
+ @SerialName("direct_source") val directSource: String? = null,
+ @SerialName("info") val info: XtreamEpisodeInfo? = null
)
+@Serializable
data class XtreamEpisodeInfo(
- @SerializedName("movie_image") val movieImage: String? = null,
- @SerializedName("plot") val plot: String? = null,
- @SerializedName("releasedate") val releaseDate: String? = null,
- @SerializedName("rating") val rating: String? = null,
- @SerializedName("duration_secs") val durationSecs: Int = 0,
- @SerializedName("duration") val duration: String? = null,
- @SerializedName("name") val name: String? = null,
- @SerializedName("bitrate") val bitrate: Int = 0
+ @SerialName("movie_image") val movieImage: String? = null,
+ @SerialName("plot") val plot: String? = null,
+ @SerialName("releasedate") val releaseDate: String? = null,
+ @SerialName("rating") val rating: String? = null,
+ @SerialName("duration_secs") @Serializable(with = LenientIntSerializer::class) val durationSecs: Int = 0,
+ @SerialName("duration") val duration: String? = null,
+ @SerialName("name") val name: String? = null,
+ @SerialName("bitrate") @Serializable(with = LenientIntSerializer::class) val bitrate: Int = 0
)
+@Serializable
data class XtreamVodInfoResponse(
- @SerializedName("info") val info: XtreamVodInfo? = null,
- @SerializedName("movie_data") val movieData: XtreamVodMovieData? = null
+ @SerialName("info") val info: XtreamVodInfo? = null,
+ @SerialName("movie_data") val movieData: XtreamVodMovieData? = null
)
+@Serializable
data class XtreamVodInfo(
- @SerializedName("movie_image") val movieImage: String? = null,
- @SerializedName("tmdb_id") val tmdbId: Long? = null,
- @SerializedName("plot") val plot: String? = null,
- @SerializedName("cast") val cast: String? = null,
- @SerializedName("director") val director: String? = null,
- @SerializedName("genre") val genre: String? = null,
- @SerializedName("releasedate") val releaseDate: String? = null,
- @SerializedName("rating") val rating: String? = null,
- @SerializedName("youtube_trailer") val youtubeTrailer: String? = null,
- @SerializedName("duration_secs") val durationSecs: Int = 0,
- @SerializedName("duration") val duration: String? = null,
- @SerializedName("backdrop_path") val backdropPath: List<String>? = null,
- @SerializedName("bitrate") val bitrate: Int = 0
+ @SerialName("movie_image") val movieImage: String? = null,
+ @SerialName("tmdb_id") @Serializable(with = LenientNullableLongSerializer::class) val tmdbId: Long? = null,
+ @SerialName("plot") val plot: String? = null,
+ @SerialName("cast") val cast: String? = null,
+ @SerialName("director") val director: String? = null,
+ @SerialName("genre") val genre: String? = null,
+ @SerialName("releasedate") val releaseDate: String? = null,
+ @SerialName("rating") val rating: String? = null,
+ @SerialName("youtube_trailer") val youtubeTrailer: String? = null,
+ @SerialName("duration_secs") @Serializable(with = LenientIntSerializer::class) val durationSecs: Int = 0,
+ @SerialName("duration") val duration: String? = null,
+ @SerialName("backdrop_path") val backdropPath: List<String>? = null,
+ @SerialName("bitrate") @Serializable(with = LenientIntSerializer::class) val bitrate: Int = 0
)
+@Serializable
data class XtreamVodMovieData(
- @SerializedName("stream_id") val streamId: Long = 0,
- @SerializedName("name") val name: String = "",
- @SerializedName("added") val added: String? = null,
- @SerializedName("category_id") val categoryId: String? = null,
- @SerializedName("container_extension") val containerExtension: String? = null,
- @SerializedName("custom_sid") val customSid: String? = null,
- @SerializedName("direct_source") val directSource: String? = null
+ @SerialName("stream_id") @Serializable(with = LenientLongSerializer::class) val streamId: Long = 0,
+ @SerialName("name") val name: String = "",
+ @SerialName("added") val added: String? = null,
+ @SerialName("category_id") val categoryId: String? = null,
+ @SerialName("container_extension") val containerExtension: String? = null,
+ @SerialName("custom_sid") val customSid: String? = null,
+ @SerialName("direct_source") val directSource: String? = null
)
+@Serializable
data class XtreamEpgResponse(
- @SerializedName("epg_listings") val epgListings: List<XtreamEpgListing> = emptyList()
+ @SerialName("epg_listings") val epgListings: List<XtreamEpgListing> = emptyList()
)
+@Serializable
data class XtreamEpgListing(
- @SerializedName("id") val id: String = "",
- @SerializedName("epg_id") val epgId: String = "",
- @SerializedName("title") val title: String = "",
- @SerializedName("lang") val lang: String = "",
- @SerializedName("start") val start: String = "",
- @SerializedName("end") val end: String = "",
- @SerializedName("description") val description: String = "",
- @SerializedName("channel_id") val channelId: String = "",
- @SerializedName("start_timestamp") val startTimestamp: Long = 0,
- @SerializedName("stop_timestamp") val stopTimestamp: Long = 0,
- @SerializedName("now_playing") val nowPlaying: Int = 0,
- @SerializedName("has_archive") val hasArchive: Int = 0
+ @SerialName("id") val id: String = "",
+ @SerialName("epg_id") val epgId: String = "",
+ @SerialName("title") val title: String = "",
+ @SerialName("lang") val lang: String = "",
+ @SerialName("start") val start: String = "",
+ @SerialName("end") val end: String = "",
+ @SerialName("description") val description: String = "",
+ @SerialName("channel_id") val channelId: String = "",
+ @SerialName("start_timestamp") @Serializable(with = LenientLongSerializer::class) val startTimestamp: Long = 0,
+ @SerialName("stop_timestamp") @Serializable(with = LenientLongSerializer::class) val stopTimestamp: Long = 0,
+ @SerialName("now_playing") @Serializable(with = LenientIntSerializer::class) val nowPlaying: Int = 0,
+ @SerialName("has_archive") @Serializable(with = LenientIntSerializer::class) val hasArchive: Int = 0
)
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt b/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt
new file mode 100644
index 00000000..56aad724
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt
@@ -0,0 +1,58 @@
+package com.streamvault.data.remote.xtream
+
+import com.streamvault.data.remote.dto.XtreamAuthResponse
+import com.streamvault.data.remote.dto.XtreamCategory
+import com.streamvault.data.remote.dto.XtreamEpgResponse
+import com.streamvault.data.remote.dto.XtreamSeriesInfoResponse
+import com.streamvault.data.remote.dto.XtreamSeriesItem
+import com.streamvault.data.remote.dto.XtreamStream
+import com.streamvault.data.remote.dto.XtreamVodInfoResponse
+import java.io.IOException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.Json
+import okhttp3.OkHttpClient
+import okhttp3.Request
+
+class OkHttpXtreamApiService(
+ private val client: OkHttpClient,
+ private val json: Json
+) : XtreamApiService {
+
+ override suspend fun authenticate(endpoint: String): XtreamAuthResponse = get(endpoint)
+
+ override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
+
+ override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = get(endpoint)
+
+ override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
+
+ override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = get(endpoint)
+
+ override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = get(endpoint)
+
+ override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
+
+ override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = get(endpoint)
+
+ override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse = get(endpoint)
+
+ override suspend fun getShortEpg(endpoint: String): XtreamEpgResponse = get(endpoint)
+
+ override suspend fun getFullEpg(endpoint: String): XtreamEpgResponse = get(endpoint)
+
+ private suspend inline fun <reified T> get(endpoint: String): T = withContext(Dispatchers.IO) {
+ val request = Request.Builder()
+ .url(endpoint)
+ .get()
+ .build()
+ client.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) {
+ throw IOException("HTTP ${response.code}")
+ }
+ val body = response.body?.string()?.takeIf { it.isNotBlank() }
+ ?: throw IOException("Empty response body")
+ json.decodeFromString<T>(body)
+ }
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
index 1b7013c1..a48bbe52 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
@@ -7,109 +7,30 @@ import com.streamvault.data.remote.dto.XtreamSeriesInfoResponse
import com.streamvault.data.remote.dto.XtreamSeriesItem
import com.streamvault.data.remote.dto.XtreamStream
import com.streamvault.data.remote.dto.XtreamVodInfoResponse
-import retrofit2.http.GET
-import retrofit2.http.Query
-import retrofit2.http.Url
/**
- * Retrofit interface for Xtream Codes player API.
- *
- * Calls use dynamic @Url so each provider can target its own server host.
+ * Xtream Codes player API abstraction.
*/
interface XtreamApiService {
+ suspend fun authenticate(endpoint: String): XtreamAuthResponse
- @GET
- suspend fun authenticate(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String
- ): XtreamAuthResponse
+ suspend fun getLiveCategories(endpoint: String): List<XtreamCategory>
- @GET
- suspend fun getLiveCategories(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_live_categories"
- ): List<XtreamCategory>
+ suspend fun getLiveStreams(endpoint: String): List<XtreamStream>
- @GET
- suspend fun getLiveStreams(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_live_streams",
- @Query("category_id") categoryId: String? = null
- ): List<XtreamStream>
+ suspend fun getVodCategories(endpoint: String): List<XtreamCategory>
- @GET
- suspend fun getVodCategories(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_vod_categories"
- ): List<XtreamCategory>
+ suspend fun getVodStreams(endpoint: String): List<XtreamStream>
- @GET
- suspend fun getVodStreams(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_vod_streams",
- @Query("category_id") categoryId: String? = null
- ): List<XtreamStream>
+ suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse
- @GET
- suspend fun getVodInfo(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_vod_info",
- @Query("vod_id") vodId: Long
- ): XtreamVodInfoResponse
+ suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory>
- @GET
- suspend fun getSeriesCategories(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_series_categories"
- ): List<XtreamCategory>
+ suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem>
- @GET
- suspend fun getSeriesList(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_series",
- @Query("category_id") categoryId: String? = null
- ): List<XtreamSeriesItem>
+ suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse
- @GET
- suspend fun getSeriesInfo(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_series_info",
- @Query("series_id") seriesId: Long
- ): XtreamSeriesInfoResponse
+ suspend fun getShortEpg(endpoint: String): XtreamEpgResponse
- @GET
- suspend fun getShortEpg(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_short_epg",
- @Query("stream_id") streamId: Long,
- @Query("limit") limit: Int = 4
- ): XtreamEpgResponse
-
- @GET
- suspend fun getFullEpg(
- @Url endpoint: String,
- @Query("username") username: String,
- @Query("password") password: String,
- @Query("action") action: String = "get_simple_data_table",
- @Query("stream_id") streamId: Long
- ): XtreamEpgResponse
+ suspend fun getFullEpg(endpoint: String): XtreamEpgResponse
}
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamErrorFormatter.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamErrorFormatter.kt
new file mode 100644
index 00000000..de51217f
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamErrorFormatter.kt
@@ -0,0 +1,24 @@
+package com.streamvault.data.remote.xtream
+
+import java.security.cert.CertificateException
+import javax.net.ssl.SSLPeerUnverifiedException
+
+internal object XtreamErrorFormatter {
+ fun message(prefix: String, throwable: Throwable): String {
+ return if (throwable.isCertificateTrustFailure()) {
+ "$prefix: Server TLS certificate is not trusted by this device. Verify the HTTPS URL or ask the provider for a valid certificate."
+ } else {
+ "$prefix: ${throwable.message ?: "Unexpected network error"}"
+ }
+ }
+
+ private fun Throwable.isCertificateTrustFailure(): Boolean {
+ return generateSequence(this) { it.cause }.any { current ->
+ current is SSLPeerUnverifiedException ||
+ current is CertificateException ||
+ current.message?.contains("trust anchor", ignoreCase = true) == true ||
+ current.message?.contains("certificate", ignoreCase = true) == true ||
+ current.message?.contains("hostname", ignoreCase = true) == true
+ }
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
index 53f97b2a..c96bbfc0 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
@@ -23,12 +23,13 @@ class XtreamProvider(
) : IptvProvider {
private var serverInfo: XtreamServerInfo? = null
- private val apiEndpoint: String = "${serverUrl.trimEnd('/')}/player_api.php"
private val adultCategoryCache = mutableMapOf<ContentType, Set<Long>>()
private val adultCategoryCacheMutex = Mutex()
override suspend fun authenticate(): Result<Provider> = try {
- val response = api.authenticate(apiEndpoint, username, password)
+ val response = api.authenticate(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password)
+ )
serverInfo = response.serverInfo
if (response.userInfo.auth != 1) {
@@ -55,7 +56,7 @@ class XtreamProvider(
var parsed: Long? = null
for (fmt in formats) {
try {
- parsed = java.text.SimpleDateFormat(fmt, java.util.Locale.getDefault()).parse(expDateStr)?.time
+ parsed = java.text.SimpleDateFormat(fmt, java.util.Locale.ROOT).parse(expDateStr)?.time
if (parsed != null) break
} catch (_: Exception) {}
}
@@ -89,53 +90,75 @@ class XtreamProvider(
)
}
} catch (e: Exception) {
- Result.error("Authentication failed: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Authentication failed", e), e)
}
// ── Live TV ────────────────────────────────────────────────────
override suspend fun getLiveCategories(): Result<List<Category>> = try {
- val categories = api.getLiveCategories(apiEndpoint, username, password)
+ val categories = api.getLiveCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_live_categories")
+ )
cacheAdultCategoryIds(ContentType.LIVE, categories)
Result.success(categories.map { it.toDomain(ContentType.LIVE) })
} catch (e: Exception) {
- Result.error("Failed to load live categories: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load live categories", e), e)
}
override suspend fun getLiveStreams(categoryId: Long?): Result<List<Channel>> = try {
val adultCategoryIds = loadAdultCategoryIds(ContentType.LIVE)
val streams = api.getLiveStreams(
- apiEndpoint, username, password,
- categoryId = categoryId?.toString()
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_live_streams",
+ extraQueryParams = mapOf("category_id" to categoryId?.toString())
+ )
)
Result.success(streams.map { it.toChannel(adultCategoryIds) })
} catch (e: Exception) {
- Result.error("Failed to load live streams: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load live streams", e), e)
}
// ── VOD ────────────────────────────────────────────────────────
override suspend fun getVodCategories(): Result<List<Category>> = try {
- val categories = api.getVodCategories(apiEndpoint, username, password)
+ val categories = api.getVodCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories")
+ )
cacheAdultCategoryIds(ContentType.MOVIE, categories)
Result.success(categories.map { it.toDomain(ContentType.MOVIE) })
} catch (e: Exception) {
- Result.error("Failed to load VOD categories: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load VOD categories", e), e)
}
override suspend fun getVodStreams(categoryId: Long?): Result<List<Movie>> = try {
val adultCategoryIds = loadAdultCategoryIds(ContentType.MOVIE)
val streams = api.getVodStreams(
- apiEndpoint, username, password,
- categoryId = categoryId?.toString()
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_vod_streams",
+ extraQueryParams = mapOf("category_id" to categoryId?.toString())
+ )
)
Result.success(streams.map { it.toMovie(adultCategoryIds) })
} catch (e: Exception) {
- Result.error("Failed to load VOD: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load VOD", e), e)
}
override suspend fun getVodInfo(vodId: Long): Result<Movie> = try {
- val response = api.getVodInfo(apiEndpoint, username, password, vodId = vodId)
+ val response = api.getVodInfo(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_vod_info",
+ extraQueryParams = mapOf("vod_id" to vodId.toString())
+ )
+ )
val movieData = response.movieData
val info = response.info
@@ -172,32 +195,47 @@ class XtreamProvider(
)
}
} catch (e: Exception) {
- Result.error("Failed to load movie details: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load movie details", e), e)
}
// ── Series ─────────────────────────────────────────────────────
override suspend fun getSeriesCategories(): Result<List<Category>> = try {
- val categories = api.getSeriesCategories(apiEndpoint, username, password)
+ val categories = api.getSeriesCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories")
+ )
cacheAdultCategoryIds(ContentType.SERIES, categories)
Result.success(categories.map { it.toDomain(ContentType.SERIES) })
} catch (e: Exception) {
- Result.error("Failed to load series categories: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load series categories", e), e)
}
override suspend fun getSeriesList(categoryId: Long?): Result<List<Series>> = try {
val adultCategoryIds = loadAdultCategoryIds(ContentType.SERIES)
val items = api.getSeriesList(
- apiEndpoint, username, password,
- categoryId = categoryId?.toString()
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_series",
+ extraQueryParams = mapOf("category_id" to categoryId?.toString())
+ )
)
Result.success(items.map { it.toDomain(adultCategoryIds) })
} catch (e: Exception) {
- Result.error("Failed to load series: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load series", e), e)
}
override suspend fun getSeriesInfo(seriesId: Long): Result<Series> = try {
- val response = api.getSeriesInfo(apiEndpoint, username, password, seriesId = seriesId)
+ val response = api.getSeriesInfo(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_series_info",
+ extraQueryParams = mapOf("series_id" to seriesId.toString())
+ )
+ )
val info = response.info
if (info == null) {
@@ -231,9 +269,11 @@ class XtreamProvider(
releaseDate = ep.info?.releaseDate,
seriesId = seriesId,
providerId = providerId,
- streamUrl = buildSeriesStreamUrl(
- ep.id.toLongOrNull() ?: 0,
- ep.containerExtension
+ streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = providerId,
+ kind = XtreamStreamKind.SERIES,
+ streamId = ep.id.toLongOrNull() ?: 0,
+ containerExtension = ep.containerExtension
),
isAdult = isAdult,
isUserProtected = false,
@@ -253,53 +293,87 @@ class XtreamProvider(
)
}
} catch (e: Exception) {
- Result.error("Failed to load series details: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load series details", e), e)
}
// ── EPG ────────────────────────────────────────────────────────
override suspend fun getEpg(channelId: String): Result<List<Program>> = try {
val streamId = channelId.toLongOrNull() ?: 0
- val response = api.getFullEpg(apiEndpoint, username, password, streamId = streamId)
+ val response = api.getFullEpg(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_simple_data_table",
+ extraQueryParams = mapOf("stream_id" to streamId.toString())
+ )
+ )
Result.success(response.epgListings.map { it.toDomain() })
} catch (e: Exception) {
- Result.error("Failed to load EPG: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load EPG", e), e)
}
override suspend fun getShortEpg(channelId: String, limit: Int): Result<List<Program>> = try {
val streamId = channelId.toLongOrNull() ?: 0
- val response = api.getShortEpg(apiEndpoint, username, password, streamId = streamId, limit = limit)
+ val response = api.getShortEpg(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_short_epg",
+ extraQueryParams = mapOf(
+ "stream_id" to streamId.toString(),
+ "limit" to limit.toString()
+ )
+ )
+ )
Result.success(response.epgListings.map { it.toDomain() })
} catch (e: Exception) {
- Result.error("Failed to load EPG: ${e.message}", e)
+ Result.error(XtreamErrorFormatter.message("Failed to load EPG", e), e)
}
// ── Stream URLs ────────────────────────────────────────────────
override suspend fun buildStreamUrl(streamId: Long, containerExtension: String?): String {
- val baseUrl = serverUrl.trimEnd('/')
- return "$baseUrl/live/$username/$password/$streamId.ts"
+ return XtreamUrlFactory.buildPlaybackUrl(serverUrl, username, password, XtreamStreamKind.LIVE, streamId)
}
private fun buildMovieStreamUrl(streamId: Long, containerExtension: String?): String {
- val baseUrl = serverUrl.trimEnd('/')
- val ext = containerExtension ?: "mp4"
- return "$baseUrl/movie/$username/$password/$streamId.$ext"
+ return XtreamUrlFactory.buildPlaybackUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ kind = XtreamStreamKind.MOVIE,
+ streamId = streamId,
+ containerExtension = containerExtension
+ )
}
private fun buildSeriesStreamUrl(streamId: Long, containerExtension: String?): String {
- val baseUrl = serverUrl.trimEnd('/')
- val ext = containerExtension ?: "mp4"
- return "$baseUrl/series/$username/$password/$streamId.$ext"
+ return XtreamUrlFactory.buildPlaybackUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ kind = XtreamStreamKind.SERIES,
+ streamId = streamId,
+ containerExtension = containerExtension
+ )
}
override suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String? {
- val baseUrl = serverUrl.trimEnd('/')
- val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd:HH-mm", java.util.Locale.getDefault())
+ val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd:HH-mm", java.util.Locale.ROOT)
dateFormat.timeZone = java.util.TimeZone.getTimeZone("UTC") // Xtream servers typically use UTC for EPG timeshifts
val formattedStart = dateFormat.format(java.util.Date(start * 1000L))
val durationMinutes = (end - start) / 60
- return "$baseUrl/timeshift/$username/$password/$durationMinutes/$formattedStart/$streamId.ts"
+ return XtreamUrlFactory.buildCatchUpUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ durationMinutes = durationMinutes,
+ formattedStart = formattedStart,
+ streamId = streamId
+ )
}
// ── Mappers ────────────────────────────────────────────────────
@@ -307,22 +381,24 @@ class XtreamProvider(
private suspend fun loadAdultCategoryIds(type: ContentType): Set<Long> {
adultCategoryCacheMutex.withLock {
adultCategoryCache[type]?.let { return it }
- }
- val categories = when (type) {
- ContentType.LIVE -> api.getLiveCategories(apiEndpoint, username, password)
- ContentType.MOVIE -> api.getVodCategories(apiEndpoint, username, password)
- ContentType.SERIES -> api.getSeriesCategories(apiEndpoint, username, password)
- ContentType.SERIES_EPISODE -> emptyList()
- }
- return categories
- .filter { AdultContentClassifier.isAdultCategoryName(it.categoryName) }
- .mapNotNull { it.categoryId.toLongOrNull() }
- .toSet()
- .also { ids ->
- adultCategoryCacheMutex.withLock {
- adultCategoryCache[type] = ids
- }
+ val categories = when (type) {
+ ContentType.LIVE -> api.getLiveCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_live_categories")
+ )
+ ContentType.MOVIE -> api.getVodCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories")
+ )
+ ContentType.SERIES -> api.getSeriesCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories")
+ )
+ ContentType.SERIES_EPISODE -> emptyList()
}
+ return categories
+ .filter { AdultContentClassifier.isAdultCategoryName(it.categoryName) }
+ .mapNotNull { it.categoryId.toLongOrNull() }
+ .toSet()
+ .also { adultCategoryCache[type] = it }
+ }
}
private suspend fun cacheAdultCategoryIds(type: ContentType, categories: List<XtreamCategory>) {
@@ -364,7 +440,11 @@ class XtreamProvider(
catchUpSupported = tvArchive == 1,
catchUpDays = tvArchiveDuration ?: 0,
providerId = providerId,
- streamUrl = "$serverUrl/live/$username/$password/$streamId.ts",
+ streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = providerId,
+ kind = XtreamStreamKind.LIVE,
+ streamId = streamId
+ ),
isAdult = resolveAdultFlag(
categoryId = categoryId?.toLongOrNull(),
categoryName = categoryName,
@@ -385,7 +465,12 @@ class XtreamProvider(
containerExtension = containerExtension,
rating = rating5based?.toFloatOrNull() ?: 0f,
providerId = providerId,
- streamUrl = buildMovieStreamUrl(streamId, containerExtension),
+ streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = providerId,
+ kind = XtreamStreamKind.MOVIE,
+ streamId = streamId,
+ containerExtension = containerExtension
+ ),
isAdult = resolveAdultFlag(
categoryId = categoryId?.toLongOrNull(),
categoryName = categoryName,
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
new file mode 100644
index 00000000..a26c04e7
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
@@ -0,0 +1,48 @@
+package com.streamvault.data.remote.xtream
+
+import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.data.security.CredentialCrypto
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderType
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class XtreamStreamUrlResolver @Inject constructor(
+ private val providerDao: ProviderDao
+) {
+ fun isInternalStreamUrl(url: String?): Boolean = XtreamUrlFactory.isInternalStreamUrl(url)
+
+ suspend fun resolve(
+ url: String,
+ fallbackProviderId: Long? = null,
+ fallbackStreamId: Long? = null,
+ fallbackContentType: ContentType? = null,
+ fallbackContainerExtension: String? = null
+ ): String? {
+ if (url.isNotBlank() && !XtreamUrlFactory.isInternalStreamUrl(url)) {
+ return url
+ }
+
+ val token = XtreamUrlFactory.parseInternalStreamUrl(url)
+ val providerId = token?.providerId ?: fallbackProviderId?.takeIf { it > 0 } ?: return null
+ val provider = providerDao.getById(providerId) ?: return null
+ if (provider.type != ProviderType.XTREAM_CODES) {
+ return url.takeIf { it.isNotBlank() }
+ }
+
+ val kind = token?.kind ?: fallbackContentType?.let(XtreamUrlFactory::kindForContentType) ?: return null
+ val streamId = token?.streamId ?: fallbackStreamId?.takeIf { it > 0 } ?: return null
+ val ext = token?.containerExtension ?: fallbackContainerExtension
+ val decryptedPassword = CredentialCrypto.decryptIfNeeded(provider.password)
+
+ return XtreamUrlFactory.buildPlaybackUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = decryptedPassword,
+ kind = kind,
+ streamId = streamId,
+ containerExtension = ext
+ )
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt
new file mode 100644
index 00000000..de1a1c9c
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt
@@ -0,0 +1,174 @@
+package com.streamvault.data.remote.xtream
+
+import android.net.Uri
+import com.streamvault.domain.model.ContentType
+
+enum class XtreamStreamKind(val pathSegment: String) {
+ LIVE("live"),
+ MOVIE("movie"),
+ SERIES("series")
+}
+
+data class XtreamStreamToken(
+ val providerId: Long,
+ val kind: XtreamStreamKind,
+ val streamId: Long,
+ val containerExtension: String? = null
+)
+
+object XtreamUrlFactory {
+ private const val INTERNAL_SCHEME = "xtream"
+ private val queryCredentialRegex = Regex("([?&](?:username|password)=)[^&\\s]+", RegexOption.IGNORE_CASE)
+ private val liveMovieSeriesPathRegex = Regex(
+ """(https?://[^\s/]+(?:/[^\s/?#]+)*)/(live|movie|series)/[^/\s?]+/[^/\s?]+(/[^\s?#]*)?""",
+ RegexOption.IGNORE_CASE
+ )
+ private val timeshiftPathRegex = Regex(
+ """(https?://[^\s/]+(?:/[^\s/?#]+)*)/timeshift/[^/\s?]+/[^/\s?]+(/[^\s?#]*)?""",
+ RegexOption.IGNORE_CASE
+ )
+
+ fun buildPlayerApiUrl(
+ serverUrl: String,
+ username: String,
+ password: String,
+ action: String? = null,
+ extraQueryParams: Map<String, String?> = emptyMap()
+ ): String {
+ return baseBuilder(serverUrl)
+ .appendPath("player_api.php")
+ .appendQueryParameter("username", username)
+ .appendQueryParameter("password", password)
+ .apply {
+ action?.let { appendQueryParameter("action", it) }
+ extraQueryParams.forEach { (key, value) -> value?.let { appendQueryParameter(key, it) } }
+ }
+ .build()
+ .toString()
+ }
+
+ fun buildXmltvUrl(serverUrl: String, username: String, password: String): String {
+ return baseBuilder(serverUrl)
+ .appendPath("xmltv.php")
+ .appendQueryParameter("username", username)
+ .appendQueryParameter("password", password)
+ .build()
+ .toString()
+ }
+
+ fun buildPlaybackUrl(
+ serverUrl: String,
+ username: String,
+ password: String,
+ kind: XtreamStreamKind,
+ streamId: Long,
+ containerExtension: String? = null
+ ): String {
+ val ext = when (kind) {
+ XtreamStreamKind.LIVE -> "ts"
+ XtreamStreamKind.MOVIE, XtreamStreamKind.SERIES -> containerExtension ?: "mp4"
+ }
+ return serverUrl.trimEnd('/') + "/${kind.pathSegment}/" +
+ Uri.encode(username) + "/" +
+ Uri.encode(password) + "/" +
+ Uri.encode(streamId.toString()) + "." + Uri.encode(ext)
+ }
+
+ fun buildCatchUpUrl(
+ serverUrl: String,
+ username: String,
+ password: String,
+ durationMinutes: Long,
+ formattedStart: String,
+ streamId: Long
+ ): String {
+ return serverUrl.trimEnd('/') + "/timeshift/" +
+ Uri.encode(username) + "/" +
+ Uri.encode(password) + "/" +
+ Uri.encode(durationMinutes.toString()) + "/" +
+ Uri.encode(formattedStart) + "/" +
+ Uri.encode(streamId.toString()) + ".ts"
+ }
+
+ fun buildInternalStreamUrl(
+ providerId: Long,
+ kind: XtreamStreamKind,
+ streamId: Long,
+ containerExtension: String? = null
+ ): String {
+ return Uri.Builder()
+ .scheme(INTERNAL_SCHEME)
+ .authority(providerId.toString())
+ .appendPath(kind.pathSegment)
+ .appendPath(streamId.toString())
+ .apply {
+ containerExtension?.takeIf { it.isNotBlank() }?.let { appendQueryParameter("ext", it) }
+ }
+ .build()
+ .toString()
+ }
+
+ fun parseInternalStreamUrl(url: String?): XtreamStreamToken? {
+ if (url.isNullOrBlank()) return null
+ val uri = runCatching { Uri.parse(url) }.getOrNull() ?: return null
+ if (!uri.scheme.equals(INTERNAL_SCHEME, ignoreCase = true)) return null
+ val providerId = uri.authority?.toLongOrNull() ?: return null
+ val kind = uri.pathSegments.getOrNull(0)?.let(::kindFromPathSegment) ?: return null
+ val streamId = uri.pathSegments.getOrNull(1)?.toLongOrNull() ?: return null
+ return XtreamStreamToken(providerId, kind, streamId, uri.getQueryParameter("ext"))
+ }
+
+ fun kindForContentType(contentType: ContentType): XtreamStreamKind? = when (contentType) {
+ ContentType.LIVE -> XtreamStreamKind.LIVE
+ ContentType.MOVIE -> XtreamStreamKind.MOVIE
+ ContentType.SERIES_EPISODE -> XtreamStreamKind.SERIES
+ ContentType.SERIES -> null
+ }
+
+ fun sanitizePersistedStreamUrl(url: String, providerId: Long): String {
+ val parsed = parseCredentialedStreamUrl(url, providerId) ?: return url
+ return buildInternalStreamUrl(parsed.providerId, parsed.kind, parsed.streamId, parsed.containerExtension)
+ }
+
+ fun isInternalStreamUrl(url: String?): Boolean = parseInternalStreamUrl(url) != null
+
+ fun sanitizeLogMessage(message: String): String {
+ val queryRedacted = queryCredentialRegex.replace(message) { match ->
+ match.groupValues[1] + "<redacted>"
+ }
+ val pathRedacted = liveMovieSeriesPathRegex.replace(queryRedacted) { match ->
+ val prefix = match.groupValues[1]
+ val type = match.groupValues[2]
+ val suffix = match.groupValues[3]
+ "$prefix/$type/<redacted>/<redacted>$suffix"
+ }
+ return timeshiftPathRegex.replace(pathRedacted) { match ->
+ val prefix = match.groupValues[1]
+ val suffix = match.groupValues[2]
+ "$prefix/timeshift/<redacted>/<redacted>$suffix"
+ }
+ }
+
+ private fun parseCredentialedStreamUrl(url: String, providerId: Long): XtreamStreamToken? {
+ val uri = runCatching { Uri.parse(url) }.getOrNull() ?: return null
+ val kind = uri.pathSegments.getOrNull(0)?.let(::kindFromPathSegment) ?: return null
+ if (uri.pathSegments.size < 4) return null
+ val fileSegment = uri.pathSegments[3]
+ val dotIndex = fileSegment.lastIndexOf('.')
+ val streamId = fileSegment.substring(0, dotIndex.takeIf { it > 0 } ?: fileSegment.length).toLongOrNull() ?: return null
+ val ext = if (dotIndex > 0 && dotIndex < fileSegment.lastIndex) fileSegment.substring(dotIndex + 1) else null
+ return XtreamStreamToken(providerId, kind, streamId, ext)
+ }
+
+ private fun baseBuilder(serverUrl: String): Uri.Builder {
+ val normalized = serverUrl.trimEnd('/') + "/"
+ return Uri.parse(normalized).buildUpon().path("")
+ }
+
+ private fun kindFromPathSegment(segment: String): XtreamStreamKind? = when (segment.lowercase()) {
+ XtreamStreamKind.LIVE.pathSegment -> XtreamStreamKind.LIVE
+ XtreamStreamKind.MOVIE.pathSegment -> XtreamStreamKind.MOVIE
+ XtreamStreamKind.SERIES.pathSegment -> XtreamStreamKind.SERIES
+ else -> null
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt
index a3a4797f..0121198f 100644
--- a/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt
@@ -1,6 +1,7 @@
package com.streamvault.data.repository
import com.streamvault.data.local.dao.*
+import com.streamvault.data.local.DatabaseTransactionRunner
import com.streamvault.data.mapper.toDomain
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ContentType
@@ -16,7 +17,8 @@ class CategoryRepositoryImpl @Inject constructor(
private val categoryDao: CategoryDao,
private val channelDao: ChannelDao,
private val movieDao: MovieDao,
- private val seriesDao: SeriesDao
+ private val seriesDao: SeriesDao,
+ private val transactionRunner: DatabaseTransactionRunner
) : CategoryRepository {
override fun getCategories(providerId: Long): Flow<List<Category>> =
@@ -35,7 +37,7 @@ class CategoryRepositoryImpl @Inject constructor(
categoryId: Long,
type: ContentType,
isProtected: Boolean
- ) {
+ ) = transactionRunner.inTransaction {
categoryDao.updateProtectionStatus(providerId, categoryId, type.name, isProtected)
when (type) {
ContentType.LIVE -> channelDao.updateProtectionStatus(providerId, categoryId, isProtected)
diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
index f7edbe20..8d277818 100644
--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
@@ -14,8 +14,10 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOf
+import com.streamvault.data.util.toFtsPrefixQuery
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import javax.inject.Singleton
@Singleton
@@ -23,7 +25,8 @@ class ChannelRepositoryImpl @Inject constructor(
private val channelDao: ChannelDao,
private val categoryDao: CategoryDao,
private val preferencesRepository: PreferencesRepository,
- private val parentalControlManager: com.streamvault.domain.manager.ParentalControlManager
+ private val parentalControlManager: com.streamvault.domain.manager.ParentalControlManager,
+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : ChannelRepository {
override fun getChannels(providerId: Long): Flow<List<Channel>> =
@@ -169,11 +172,14 @@ class ChannelRepositoryImpl @Inject constructor(
@Deprecated("Use getStreamInfo() instead", ReplaceWith("getStreamInfo(channel)"))
override suspend fun getStreamUrl(channel: Channel): Result<String> =
- if (channel.streamUrl.isNotBlank()) {
- Result.success(channel.streamUrl)
- } else {
- Result.error("No stream URL available for channel: ${channel.name}")
- }
+ xtreamStreamUrlResolver.resolve(
+ url = channel.streamUrl,
+ fallbackProviderId = channel.providerId,
+ fallbackStreamId = channel.streamId,
+ fallbackContentType = ContentType.LIVE
+ )?.let { resolvedUrl ->
+ Result.success(resolvedUrl)
+ } ?: Result.error("No stream URL available for channel: ${channel.name}")
override suspend fun refreshChannels(providerId: Long): Result<Unit> {
// Refresh is handled by ProviderRepository.refreshProviderData
@@ -236,13 +242,4 @@ class ChannelRepositoryImpl @Inject constructor(
private fun channelGroupKey(entity: ChannelEntity): String =
if (entity.logicalGroupId.isNotBlank()) entity.logicalGroupId else entity.id.toString()
-
- private fun String.toFtsPrefixQuery(): String {
- val tokens = trim()
- .split(Regex("\\s+"))
- .map { token -> token.replace(Regex("[^\\p{L}\\p{N}_]"), "") }
- .filter { it.length >= 2 }
-
- return tokens.joinToString(" AND ") { "$it*" }
- }
}
diff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt
index 0fa0b0cb..87db7190 100644
--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt
@@ -10,15 +10,24 @@ import com.streamvault.domain.model.Program
import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.EpgRepository
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
+import java.io.FilterInputStream
+import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
+@OptIn(ExperimentalCoroutinesApi::class)
class EpgRepositoryImpl @Inject constructor(
private val programDao: ProgramDao,
private val xmltvParser: XmltvParser,
@@ -28,6 +37,9 @@ class EpgRepositoryImpl @Inject constructor(
companion object {
private const val MAX_EPG_SIZE_BYTES = 200L * 1_048_576 // 200 MB
+ private const val NOW_AND_NEXT_LOOKBACK_MS = 60L * 60L * 1000L
+ private const val NOW_AND_NEXT_LOOKAHEAD_MS = 2L * 60L * 60L * 1000L
+ private const val NOW_AND_NEXT_REFRESH_INTERVAL_MS = 60L * 1000L
}
override fun getProgramsForChannel(
@@ -45,39 +57,55 @@ class EpgRepositoryImpl @Inject constructor(
startTime: Long,
endTime: Long
): Flow<Map<String, List<Program>>> {
- if (channelIds.isEmpty()) {
- return kotlinx.coroutines.flow.flowOf(emptyMap())
+ if (channelIds.isEmpty()) return flowOf(emptyMap())
+ val chunks = channelIds.chunked(500)
+ if (chunks.size == 1) {
+ return programDao.getForChannels(providerId, channelIds, startTime, endTime)
+ .map { entities -> entities.map { it.toDomain() }.groupBy { it.channelId } }
+ }
+ return combine(chunks.map { chunk ->
+ programDao.getForChannels(providerId, chunk, startTime, endTime)
+ }) { arrays ->
+ arrays.flatMap { it.toList() }.map { it.toDomain() }.groupBy { it.channelId }
}
- return programDao.getForChannels(providerId, channelIds, startTime, endTime)
- .map { entities ->
- entities.map { it.toDomain() }
- .groupBy { it.channelId }
- }
}
override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> =
programDao.getNowPlaying(providerId, channelId, System.currentTimeMillis())
.map { it?.toDomain() }
- override fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>): Flow<Map<String, Program?>> =
- programDao.getNowPlayingForChannels(providerId, channelIds, System.currentTimeMillis())
- .map { entities ->
- val grouped = entities.map { it.toDomain() }.groupBy { it.channelId }
- channelIds.associateWith { id -> grouped[id]?.firstOrNull() }
- }
+ override fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>): Flow<Map<String, Program?>> {
+ if (channelIds.isEmpty()) return flowOf(emptyMap())
+ val now = System.currentTimeMillis()
+ val chunks = channelIds.chunked(500)
+ if (chunks.size == 1) {
+ return programDao.getNowPlayingForChannels(providerId, channelIds, now)
+ .map { entities ->
+ val grouped = entities.map { it.toDomain() }.groupBy { it.channelId }
+ channelIds.associateWith { id -> grouped[id]?.firstOrNull() }
+ }
+ }
+ return combine(chunks.map { chunk ->
+ programDao.getNowPlayingForChannels(providerId, chunk, now)
+ }) { arrays ->
+ val grouped = arrays.flatMap { it.toList() }.map { it.toDomain() }.groupBy { it.channelId }
+ channelIds.associateWith { id -> grouped[id]?.firstOrNull() }
+ }
+ }
override fun getNowAndNext(providerId: Long, channelId: String): Flow<Pair<Program?, Program?>> =
- programDao.getForChannel(
- providerId,
- channelId,
- System.currentTimeMillis() - 3600000, // 1 hour ago
- System.currentTimeMillis() + 7200000 // 2 hours from now
- ).map { entities ->
- val programs = entities.map { it.toDomain() }
- val now = System.currentTimeMillis()
- val current = programs.find { it.startTime <= now && it.endTime > now }
- val next = programs.find { it.startTime > now }
- Pair(current, next)
+ nowTicker().flatMapLatest { now ->
+ programDao.getForChannel(
+ providerId = providerId,
+ channelId = channelId,
+ startTime = now - NOW_AND_NEXT_LOOKBACK_MS,
+ endTime = now + NOW_AND_NEXT_LOOKAHEAD_MS
+ ).map { entities ->
+ val programs = entities.map { it.toDomain() }
+ val current = programs.find { it.startTime <= now && it.endTime > now }
+ val next = programs.find { it.startTime > now }
+ current to next
+ }
}
override suspend fun refreshEpg(providerId: Long, epgUrl: String): Result<Unit> =
@@ -103,7 +131,19 @@ class EpgRepositoryImpl @Inject constructor(
val body = response.body ?: return@withContext Result.error("Empty EPG response")
body.byteStream().use { inputStream ->
- xmltvParser.parseStreaming(inputStream) { program ->
+ // Cap total bytes read even when Content-Length is absent (chunked transfer)
+ val limitedStream = object : FilterInputStream(inputStream) {
+ private var bytesRead = 0L
+ override fun read(): Int {
+ if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")
+ return super.read().also { if (it >= 0) bytesRead++ }
+ }
+ override fun read(b: ByteArray, off: Int, len: Int): Int {
+ if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")
+ return super.read(b, off, len).also { if (it > 0) bytesRead += it }
+ }
+ }
+ xmltvParser.parseStreaming(limitedStream) { program ->
batch.add(program.copy(providerId = stagingProviderId).toEntity())
if (batch.size >= 500) {
programDao.insertAll(batch.toList())
@@ -132,4 +172,11 @@ class EpgRepositoryImpl @Inject constructor(
override suspend fun clearOldPrograms(beforeTime: Long) {
programDao.deleteOld(beforeTime)
}
+
+ private fun nowTicker(): Flow<Long> = flow {
+ while (true) {
+ emit(System.currentTimeMillis())
+ delay(NOW_AND_NEXT_REFRESH_INTERVAL_MS)
+ }
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt
index b8e6f2b7..ce612a64 100644
--- a/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt
@@ -92,7 +92,7 @@ class FavoriteRepositoryImpl @Inject constructor(
com.streamvault.data.local.entity.VirtualGroupEntity(
name = name,
iconEmoji = iconEmoji,
- contentType = contentType.name
+ contentType = contentType
)
)
Result.success(VirtualGroup(id = id, name = name, iconEmoji = iconEmoji, contentType = contentType))
diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
index f77c7e96..3f927ba5 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -14,41 +14,33 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.MovieRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
+import com.streamvault.data.util.toFtsPrefixQuery
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import javax.inject.Singleton
@Singleton
class MovieRepositoryImpl @Inject constructor(
private val movieDao: MovieDao,
private val categoryDao: CategoryDao,
- private val preferencesRepository: PreferencesRepository
+ private val preferencesRepository: PreferencesRepository,
+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : MovieRepository {
override fun getMovies(providerId: Long): Flow<List<Movie>> =
- combine(
- movieDao.getByProvider(providerId),
- preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
+ preferencesRepository.parentalControlLevel.flatMapLatest { level ->
+ if (level == 2) movieDao.getByProviderUnprotected(providerId)
+ else movieDao.getByProvider(providerId)
}.map { list -> list.map { it.toDomain() } }
override fun getMoviesByCategory(providerId: Long, categoryId: Long): Flow<List<Movie>> =
- combine(
- movieDao.getByCategory(providerId, categoryId),
- preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
+ preferencesRepository.parentalControlLevel.flatMapLatest { level ->
+ if (level == 2) movieDao.getByCategoryUnprotected(providerId, categoryId)
+ else movieDao.getByCategory(providerId, categoryId)
}.map { list -> list.map { it.toDomain() } }
override fun getMoviesByCategoryPage(
@@ -82,18 +74,27 @@ class MovieRepositoryImpl @Inject constructor(
override fun getCategoryPreviewRows(providerId: Long, limitPerCategory: Int): Flow<Map<Long?, List<Movie>>> =
combine(
- movieDao.getByProvider(providerId),
+ categoryDao.getByProviderAndType(providerId, ContentType.MOVIE.name),
preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
+ ) { categories, level ->
+ val filtered = if (level == 2) categories.filter { !it.isAdult && !it.isUserProtected } else categories
+ filtered to level
+ }.flatMapLatest { (filteredCategories, level) ->
+ if (filteredCategories.isEmpty()) {
+ flowOf(emptyMap())
} else {
- entities
+ // SQL LIMIT applied per-category — avoids loading the full catalog into memory
+ val categoryGroupFlows: List<Flow<Pair<Long?, List<Movie>>>> = filteredCategories.map { cat ->
+ movieDao.getByCategoryPreview(providerId, cat.categoryId, limitPerCategory)
+ .map { entities ->
+ val items = if (level == 2) entities.filter { !it.isUserProtected } else entities
+ (cat.categoryId as Long?) to items.map { it.toDomain() }
+ }
+ }
+ combine(categoryGroupFlows) { pairs ->
+ pairs.associate { it.first to it.second }
+ }
}
- }.map { entities ->
- entities.map { it.toDomain() }
- .groupBy { it.categoryId }
- .mapValues { (_, items) -> items.take(limitPerCategory) }
}
override fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Movie>> =
@@ -197,11 +198,15 @@ class MovieRepositoryImpl @Inject constructor(
@Deprecated("Use getStreamInfo() instead", ReplaceWith("getStreamInfo(movie)"))
override suspend fun getStreamUrl(movie: Movie): Result<String> =
- if (movie.streamUrl.isNotBlank()) {
- Result.success(movie.streamUrl)
- } else {
- Result.error("No stream URL available for movie: ${movie.name}")
- }
+ xtreamStreamUrlResolver.resolve(
+ url = movie.streamUrl,
+ fallbackProviderId = movie.providerId,
+ fallbackStreamId = movie.streamId,
+ fallbackContentType = ContentType.MOVIE,
+ fallbackContainerExtension = movie.containerExtension
+ )?.let { resolvedUrl ->
+ Result.success(resolvedUrl)
+ } ?: Result.error("No stream URL available for movie: ${movie.name}")
override suspend fun refreshMovies(providerId: Long): Result<Unit> =
Result.success(Unit) // Handled by ProviderRepository
@@ -209,13 +214,4 @@ class MovieRepositoryImpl @Inject constructor(
override suspend fun updateWatchProgress(movieId: Long, progress: Long) {
movieDao.updateWatchProgress(movieId, progress)
}
-
- private fun String.toFtsPrefixQuery(): String {
- val tokens = trim()
- .split(Regex("\\s+"))
- .map { token -> token.replace(Regex("[^\\p{L}\\p{N}_]"), "") }
- .filter { it.length >= 2 }
-
- return tokens.joinToString(" AND ") { "$it*" }
- }
}
diff --git a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
index 06655016..3d1be991 100644
--- a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
@@ -12,6 +12,7 @@ import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.first
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.data.remote.xtream.XtreamUrlFactory
@Singleton
class PlaybackHistoryRepositoryImpl @Inject constructor(
@@ -36,6 +37,7 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(
val existing = dao.get(history.contentId, history.contentType.name, history.providerId)
val updatedHistory = history.copy(
+ streamUrl = XtreamUrlFactory.sanitizePersistedStreamUrl(history.streamUrl, history.providerId),
resumePositionMs = history.resumePositionMs.takeIf { it > 0L } ?: existing?.resumePositionMs ?: 0L,
totalDurationMs = history.totalDurationMs.takeIf { it > 0L } ?: existing?.totalDurationMs ?: 0L,
watchCount = (existing?.watchCount ?: 0) + 1,
@@ -52,6 +54,7 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(
// Resume ticks should not increment watch count on every update.
// Keep existing count for ongoing sessions; initialize to 1 on first save.
val updatedHistory = history.copy(
+ streamUrl = XtreamUrlFactory.sanitizePersistedStreamUrl(history.streamUrl, history.providerId),
watchCount = existing?.watchCount ?: 1,
lastWatchedAt = System.currentTimeMillis()
)
diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
index 28d4b527..8bfa64ad 100644
--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
@@ -7,6 +7,7 @@ import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.data.sync.SyncManager
+import com.streamvault.data.util.ProviderInputSanitizer
import com.streamvault.data.util.UrlSecurityPolicy
import com.streamvault.domain.model.*
import com.streamvault.domain.provider.IptvProvider
@@ -21,12 +22,7 @@ import javax.inject.Singleton
class ProviderRepositoryImpl @Inject constructor(
private val providerDao: ProviderDao,
private val channelDao: ChannelDao,
- private val movieDao: MovieDao,
- private val seriesDao: SeriesDao,
- private val categoryDao: CategoryDao,
private val programDao: ProgramDao,
- private val playbackHistoryDao: PlaybackHistoryDao,
- private val syncMetadataDao: SyncMetadataDao,
private val xtreamApiService: XtreamApiService,
private val syncManager: SyncManager
) : ProviderRepository {
@@ -55,15 +51,8 @@ class ProviderRepositoryImpl @Inject constructor(
}
override suspend fun deleteProvider(id: Long): Result<Unit> = try {
+ // ProgramEntity still has no provider FK, so it requires explicit cleanup.
programDao.deleteByProvider(id)
- playbackHistoryDao.deleteByProvider(id)
- syncMetadataDao.delete(id)
- channelDao.deleteByProvider(id)
- movieDao.deleteByProvider(id)
- seriesDao.deleteByProvider(id)
- categoryDao.deleteByProviderAndType(id, "LIVE")
- categoryDao.deleteByProviderAndType(id, "MOVIE")
- categoryDao.deleteByProviderAndType(id, "SERIES")
providerDao.delete(id)
Result.success(Unit)
} catch (e: Exception) {
@@ -71,8 +60,7 @@ class ProviderRepositoryImpl @Inject constructor(
}
override suspend fun setActiveProvider(id: Long): Result<Unit> = try {
- providerDao.deactivateAll()
- providerDao.activate(id)
+ providerDao.setActive(id)
Result.success(Unit)
} catch (e: Exception) {
Result.error("Failed to set active provider: ${e.message}", e)
@@ -86,28 +74,35 @@ class ProviderRepositoryImpl @Inject constructor(
onProgress: ((String) -> Unit)?,
id: Long?
): Result<Provider> {
- UrlSecurityPolicy.validateXtreamServerUrl(serverUrl)?.let { message ->
+ val normalizedServerUrl = ProviderInputSanitizer.normalizeUrl(serverUrl)
+ val normalizedUsername = ProviderInputSanitizer.normalizeUsername(username)
+ val normalizedName = ProviderInputSanitizer.normalizeProviderName(name)
+
+ ProviderInputSanitizer.validateUrl(normalizedServerUrl)?.let { message ->
+ return Result.error(message)
+ }
+ UrlSecurityPolicy.validateXtreamServerUrl(normalizedServerUrl)?.let { message ->
return Result.error(message)
}
onProgress?.invoke("Authenticating...")
val existingProvider = if (id != null) {
providerDao.getById(id)
} else {
- providerDao.getByUrlAndUser(serverUrl, username)
+ providerDao.getByUrlAndUser(normalizedServerUrl, normalizedUsername)
}
val effectivePassword = password.takeIf { it.isNotBlank() }
?: existingProvider?.password?.let(CredentialCrypto::decryptIfNeeded)
?: ""
- val provider = createXtreamProvider(0, serverUrl, username, effectivePassword)
+ val provider = createXtreamProvider(0, normalizedServerUrl, normalizedUsername, effectivePassword)
return when (val authResult = provider.authenticate()) {
is Result.Success -> {
val providerData = if (existingProvider != null) {
onProgress?.invoke("Updating existing provider...")
val updated = existingProvider.copy(
- name = name.ifBlank { existingProvider.name },
- serverUrl = serverUrl,
- username = username,
+ name = normalizedName.ifBlank { existingProvider.name },
+ serverUrl = normalizedServerUrl,
+ username = normalizedUsername,
password = effectivePassword,
isActive = true,
lastSyncedAt = 0
@@ -117,13 +112,12 @@ class ProviderRepositoryImpl @Inject constructor(
)
updated.toPublicDomain()
} else {
- val newData = authResult.data.copy(name = name.ifBlank { authResult.data.name })
+ val newData = authResult.data.copy(name = normalizedName.ifBlank { authResult.data.name })
val newId = providerDao.insert(newData.toSecureEntity())
newData.copy(id = newId).copy(password = "")
}
- providerDao.deactivateAll()
- providerDao.activate(providerData.id)
+ providerDao.setActive(providerData.id)
when (val syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress)) {
is Result.Success -> {
@@ -160,25 +154,31 @@ class ProviderRepositoryImpl @Inject constructor(
onProgress: ((String) -> Unit)?,
id: Long?
): Result<Provider> = try {
- UrlSecurityPolicy.validatePlaylistSourceUrl(url)?.let { message ->
+ val normalizedUrl = ProviderInputSanitizer.normalizeUrl(url)
+ val normalizedName = ProviderInputSanitizer.normalizeProviderName(name)
+
+ ProviderInputSanitizer.validateUrl(normalizedUrl)?.let { message ->
+ return Result.error(message)
+ }
+ UrlSecurityPolicy.validatePlaylistSourceUrl(normalizedUrl)?.let { message ->
return Result.error(message)
}
onProgress?.invoke("Validating playlist URL...")
- val providerName = name.ifBlank {
- url.substringAfterLast("/").substringBefore("?").ifBlank { "M3U Playlist" }
+ val providerName = normalizedName.ifBlank {
+ normalizedUrl.substringAfterLast("/").substringBefore("?").ifBlank { "M3U Playlist" }
}
val existingProvider = if (id != null) {
providerDao.getById(id)
} else {
- providerDao.getByUrlAndUser(url, "")
+ providerDao.getByUrlAndUser(normalizedUrl, "")
}
val providerData = if (existingProvider != null) {
val updated = existingProvider.copy(
- name = if (name.isNotBlank()) name else existingProvider.name,
- serverUrl = url,
- m3uUrl = url,
+ name = if (normalizedName.isNotBlank()) normalizedName else existingProvider.name,
+ serverUrl = normalizedUrl,
+ m3uUrl = normalizedUrl,
isActive = true,
lastSyncedAt = 0
)
@@ -188,8 +188,8 @@ class ProviderRepositoryImpl @Inject constructor(
val provider = Provider(
name = providerName,
type = ProviderType.M3U,
- serverUrl = url,
- m3uUrl = url,
+ serverUrl = normalizedUrl,
+ m3uUrl = normalizedUrl,
status = ProviderStatus.ACTIVE
)
val newId = providerDao.insert(provider.toSecureEntity())
@@ -305,7 +305,7 @@ class ProviderRepositoryImpl @Inject constructor(
) {
val current = providerDao.getById(providerId) ?: return
val updated = current.copy(
- status = status.name,
+ status = status,
lastSyncedAt = lastSyncedAt ?: current.lastSyncedAt
)
providerDao.update(updated)
diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
index 2a81cd62..cd0602a1 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -5,13 +5,17 @@ import com.streamvault.data.local.entity.*
import com.streamvault.data.mapper.*
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.domain.model.*
import com.streamvault.domain.repository.SeriesRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
+import com.streamvault.data.util.toFtsPrefixQuery
+import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
import javax.inject.Singleton
@@ -23,9 +27,17 @@ class SeriesRepositoryImpl @Inject constructor(
private val categoryDao: CategoryDao,
private val providerDao: ProviderDao,
private val xtreamApiService: XtreamApiService,
- private val preferencesRepository: PreferencesRepository
+ private val preferencesRepository: PreferencesRepository,
+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : SeriesRepository {
+ private data class CachedXtreamProvider(
+ val signature: String,
+ val provider: XtreamProvider
+ )
+
+ private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()
+
override fun getSeries(providerId: Long): Flow<List<Series>> =
combine(
seriesDao.getByProvider(providerId),
@@ -81,18 +93,27 @@ class SeriesRepositoryImpl @Inject constructor(
override fun getCategoryPreviewRows(providerId: Long, limitPerCategory: Int): Flow<Map<Long?, List<Series>>> =
combine(
- seriesDao.getByProvider(providerId),
+ categoryDao.getByProviderAndType(providerId, ContentType.SERIES.name),
preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
+ ) { categories, level ->
+ val filtered = if (level == 2) categories.filter { !it.isAdult && !it.isUserProtected } else categories
+ filtered to level
+ }.flatMapLatest { (filteredCategories, level) ->
+ if (filteredCategories.isEmpty()) {
+ flowOf(emptyMap())
} else {
- entities
+ // SQL LIMIT applied per-category — avoids loading the full catalog into memory
+ val categoryGroupFlows: List<Flow<Pair<Long?, List<Series>>>> = filteredCategories.map { cat ->
+ seriesDao.getByCategoryPreview(providerId, cat.categoryId, limitPerCategory)
+ .map { entities ->
+ val items = if (level == 2) entities.filter { !it.isUserProtected } else entities
+ (cat.categoryId as Long?) to items.map { it.toDomain() }
+ }
+ }
+ combine(categoryGroupFlows) { pairs ->
+ pairs.associate { it.first to it.second }
+ }
}
- }.map { entities ->
- entities.map { it.toDomain() }
- .groupBy { it.categoryId }
- .mapValues { (_, items) -> items.take(limitPerCategory) }
}
override fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Series>> =
@@ -197,17 +218,11 @@ class SeriesRepositoryImpl @Inject constructor(
?: return Result.error("Provider not found")
// M3U and other non-Xtream providers have no standardized series-detail endpoint.
- if (provider.type != ProviderType.XTREAM_CODES.name) {
+ if (provider.type != ProviderType.XTREAM_CODES) {
return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
}
- val xtreamProvider = XtreamProvider(
- providerId = providerId,
- api = xtreamApiService,
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = CredentialCrypto.decryptIfNeeded(provider.password)
- )
+ val xtreamProvider = getOrCreateXtreamProvider(providerId, provider)
return when (val remoteResult = xtreamProvider.getSeriesInfo(seriesEntity.seriesId)) {
is Result.Success -> {
@@ -310,11 +325,15 @@ class SeriesRepositoryImpl @Inject constructor(
@Deprecated("Use getEpisodeStreamInfo() instead", ReplaceWith("getEpisodeStreamInfo(episode)"))
override suspend fun getEpisodeStreamUrl(episode: Episode): Result<String> =
- if (episode.streamUrl.isNotBlank()) {
- Result.success(episode.streamUrl)
- } else {
- Result.error("No stream URL available for episode: ${episode.title}")
- }
+ xtreamStreamUrlResolver.resolve(
+ url = episode.streamUrl,
+ fallbackProviderId = episode.providerId,
+ fallbackStreamId = episode.episodeId.takeIf { it > 0 } ?: episode.id,
+ fallbackContentType = ContentType.SERIES_EPISODE,
+ fallbackContainerExtension = episode.containerExtension
+ )?.let { resolvedUrl ->
+ Result.success(resolvedUrl)
+ } ?: Result.error("No stream URL available for episode: ${episode.title}")
override suspend fun refreshSeries(providerId: Long): Result<Unit> =
Result.success(Unit) // Handled by ProviderRepository
@@ -339,12 +358,22 @@ class SeriesRepositoryImpl @Inject constructor(
return seriesEntity.toDomain().copy(seasons = seasons)
}
- private fun String.toFtsPrefixQuery(): String {
- val tokens = trim()
- .split(Regex("\\s+"))
- .map { token -> token.replace(Regex("[^\\p{L}\\p{N}_]"), "") }
- .filter { it.length >= 2 }
+ private fun getOrCreateXtreamProvider(providerId: Long, provider: ProviderEntity): XtreamProvider {
+ val decryptedPassword = CredentialCrypto.decryptIfNeeded(provider.password)
+ val signature = listOf(provider.serverUrl, provider.username, decryptedPassword).joinToString("\u0000")
+ val cached = xtreamProviderCache[providerId]
+ if (cached != null && cached.signature == signature) {
+ return cached.provider
+ }
- return tokens.joinToString(" AND ") { "$it*" }
+ return XtreamProvider(
+ providerId = providerId,
+ api = xtreamApiService,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = decryptedPassword
+ ).also { xtreamProvider ->
+ xtreamProviderCache[providerId] = CachedXtreamProvider(signature, xtreamProvider)
+ }
}
}
diff --git a/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt b/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt
index 18fa3de3..70b40e1b 100644
--- a/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt
+++ b/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt
@@ -2,6 +2,7 @@ package com.streamvault.data.security
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
+import android.util.Log
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
@@ -14,6 +15,7 @@ import javax.crypto.spec.GCMParameterSpec
* Values are persisted as: enc:v1:<base64(iv + ciphertext)>
*/
object CredentialCrypto {
+ private const val TAG = "CredentialCrypto"
private const val KEYSTORE_TYPE = "AndroidKeyStore"
private const val KEY_ALIAS = "streamvault_credentials"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
@@ -31,9 +33,10 @@ object CredentialCrypto {
val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
val packed = iv + encrypted
PREFIX + java.util.Base64.getEncoder().encodeToString(packed)
- } catch (_: Exception) {
- // Fail closed would break existing users; keep original value if crypto fails.
- value
+ } catch (e: Exception) {
+ // Do NOT fall back to plaintext — rethrow so the caller can surface the failure.
+ Log.e(TAG, "Keystore encryption failed. Credential will NOT be stored.", e)
+ throw SecurityException("Failed to encrypt credential: ${e.message}", e)
}
}
@@ -55,8 +58,12 @@ object CredentialCrypto {
GCMParameterSpec(AUTH_TAG_BITS, iv)
)
String(cipher.doFinal(ciphertext), Charsets.UTF_8)
- } catch (_: Exception) {
- value
+ } catch (e: Exception) {
+ // Decryption failed (e.g. key invalidated after device reset).
+ // Return empty string — the caller will surface an auth failure rather than
+ // silently sending a garbled ciphertext blob as the password.
+ Log.e(TAG, "Keystore decryption failed. Stored credential is unreadable.", e)
+ ""
}
}
diff --git a/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt b/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt
new file mode 100644
index 00000000..a50dc09c
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt
@@ -0,0 +1,10 @@
+package com.streamvault.data.sync
+
+object ContentCachePolicy {
+ const val CATALOG_TTL_MILLIS = 24L * 60 * 60 * 1000L
+ const val EPG_TTL_MILLIS = 6L * 60 * 60 * 1000L
+
+ fun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long = System.currentTimeMillis()): Boolean {
+ return lastSyncAt <= 0L || now - lastSyncAt >= ttlMillis
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt b/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt
new file mode 100644
index 00000000..e82af47b
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt
@@ -0,0 +1,116 @@
+package com.streamvault.data.sync
+
+import android.util.Log
+import com.streamvault.data.local.StreamVaultDatabase
+import com.streamvault.data.local.dao.EpisodeDao
+import com.streamvault.data.local.dao.FavoriteDao
+import com.streamvault.data.local.dao.ProgramDao
+import java.io.File
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+@Singleton
+class DatabaseMaintenanceManager @Inject constructor(
+ private val database: StreamVaultDatabase,
+ private val programDao: ProgramDao,
+ private val episodeDao: EpisodeDao,
+ private val favoriteDao: FavoriteDao
+) {
+
+ suspend fun runDailyMaintenance(now: Long = System.currentTimeMillis()): MaintenanceReport = withContext(Dispatchers.IO) {
+ val oldProgramThreshold = now - PROGRAM_RETENTION_MILLIS
+ val deletedPrograms = programDao.deleteOld(oldProgramThreshold)
+ val deletedOrphanEpisodes = episodeDao.deleteOrphans()
+ val deletedStaleFavorites = favoriteDao.deleteMissingLiveFavorites() +
+ favoriteDao.deleteMissingMovieFavorites() +
+ favoriteDao.deleteMissingSeriesFavorites()
+
+ val statsBeforeVacuum = collectStorageStats()
+ val vacuumRan = shouldVacuum(statsBeforeVacuum)
+ if (vacuumRan) {
+ runVacuum()
+ }
+ val statsAfterVacuum = collectStorageStats()
+
+ MaintenanceReport(
+ deletedPrograms = deletedPrograms,
+ deletedOrphanEpisodes = deletedOrphanEpisodes,
+ deletedStaleFavorites = deletedStaleFavorites,
+ vacuumRan = vacuumRan,
+ statsBeforeVacuum = statsBeforeVacuum,
+ statsAfterVacuum = statsAfterVacuum
+ )
+ }
+
+ private fun collectStorageStats(): DatabaseStorageStats {
+ val sqliteDb = database.openHelper.writableDatabase
+ val pageSize = sqliteDb.longPragma("page_size")
+ val pageCount = sqliteDb.longPragma("page_count")
+ val freelistCount = sqliteDb.longPragma("freelist_count")
+ val databasePath = sqliteDb.path ?: return DatabaseStorageStats(
+ pageSizeBytes = pageSize,
+ pageCount = pageCount,
+ freelistCount = freelistCount,
+ mainDbBytes = 0L,
+ walBytes = 0L
+ )
+ val databaseFile = File(databasePath)
+ val walFile = File("$databasePath-wal")
+ return DatabaseStorageStats(
+ pageSizeBytes = pageSize,
+ pageCount = pageCount,
+ freelistCount = freelistCount,
+ mainDbBytes = databaseFile.length(),
+ walBytes = walFile.takeIf(File::exists)?.length() ?: 0L
+ )
+ }
+
+ private fun runVacuum() {
+ val sqliteDb = database.openHelper.writableDatabase
+ sqliteDb.query("PRAGMA wal_checkpoint(TRUNCATE)").use { }
+ sqliteDb.execSQL("VACUUM")
+ Log.i(TAG, "Database VACUUM completed")
+ }
+
+ private fun shouldVacuum(stats: DatabaseStorageStats): Boolean {
+ if (stats.reclaimableBytes < MIN_RECLAIMABLE_BYTES) return false
+ if (stats.mainDbBytes < MIN_DATABASE_BYTES) return false
+ return stats.reclaimableBytes * 100 >= stats.mainDbBytes * RECLAIMABLE_PERCENT_THRESHOLD
+ }
+
+ private fun androidx.sqlite.db.SupportSQLiteDatabase.longPragma(pragma: String): Long {
+ query("PRAGMA $pragma").use { cursor ->
+ return if (cursor.moveToFirst()) cursor.getLong(0) else 0L
+ }
+ }
+
+ data class MaintenanceReport(
+ val deletedPrograms: Int,
+ val deletedOrphanEpisodes: Int,
+ val deletedStaleFavorites: Int,
+ val vacuumRan: Boolean,
+ val statsBeforeVacuum: DatabaseStorageStats,
+ val statsAfterVacuum: DatabaseStorageStats
+ )
+
+ data class DatabaseStorageStats(
+ val pageSizeBytes: Long,
+ val pageCount: Long,
+ val freelistCount: Long,
+ val mainDbBytes: Long,
+ val walBytes: Long
+ ) {
+ val reclaimableBytes: Long get() = pageSizeBytes * freelistCount
+ val logicalDbBytes: Long get() = pageSizeBytes * pageCount
+ }
+
+ companion object {
+ private const val TAG = "DbMaintenance"
+ private const val PROGRAM_RETENTION_MILLIS = 24L * 60 * 60 * 1000L
+ private const val MIN_RECLAIMABLE_BYTES = 32L * 1024 * 1024
+ private const val MIN_DATABASE_BYTES = 128L * 1024 * 1024
+ private const val RECLAIMABLE_PERCENT_THRESHOLD = 20L
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
index 47aa0a12..b3d05337 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -14,10 +14,12 @@ import com.streamvault.data.mapper.toEntity
import com.streamvault.data.parser.M3uParser
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
+import com.streamvault.data.remote.xtream.XtreamUrlFactory
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.data.util.AdultContentClassifier
import com.streamvault.data.util.UrlSecurityPolicy
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
@@ -25,14 +27,11 @@ import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.repository.EpgRepository
import com.streamvault.domain.repository.SyncMetadataRepository
-import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
-import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
@@ -86,13 +85,13 @@ class SyncManager @Inject constructor(
private class CategoryAccumulator(
private val providerId: Long,
- private val type: String,
- private val startId: Long
+ private val type: ContentType,
+ private val startId: Long // retained for API compatibility but no longer used in ID generation
) {
private val categoryIds = LinkedHashMap<String, Long>()
fun idFor(name: String): Long {
- return categoryIds.getOrPut(name) { providerId * 100_000L + startId + categoryIds.size }
+ return categoryIds.getOrPut(name) { stableId(providerId, type, name) }
}
fun entities(): List<CategoryEntity> {
@@ -107,9 +106,17 @@ class SyncManager @Inject constructor(
)
}
}
- }
- private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ /** Generates a stable, collision-resistant ID from the provider+type+name triple. */
+ private fun stableId(providerId: Long, type: ContentType, name: String): Long {
+ val key = "$providerId/${type.name}/$name"
+ val bytes = java.security.MessageDigest.getInstance("SHA-256")
+ .digest(key.toByteArray(Charsets.UTF_8))
+ var result = 0L
+ for (i in 0 until 8) result = (result shl 8) or (bytes[i].toLong() and 0xFF)
+ return (result and Long.MAX_VALUE).coerceAtLeast(1L)
+ }
+ }
private val _syncState = MutableStateFlow<SyncState>(SyncState.Idle)
val syncState: StateFlow<SyncState> = _syncState.asStateFlow()
@@ -146,10 +153,6 @@ class SyncManager @Inject constructor(
}
}
- fun syncAsync(providerId: Long, force: Boolean = false, onProgress: ((String) -> Unit)? = null) {
- scope.launch { sync(providerId, force, onProgress) }
- }
-
fun resetState() {
_syncState.value = SyncState.Idle
}
@@ -202,7 +205,7 @@ class SyncManager @Inject constructor(
var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
- if (force || !isCacheValid(metadata.lastLiveSync, TTL_24_HOURS, now)) {
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
progress(onProgress, "Downloading Live TV...")
val cats = retryTransient { api.getLiveCategories().getOrThrow("Live categories") }
categoryDao.replaceAll(provider.id, "LIVE", cats.map { it.toEntity(provider.id) })
@@ -214,7 +217,7 @@ class SyncManager @Inject constructor(
syncMetadataRepository.updateMetadata(metadata)
}
- if (force || !isCacheValid(metadata.lastMovieSync, TTL_24_HOURS, now)) {
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
progress(onProgress, "Downloading Movies...")
val catsResult = runCatching { retryTransient { api.getVodCategories().getOrThrow("VOD categories") } }
catsResult.getOrNull()?.let {
@@ -229,7 +232,7 @@ class SyncManager @Inject constructor(
} ?: warnings.add("Movies streams sync failed")
}
- if (force || !isCacheValid(metadata.lastSeriesSync, TTL_24_HOURS, now)) {
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
progress(onProgress, "Downloading Series...")
val catsResult = runCatching { retryTransient { api.getSeriesCategories().getOrThrow("Series categories") } }
catsResult.getOrNull()?.let {
@@ -244,11 +247,13 @@ class SyncManager @Inject constructor(
} ?: warnings.add("Series list sync failed")
}
- if (force || !isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now)) {
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastEpgSync, ContentCachePolicy.EPG_TTL_MILLIS, now)) {
try {
progress(onProgress, "Downloading EPG...")
val base = provider.serverUrl.trimEnd('/')
- val xmltvUrl = provider.epgUrl.ifBlank { "$base/xmltv.php?username=${provider.username}&password=${provider.password}" }
+ val xmltvUrl = provider.epgUrl.ifBlank {
+ XtreamUrlFactory.buildXmltvUrl(base, provider.username, provider.password)
+ }
UrlSecurityPolicy.validateOptionalEpgUrl(xmltvUrl)?.let { message ->
throw IllegalStateException(message)
}
@@ -273,7 +278,7 @@ class SyncManager @Inject constructor(
var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
- if (force || !isCacheValid(metadata.lastLiveSync, TTL_24_HOURS, now)) {
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
val stats = withContext(Dispatchers.IO) { importM3uPlaylist(provider, onProgress) }
if (stats.liveCount == 0 && stats.movieCount == 0) {
throw IllegalStateException("Playlist is empty or contains no supported entries")
@@ -293,7 +298,7 @@ class SyncManager @Inject constructor(
}
val currentEpgUrl = providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
- if (!currentEpgUrl.isNullOrBlank() && (force || !isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now))) {
+ if (!currentEpgUrl.isNullOrBlank() && (force || ContentCachePolicy.shouldRefresh(metadata.lastEpgSync, ContentCachePolicy.EPG_TTL_MILLIS, now))) {
val epgValidationError = UrlSecurityPolicy.validateOptionalEpgUrl(currentEpgUrl)
if (epgValidationError != null) {
warnings.add(epgValidationError)
@@ -321,7 +326,9 @@ class SyncManager @Inject constructor(
val epgUrl = when (provider.type) {
ProviderType.XTREAM_CODES -> {
val base = provider.serverUrl.trimEnd('/')
- provider.epgUrl.ifBlank { "$base/xmltv.php?username=${provider.username}&password=${provider.password}" }
+ provider.epgUrl.ifBlank {
+ XtreamUrlFactory.buildXmltvUrl(base, provider.username, provider.password)
+ }
}
ProviderType.M3U -> providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
}
@@ -419,8 +426,8 @@ class SyncManager @Inject constructor(
progress(onProgress, "Downloading Playlist...")
val existingChannelIds = if (includeLive) channelDao.getIdMappings(provider.id).associate { it.remoteId to it.id } else emptyMap()
val existingMovieIds = if (includeMovies) movieDao.getIdMappings(provider.id).associate { it.remoteId to it.id } else emptyMap()
- val liveCategories = CategoryAccumulator(provider.id, "LIVE", 1L)
- val movieCategories = CategoryAccumulator(provider.id, "MOVIE", 10_000L)
+ val liveCategories = CategoryAccumulator(provider.id, ContentType.LIVE, 1L)
+ val movieCategories = CategoryAccumulator(provider.id, ContentType.MOVIE, 10_000L)
val channelBatch = ArrayList<ChannelEntity>(batchSize)
val movieBatch = ArrayList<MovieEntity>(batchSize)
val seenLiveStreamIds = if (includeLive) mutableSetOf<Long>() else null
@@ -451,7 +458,7 @@ class SyncManager @Inject constructor(
progress(onProgress, "Imported $parsedCount playlist entries...")
nextMilestone += PROGRESS_INTERVAL
}
- if (!UrlSecurityPolicy.isAllowedImportedUrl(entry.url)) {
+ if (!UrlSecurityPolicy.isAllowedStreamEntryUrl(entry.url)) {
insecureStreamCount++
return@parseStreaming
}
@@ -669,21 +676,8 @@ class SyncManager @Inject constructor(
return result and Long.MAX_VALUE
}
- internal fun isVodEntry(entry: M3uParser.M3uEntry): Boolean {
- val url = entry.url.lowercase()
- val group = entry.groupTitle.lowercase()
- return url.endsWith(".mp4") ||
- url.endsWith(".mkv") ||
- url.endsWith(".avi") ||
- url.contains("/movie/") ||
- group.contains("movie") ||
- group.contains("vod") ||
- group.contains("film")
- }
-
- private fun isCacheValid(lastSync: Long, ttlMillis: Long, now: Long = System.currentTimeMillis()): Boolean {
- return lastSync > 0 && (now - lastSync) < ttlMillis
- }
+ /** Delegates to M3uParser to avoid duplicate logic. */
+ internal fun isVodEntry(entry: M3uParser.M3uEntry): Boolean = M3uParser.isVodEntry(entry)
private fun progress(callback: ((String) -> Unit)?, message: String) {
_syncState.value = SyncState.Syncing(message)
@@ -740,8 +734,6 @@ class SyncManager @Inject constructor(
}
companion object {
- const val TTL_24_HOURS = 24L * 60 * 60 * 1000L
- const val TTL_6_HOURS = 6L * 60 * 60 * 1000L
private const val PROGRESS_INTERVAL = 5_000
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt
index 135b1864..b213e0bb 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt
@@ -4,7 +4,6 @@ import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
-import com.streamvault.data.local.dao.ProgramDao
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
@@ -18,22 +17,24 @@ class SyncWorker(
@EntryPoint
@InstallIn(SingletonComponent::class)
interface SyncWorkerEntryPoint {
- fun programDao(): ProgramDao
+ fun databaseMaintenanceManager(): DatabaseMaintenanceManager
}
override suspend fun doWork(): Result {
- Log.d("SyncWorker", "Starting EPG garbage collection...")
+ Log.d("SyncWorker", "Starting data maintenance...")
return try {
val entryPoint = EntryPointAccessors.fromApplication(applicationContext, SyncWorkerEntryPoint::class.java)
- val programDao = entryPoint.programDao()
-
- // Delete EPG programs older than 24 hours
- val threshold = System.currentTimeMillis() - (24 * 60 * 60 * 1000L)
- programDao.deleteOld(threshold)
- Log.d("SyncWorker", "Successfully cleaned old EPG data")
+ val report = entryPoint.databaseMaintenanceManager().runDailyMaintenance()
+ Log.d(
+ "SyncWorker",
+ "Maintenance complete: oldPrograms=${report.deletedPrograms}, orphanEpisodes=${report.deletedOrphanEpisodes}, " +
+ "staleFavorites=${report.deletedStaleFavorites}, vacuumRan=${report.vacuumRan}, " +
+ "dbBytes=${report.statsAfterVacuum.mainDbBytes}, walBytes=${report.statsAfterVacuum.walBytes}, " +
+ "reclaimableBytes=${report.statsAfterVacuum.reclaimableBytes}"
+ )
Result.success()
} catch (e: Exception) {
- Log.e("SyncWorker", "Failed to clean old EPG data", e)
+ Log.e("SyncWorker", "Failed to run data maintenance", e)
Result.retry()
}
}
diff --git a/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt b/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt
index 6b83ec9f..61eb53e1 100644
--- a/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt
+++ b/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt
@@ -44,9 +44,11 @@ object AdultContentClassifier {
fun isAdultCategoryName(name: String?): Boolean {
if (name.isNullOrBlank()) return false
- val normalized = normalize(name)
+ // Pad with spaces so we can do word-boundary matching via contains().
+ // This prevents "sex" matching "Essex" or "Middlesex", "adult" matching "adulting", etc.
+ val normalized = " ${normalize(name)} "
return keywords.any { keyword ->
- normalized.contains(normalize(keyword))
+ normalized.contains(" ${normalize(keyword)} ")
}
}
diff --git a/data/src/main/java/com/streamvault/data/util/FtsQueryUtils.kt b/data/src/main/java/com/streamvault/data/util/FtsQueryUtils.kt
new file mode 100644
index 00000000..b6b8f4e4
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/util/FtsQueryUtils.kt
@@ -0,0 +1,19 @@
+package com.streamvault.data.util
+
+/**
+ * Builds a Room FTS MATCH query string from a raw user search term.
+ *
+ * Each whitespace-separated token is stripped of non-word characters and
+ * turned into a prefix token (`token*`), joined with AND.
+ * Tokens shorter than 2 characters are ignored.
+ *
+ * Example: "star wars" → "star* AND wars*"
+ */
+internal fun String.toFtsPrefixQuery(): String {
+ val tokens = trim()
+ .split(Regex("\\s+"))
+ .map { token -> token.replace(Regex("[^\\p{L}\\p{N}_]"), "") }
+ .filter { it.length >= 2 }
+
+ return tokens.joinToString(" AND ") { "$it*" }
+}
diff --git a/data/src/main/java/com/streamvault/data/util/ProviderInputSanitizer.kt b/data/src/main/java/com/streamvault/data/util/ProviderInputSanitizer.kt
new file mode 100644
index 00000000..ed8f71de
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/util/ProviderInputSanitizer.kt
@@ -0,0 +1,51 @@
+package com.streamvault.data.util
+
+object ProviderInputSanitizer {
+ const val MAX_PROVIDER_NAME_LENGTH = 80
+ const val MAX_URL_LENGTH = 2048
+ const val MAX_USERNAME_LENGTH = 128
+ const val MAX_PASSWORD_LENGTH = 256
+
+ fun sanitizeProviderNameForEditing(input: String): String = sanitizeSingleLine(input, MAX_PROVIDER_NAME_LENGTH)
+
+ fun sanitizeUrlForEditing(input: String): String = sanitizeRaw(input, MAX_URL_LENGTH)
+
+ fun sanitizeUsernameForEditing(input: String): String = sanitizeSingleLine(input, MAX_USERNAME_LENGTH)
+
+ fun sanitizePasswordForEditing(input: String): String = sanitizeRaw(input, MAX_PASSWORD_LENGTH)
+
+ fun normalizeProviderName(input: String): String =
+ sanitizeSingleLine(input, MAX_PROVIDER_NAME_LENGTH)
+ .trim()
+ .replace(WHITESPACE_REGEX, " ")
+
+ fun normalizeUrl(input: String): String = sanitizeRaw(input, MAX_URL_LENGTH).trim()
+
+ fun normalizeUsername(input: String): String = sanitizeSingleLine(input, MAX_USERNAME_LENGTH).trim()
+
+ fun validateUrl(url: String): String? {
+ return if (url.any(Char::isWhitespace)) {
+ "URLs cannot contain spaces or line breaks."
+ } else {
+ null
+ }
+ }
+
+ private fun sanitizeSingleLine(input: String, maxLength: Int): String {
+ return sanitizeRaw(input, maxLength).replace(LINE_BREAK_REGEX, " ")
+ }
+
+ private fun sanitizeRaw(input: String, maxLength: Int): String {
+ val sanitized = buildString(input.length.coerceAtMost(maxLength)) {
+ input.forEach { char ->
+ if (!char.isISOControl()) {
+ append(char)
+ }
+ }
+ }
+ return sanitized.take(maxLength)
+ }
+
+ private val LINE_BREAK_REGEX = Regex("\\s+")
+ private val WHITESPACE_REGEX = Regex("\\s+")
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
index 83d2e6d4..4f47a466 100644
--- a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
+++ b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
@@ -6,12 +6,19 @@ import java.util.Locale
object UrlSecurityPolicy {
private val secureRemoteSchemes = setOf("https")
private val localSchemes = setOf("file", "content")
+ // IPTV stream/asset URLs may legitimately use plain HTTP or RTSP
+ private val streamEntrySchemes = setOf("http", "https", "rtsp", "rtsps", "rtmp", "file", "content")
fun isSecureRemoteUrl(url: String): Boolean = !containsNewlines(url) && hasAllowedScheme(url, secureRemoteSchemes)
fun isAllowedImportedUrl(url: String): Boolean =
!containsNewlines(url) && hasAllowedScheme(url, secureRemoteSchemes + localSchemes)
+ /** Validates individual stream/asset entries inside an imported playlist. HTTP is allowed here
+ * because the majority of IPTV providers serve streams over plain HTTP. */
+ fun isAllowedStreamEntryUrl(url: String): Boolean =
+ !containsNewlines(url) && hasAllowedScheme(url, streamEntrySchemes)
+
fun validateXtreamServerUrl(url: String): String? {
return if (isSecureRemoteUrl(url)) {
null
@@ -38,7 +45,7 @@ object UrlSecurityPolicy {
fun sanitizeImportedAssetUrl(url: String?): String? {
val value = url?.trim().orEmpty()
- return value.takeIf { it.isNotEmpty() && isAllowedImportedUrl(it) }
+ return value.takeIf { it.isNotEmpty() && isAllowedStreamEntryUrl(it) }
}
private fun hasAllowedScheme(url: String, allowedSchemes: Set<String>): Boolean {
diff --git a/docs/audit/00_EXECUTIVE_SUMMARY.md b/docs/audit/00_EXECUTIVE_SUMMARY.md
new file mode 100644
index 00000000..10f9d6a7
--- /dev/null
+++ b/docs/audit/00_EXECUTIVE_SUMMARY.md
@@ -0,0 +1,110 @@
+# StreamVault Pre-Release Audit: Executive Summary & Action Plan
+
+> **Audit Date:** March 17, 2026
+> **Audited Modules:** app, data, domain, player (full codebase)
+> **Total Files Reviewed:** ~100+ Kotlin source files, build configs, CI/CD, tests, security
+
+---
+
+## Overall Assessment
+
+StreamVault is a **well-engineered Android TV IPTV player** with clean multi-module architecture, modern Kotlin/Compose stack, and several strong security implementations. The codebase demonstrates thoughtful design decisions and consistent patterns across most areas.
+
+**However, the app is not ready for a premium production release.** There are 5 critical issues that must be fixed, 8 high-priority issues, and numerous medium/low items. The most impactful problems are: dead code in two major screens, thread safety bugs, race conditions, missing Android TV platform integration, and insufficient test coverage.
+
+---
+
+## Issue Count by Severity
+
+| Severity | Count | Description |
+|----------|-------|-------------|
+| 🔴 **CRITICAL** | 5 | Must fix before any release — broken features, data corruption risk |
+| 🟠 **HIGH** | 8 | Should fix before production — UX issues, security gaps, race conditions |
+| 🟡 **MEDIUM** | 12 | Fix within first release cycle — quality, consistency, accessibility |
+| 🟢 **LOW** | 15+ | Track for future improvements — nice-to-haves, optimizations |
+
+---
+
+## Critical Issues (Must Fix)
+
+| ID | Issue | File(s) | Details |
+|----|-------|---------|---------|
+| **C-1** | ~2,300 lines of dead code (unreachable after `return`) | MoviesScreen.kt, SeriesScreen.kt | Category sidebar browsing is completely non-functional |
+| **C-2** | 8 empty `onClick = { }` handlers on visible chips | MoviesScreen.kt, SeriesScreen.kt | Interactive-looking UI elements that do nothing |
+| **C-3** | `SimpleDateFormat` race condition in XmltvParser | XmltvParser.kt | Shared mutable instances used across threads |
+| **C-4** | Concurrent EPG sync can corrupt data | EpgRepositoryImpl.kt | Same staging ID used by parallel syncs |
+| **C-5** | Favorite position collision (non-atomic insert) | FavoriteRepositoryImpl.kt | Check-then-act without transaction wrapping |
+
+---
+
+## High Priority Issues
+
+| ID | Issue | Category |
+|----|-------|----------|
+| **H-1** | Hardcoded colors bypass theme system (MultiView + Dashboard) | UI Consistency |
+| **H-2** | Missing Android TV platform features (Watch Next, Voice Search) | Platform Integration |
+| **H-3** | Parental control state — in-memory only, no brute-force protection | Security / UX |
+| **H-4** | ConcurrentHashMap check-then-act race in SeriesRepository | Thread Safety |
+| **H-5** | Multi-provider sync state overwrites in SyncManager | Data Integrity |
+| **H-6** | CredentialCrypto silent failure — empty string on decryption error | UX / Security |
+| **H-7** | Network error types not classified (auth vs network vs parsing) | Error Handling |
+| **H-8** | Test coverage ~15-20% — missing security, error path, and integration tests | Quality Assurance |
+
+---
+
+## Detailed Audit Documents
+
+| Document | Focus Area |
+|----------|-----------|
+| [01_CRITICAL_ISSUES.md](01_CRITICAL_ISSUES.md) | Critical & High priority issues with code details |
+| [02_SECURITY_REVIEW.md](02_SECURITY_REVIEW.md) | OWASP-relevant security analysis |
+| [03_ARCHITECTURE_QUALITY_PERFORMANCE.md](03_ARCHITECTURE_QUALITY_PERFORMANCE.md) | Patterns, magic numbers, performance, accessibility |
+| [04_MISSING_FEATURES_COMPLETENESS.md](04_MISSING_FEATURES_COMPLETENESS.md) | Feature gaps, missing implementations, test coverage |
+
+---
+
+## Recommended Fix Order
+
+### Phase 1: Release Blockers (Before Any Release)
+1. Fix or remove dead code in MoviesScreen/SeriesScreen (C-1)
+2. Implement or remove empty onClick handlers (C-2)
+3. Fix XmltvParser SimpleDateFormat thread safety (C-3)
+4. Add per-provider EPG sync lock (C-4)
+5. Make favorite position insert atomic (C-5)
+
+### Phase 2: Production Hardening (Before Public Release)
+6. Replace hardcoded colors with theme tokens (H-1)
+7. Fix ConcurrentHashMap race in SeriesRepository (H-4)
+8. Fix SyncManager multi-provider state tracking (H-5)
+9. Surface CredentialCrypto decryption failures to user (H-6)
+10. Classify network errors properly (H-7)
+11. Persist parental control unlock state with TTL (H-3)
+12. Add security test suite (H-8)
+13. Add error path tests for critical flows
+
+### Phase 3: Premium Polish (For Premium Positioning)
+14. Implement Watch Next / recommendation channels (H-2)
+15. Add voice search integration
+16. Add quality selection UI in player
+17. Implement stream failover using alternativeStreams
+18. Add playback speed control
+19. Add more use cases in domain layer
+20. Improve accessibility (high contrast, reduced motion, text sizing)
+
+---
+
+## What's Working Well ✅
+
+| Area | Assessment |
+|------|-----------|
+| **Architecture** | Clean multi-module design (app/data/domain/player) with proper dependency direction |
+| **Credential Security** | AES-GCM with Android Keystore, PBKDF2 PIN hashing — industry standard |
+| **Input Validation** | Comprehensive sanitization and URL security policy |
+| **SQL Security** | All Room queries parameterized; FTS search properly escaped |
+| **Localization** | 25+ languages, full RTL support, all strings externalized |
+| **Streaming Protocol** | HLS, DASH, RTSP, MPEG-TS, Progressive all supported |
+| **UI Foundation** | Netflix-style design with hero banners, shimmer loading, focus management |
+| **Sync System** | WorkManager-based, exponential backoff retry, batch processing |
+| **Database Migrations** | 13 versioned migrations with no destructive fallback |
+| **PiP Support** | Picture-in-picture properly integrated with lifecycle |
+| **Multi-View** | Thermal-aware multi-stream playback with performance monitoring |
diff --git a/docs/audit/01_CRITICAL_BLOCKERS.md b/docs/audit/01_CRITICAL_BLOCKERS.md
deleted file mode 100644
index 15514bae..00000000
--- a/docs/audit/01_CRITICAL_BLOCKERS.md
+++ /dev/null
@@ -1,399 +0,0 @@
-# 01 — Critical Blockers
-
-All ship-blocking issues that will cause crashes, data loss, or security vulnerabilities in production.
-
----
-
-## 1. ✅ FIXED — Missing `proguard-rules.pro` — Release Builds Will Fail
-
-**Module:** Build Configuration
-**File:** `app/build.gradle.kts`
-**Severity:** 🔴 SHIP BLOCKER
-
-The release build type enables minification and resource shrinking but references a ProGuard rules file that does not exist:
-
-```kotlin
-buildTypes {
- release {
- isMinifyEnabled = true
- isShrinkResources = true
- proguardFiles(
- getDefaultProguardFile("proguard-android-optimize.txt"),
- "proguard-rules.pro" // ← FILE DOES NOT EXIST
- )
- }
-}
-```
-
-**Impact:** R8 will strip critical classes (Hilt components, Retrofit interfaces, Room entities, GSON models) causing runtime crashes in release builds.
-
-**Fix:** Create `app/proguard-rules.pro` with keep rules for:
-- Hilt-generated components
-- Retrofit service interfaces and GSON-serialized models
-- Room database entities and DAOs
-- Media3/ExoPlayer decoder internals
-- Domain model data classes used in serialization
-
----
-
-## 2. ✅ FIXED — Decoder Mode Logic Is Reversed
-
-**Module:** Player
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (lines 81–86)
-**Severity:** 🔴 SHIP BLOCKER
-
-```kotlin
-when (currentDecoderMode) {
- DecoderMode.AUTO -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
- DecoderMode.HARDWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF // ← WRONG
- DecoderMode.SOFTWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER // ← WRONG
-}
-```
-
-- Selecting **HARDWARE** actually *disables* extension renderers (software path used)
-- Selecting **SOFTWARE** *enables* extension renderers (hardware path used)
-- The user-facing setting does the opposite of what it claims
-
-**Fix:**
-```kotlin
-DecoderMode.HARDWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
-DecoderMode.SOFTWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF
-```
-
----
-
-## 3. ✅ FIXED — No MediaSession Integration — TV Remote Won't Work
-
-**Module:** Player
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt`
-**Severity:** 🔴 SHIP BLOCKER
-
-The `media3-session` library is declared as a dependency but never used. No `MediaSession` is created. This means:
-
-- Android TV remote control buttons (play/pause/stop) won't control playback
-- Fire TV Stick voice commands won't work
-- System media notifications are absent
-- Violates Android TV app quality guidelines
-
-**Fix:** Create a `MediaSession` in the player engine and expose it for the UI to bind:
-```kotlin
-private var mediaSession: MediaSession? = null
-
-// In player initialization:
-mediaSession = MediaSession.Builder(context, exoPlayer).build()
-
-// In release():
-mediaSession?.release()
-```
-
----
-
-## 4. ✅ FIXED — `pixelWidthHeightRatio` Stored as Frame Rate
-
-**Module:** Player
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (line 180)
-**Severity:** 🔴 CRITICAL
-
-```kotlin
-override fun onVideoSizeChanged(videoSize: VideoSize) {
- _videoFormat.value = VideoFormat(
- width = videoSize.width,
- height = videoSize.height,
- frameRate = videoSize.pixelWidthHeightRatio // ← THIS IS ASPECT RATIO, NOT FPS
- )
-}
-```
-
-`pixelWidthHeightRatio` is typically 1.0 (square pixels) and has nothing to do with frame rate. The diagnostics/stats overlay will show completely wrong frame rate data.
-
-**Fix:** Capture frame rate from `onVideoInputFormatChanged` callback instead:
-```kotlin
-override fun onVideoInputFormatChanged(eventTime: EventTime, format: Format, ...) {
- lastFrameRate = format.frameRate
-}
-```
-
----
-
-## 5. ⚠️ MITIGATED — EPG Staging Uses Negative Provider IDs — Data Corruption Risk
-
-**Module:** Data
-**File:** `data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt` (lines 48–49)
-**Severity:** 🔴 CRITICAL
-
-```kotlin
-val stagingProviderId = -providerId
-programDao.deleteByProvider(stagingProviderId)
-// ... insert programs with staging ID ...
-programDao.moveToProvider(stagingProviderId, providerId)
-```
-
-Using negative provider IDs as a staging mechanism creates a race condition: if sync is interrupted between insert and move, orphaned programs with negative IDs remain permanently. Concurrent syncs for different providers could also collide.
-
-**Fix:** Add a `sync_status` column (`STAGING` / `ACTIVE`) to the programs table instead of manipulating provider IDs.
-
----
-
-## 6. ✅ FIXED — M3U Category ID Collision Across Providers
-
-**Module:** Data
-**File:** `data/src/main/java/com/streamvault/data/sync/SyncManager.kt` (lines 419–430)
-**Severity:** 🔴 CRITICAL
-
-```kotlin
-class CategoryAccumulator(providerId: Long, type: String, startId: Long) {
- private val categoryIds = LinkedHashMap<String, Long>()
- fun idFor(name: String): Long {
- return categoryIds.getOrPut(name) { startId + categoryIds.size }
- }
-}
-```
-
-Category IDs are allocated sequentially (1–9999 for LIVE, 10000+ for MOVIE) without provider scoping. If two providers have categories, IDs will collide, causing channels from Provider A to appear under Provider B's categories.
-
-**Fix:** Scope IDs per provider: `providerId * 1_000_000 + index` or use truly unique auto-generated IDs.
-
----
-
-## 7. ⏭️ DEFERRED — Database Migration 8→9 ID Remapping Can Corrupt References
-
-**Module:** Data
-**File:** `data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt` (lines 180–290)
-**Severity:** 🔴 CRITICAL
-
-The migration rebuilds tables and attempts to remap IDs via JOIN:
-
-```sql
-INSERT INTO channel_id_map(old_id, new_id)
-SELECT old.id, new.id FROM channels old
-JOIN channels_new new
- ON new.provider_id = old.provider_id
- AND new.stream_id = old.stream_id
-```
-
-If duplicate `(provider_id, stream_id)` pairs exist in source data (which M3U imports don't prevent), the JOIN produces multiple matches. Favorites, history, and other references will point to wrong channels.
-
-**Fix:** Add `DISTINCT` or `LIMIT 1` per old_id, and validate uniqueness constraints before the JOIN.
-
----
-
-## 8. ✅ FIXED — ViewModels Never Cancel Background Jobs — Memory Leaks
-
-**Module:** App
-**Files:** Multiple ViewModels
-**Severity:** 🔴 CRITICAL
-
-`PlayerViewModel`, `HomeViewModel`, and `MultiViewViewModel` all create long-running `Job` references that are never cancelled in `onCleared()`:
-
-**PlayerViewModel:**
-```kotlin
-private var channelInfoHideJob: Job? = null
-private var liveOverlayHideJob: Job? = null
-private var diagnosticsHideJob: Job? = null
-private var numericInputCommitJob: Job? = null
-private var epgJob: Job? = null
-private var playlistJob: Job? = null
-// None cancelled in onCleared()
-```
-
-**HomeViewModel:**
-```kotlin
-private var epgJob: Job? = null
-private var loadChannelsJob: Job? = null
-private var categoriesJob: Job? = null
-private var recentChannelsJob: Job? = null
-private var previewPlaybackJob: Job? = null
-// None cancelled in onCleared()
-```
-
-**MultiViewViewModel:**
-```kotlin
-private var borderHideJob: Job? = null
-private var telemetryJob: Job? = null
-private val playerEngines = mutableMapOf<Int, PlayerEngine>()
-// PlayerEngine instances may not release on back press
-```
-
-**Impact:** When the user navigates away, Jobs keep running, player engines keep buffering, and memory is never reclaimed. On low-RAM TV devices this will cause ANR or OOM.
-
-**Fix:** Cancel all Jobs and release all resources in `onCleared()`:
-```kotlin
-override fun onCleared() {
- listOf(epgJob, playlistJob, channelInfoHideJob, ...).forEach { it?.cancel() }
- playerEngine.release()
-}
-```
-
----
-
-## 9. ✅ FIXED — Credentials Can Leak Into Crash Logs
-
-**Module:** Data
-**File:** `data/src/main/java/com/streamvault/data/sync/SyncManager.kt` (lines 738–753)
-**Severity:** 🔴 CRITICAL
-
-While `redactUrlForLogs()` exists, it is not consistently applied. Exception messages from OkHttp/Retrofit often embed the full URL including credentials:
-
-```kotlin
-Log.e(TAG, "Sync failed for provider $providerId: ${e.message}", e)
-// e.message → "Failed to reach http://user:pass@server:8080/get.php?..."
-```
-
-**Impact:** Credentials exposed in logcat, crash reporters (Firebase Crashlytics, etc.), and analytics.
-
-**Fix:** Always sanitize before logging:
-```kotlin
-val safeMessage = redactUrlForLogs(e.message ?: "unknown error")
-Log.e(TAG, "Sync failed for provider $providerId: $safeMessage")
-```
-
----
-
-## 10. ✅ FIXED — No Signing Configuration for Release
-
-**Module:** Build
-**File:** `app/build.gradle.kts`
-**Severity:** 🔴 SHIP BLOCKER
-
-No `signingConfigs` block exists. Cannot generate a signed APK/AAB for Google Play without manual configuration.
-
-**Fix:** Add a signing configuration that reads from environment variables or a local keystore properties file (not committed to VCS):
-```kotlin
-signingConfigs {
- create("release") {
- storeFile = file(keystoreProperties["storeFile"] as String)
- storePassword = keystoreProperties["storePassword"] as String
- keyAlias = keystoreProperties["keyAlias"] as String
- keyPassword = keystoreProperties["keyPassword"] as String
- }
-}
-```
-
----
-
-## 11. ✅ FIXED (race) / ⚠️ BY DESIGN (persistence) — ParentalControlManager Has Race Condition and No Persistence
-
-**Module:** Domain
-**File:** `domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt` (lines 21–28)
-**Severity:** 🔴 CRITICAL
-
-```kotlin
-fun unlockCategory(providerId: Long, categoryId: Long) {
- val current = _unlockedCategoriesByProvider.value.toMutableMap() // ← Non-atomic read
- val providerSet = (current[providerId] ?: emptySet()).toMutableSet()
- providerSet.add(categoryId)
- current[providerId] = providerSet
- _unlockedCategoriesByProvider.value = current // ← Race window
-}
-```
-
-**Issue 1:** Between `.value` read and `.value = current`, another coroutine can modify state → lost updates.
-**Issue 2:** All unlock state is held only in memory. App restart resets all parental control unlocks — parental controls are essentially useless.
-**Issue 3:** No PIN/password is required to unlock a category.
-
----
-
-## 12. ✅ FIXED — No Foreign Key Constraints in Room Database
-
-**Module:** Data
-**File:** `data/src/main/java/com/streamvault/data/local/entity/Entities.kt`
-**Severity:** 🔴 CRITICAL
-
-Room entities have no `@ForeignKey` annotations. Deleting a provider leaves behind orphaned channels, movies, series, favorites, EPG data, and playback history. Over time, the database accumulates ghost records consuming storage and degrading query performance.
-
-**Fix:** Add cascading foreign keys:
-```kotlin
-@Entity(
- foreignKeys = [ForeignKey(
- entity = ProviderEntity::class,
- parentColumns = ["id"],
- childColumns = ["provider_id"],
- onDelete = ForeignKey.CASCADE
- )]
-)
-```
-
----
-
-## 13. ✅ FIXED — XML Date Parsing Returns Epoch 0 Silently
-
-**Module:** Data
-**File:** `data/src/main/java/com/streamvault/data/parser/XmltvParser.kt` (lines 184–200)
-**Severity:** 🔴 CRITICAL
-
-```kotlin
-try {
- val cleaned = dateStr.replace("""[^\d]""".toRegex(), "")
- if (cleaned.length >= 14) {
- val basicFormat = SimpleDateFormat("yyyyMMddHHmmss", Locale.US)
- return basicFormat.parse(cleaned.substring(0, 14))?.time ?: 0
- }
-} catch (_: Exception) { }
-return 0 // ← Programs marked as starting at Jan 1, 1970
-```
-
-Any XMLTV program with an unparseable date gets `startTime = 0`, placing it in the distant past. These programs are silently lost from the EPG display. No warning is logged.
-
----
-
-## 14. ✅ FIXED — M3U Input Not Length-Bounded (DoS Vector)
-
-**Module:** Data
-**File:** `data/src/main/java/com/streamvault/data/parser/M3uParser.kt` (lines 299–330)
-**Severity:** 🔴 CRITICAL
-
-Channel names, group titles, and other strings from M3U files have no maximum length validation. A malicious or malformed M3U with megabyte-length strings will:
-1. Be stored in Room → database bloat
-2. Rendered in UI → ANR during text layout
-3. Occupy heap → OOM on low-RAM TV devices
-
-**Fix:** Truncate all parsed strings: `name = extinf.name.take(500)`, `groupTitle = group.take(200)`.
-
----
-
-## 15. ⚠️ FALSE POSITIVE — `file://` URI Exposure
-
-**Module:** App
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt` (line 91)
-**Severity:** 🔴 CRITICAL
-
-```kotlin
-m3uUrl = "file://${outFile.absolutePath}"
-```
-
-Direct `file://` URIs are forbidden on Android 7+ (API 24) for cross-process sharing and violate security best practices. On API 29+, scoped storage further restricts raw file access.
-
-**Fix:** Use `FileProvider` to serve local M3U files with `content://` URIs.
-
----
-
-## 16. ✅ FIXED — No Error Recovery Strategy in Player
-
-**Module:** Player
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (lines 172–173)
-**Severity:** 🔴 CRITICAL
-
-```kotlin
-override fun onPlayerError(error: PlaybackException) {
- _error.tryEmit(PlayerError.fromException(error))
- _playbackState.value = PlaybackState.ERROR
-}
-```
-
-When a stream fails, the player transitions to `ERROR` state and stays there permanently. IPTV streams frequently experience transient network issues — the player should auto-retry with exponential backoff. Currently the only recovery path is manual user intervention (selecting a different channel and coming back).
-
-**Fix:** Implement retry logic:
-```kotlin
-private var retryCount = 0
-private val maxRetries = 3
-
-override fun onPlayerError(error: PlaybackException) {
- if (retryCount < maxRetries && error.isRecoverable()) {
- retryCount++
- handler.postDelayed({ prepare(lastStreamInfo) }, retryCount * 2000L)
- } else {
- _error.tryEmit(PlayerError.fromException(error))
- _playbackState.value = PlaybackState.ERROR
- }
-}
-```
diff --git a/docs/audit/01_CRITICAL_ISSUES.md b/docs/audit/01_CRITICAL_ISSUES.md
new file mode 100644
index 00000000..46aa3e51
--- /dev/null
+++ b/docs/audit/01_CRITICAL_ISSUES.md
@@ -0,0 +1,241 @@
+# StreamVault Pre-Release Audit: Critical & High Issues
+
+> **Audit Date:** March 17, 2026
+> **Scope:** Full codebase review across all 4 modules (app, data, domain, player)
+> **Verdict:** App has a strong architectural foundation but has several critical items that must be resolved before production release.
+
+---
+
+## CRITICAL-1: Dead Code — ~2,300 Lines of Unreachable Code in Movies & Series Screens
+
+**Files:**
+- `app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt` (Line 192)
+- `app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt` (Line 192)
+
+**Description:**
+Both `MoviesScreen.kt` (1,342 lines) and `SeriesScreen.kt` (1,364 lines) contain a `return@AppScreenScaffold` at line 192, making everything after that line completely unreachable. This means:
+- The full category sidebar with search/filter/reorder functionality (~300+ lines each) is dead code
+- Category browsing, library lens navigation (top-rated, fresh, continue-watching), and reorder features are non-functional
+- Approximately **1,150 + 1,172 = 2,322 lines** of dead code
+
+**Impact:** Major feature set (VOD category management) is silently broken. Users cannot browse movies/series by category through the sidebar.
+
+**Action:** Either remove the `return@AppScreenScaffold` to restore the feature, or delete the dead code if the new approach (before the return) fully replaces it.
+
+---
+
+## CRITICAL-2: Non-Functional UI Elements — 8 Empty onClick Handlers
+
+**Files:**
+- `MoviesScreen.kt` — Lines 951, 961, 971, 1152
+- `SeriesScreen.kt` — Lines 983, 993, 1003, 1174
+
+**Description:**
+Eight `VodActionChip` components display data (counts, labels) but have `onClick = { }` — they do nothing when clicked. These include:
+- "Continue Watching" lens chips (show item count but don't navigate)
+- "Top Rated" lens chips (show pick count but don't filter)
+- "Fresh Movies/Series" lens chips (show count but don't filter)
+- Selected category display chips (show title count but don't open category)
+
+**Impact:** Users see interactive-looking chips that respond visually to focus but perform no action. This is a broken UX for a premium app.
+
+**Action:** Implement the lens navigation logic (scroll to section, filter content, etc.) or remove the chips entirely.
+
+---
+
+## CRITICAL-3: Thread Safety — XmltvParser SimpleDateFormat Race Condition
+
+**File:** `data/src/main/java/com/streamvault/data/parser/XmltvParser.kt` (Line ~30)
+
+**Description:**
+```kotlin
+private val dateFormats = listOf(
+ SimpleDateFormat("yyyyMMddHHmmss Z", Locale.US),
+ SimpleDateFormat("yyyyMMddHHmmss", Locale.US),
+).onEach { it.timeZone = TimeZone.getTimeZone("UTC") }
+```
+`SimpleDateFormat` is not thread-safe. These shared instances are reused across parsing calls without cloning. If concurrent EPG parsing triggers simultaneous date parsing, data corruption or crashes can occur.
+
+**Impact:** Potential crashes, corrupted EPG data, or wrong program times under concurrent load.
+
+**Action:** Clone each `SimpleDateFormat` before use, or migrate to `java.time.format.DateTimeFormatter` (thread-safe by design).
+
+---
+
+## CRITICAL-4: Race Condition — Concurrent EPG Sync Can Corrupt Data
+
+**File:** `data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt` (Lines 113-149)
+
+**Description:**
+EPG sync uses a staging provider ID (`-providerId`) for temporary storage during download. If two syncs run concurrently for the same provider:
+1. Both use the same staging ID (`-providerId`)
+2. Second sync overwrites the first sync's staged data
+3. Final transaction can commit mixed/incomplete data
+
+EPG parsing can take 30+ seconds, creating a large timing window.
+
+**Impact:** Corrupted EPG data — wrong programs displayed for channels.
+
+**Action:** Add a per-provider sync mutex/lock, or use unique staging IDs per sync operation.
+
+---
+
+## CRITICAL-5: Race Condition — Favorite Position Collision
+
+**File:** `data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt` (Line ~102)
+
+**Description:**
+```kotlin
+val maxPos = favoriteDao.getMaxPosition(groupId) ?: -1
+val favorite = Favorite(position = maxPos + 1, ...)
+```
+Position lookup and insert are not atomic. Two concurrent `addFavorite()` calls can get the same `maxPos` value, resulting in duplicate positions.
+
+**Impact:** Favorites list ordering breaks; items overlap in display.
+
+**Action:** Wrap in a Room `@Transaction`, or use `INSERT ... SELECT MAX(position)+1`.
+
+---
+
+## HIGH-1: Hardcoded Colors Outside Theme System — MultiViewScreen
+
+**File:** `app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt`
+
+**Description:**
+8+ hardcoded hex color values bypass the `AppColors` theme system:
+- `Color(0xFF555555)` — Gray placeholder (×2)
+- `Color(0xFFFF5252)` — Red error (×2)
+- `Color(0xFFFFC107)` — Amber blocked (×1)
+- `Color(0xFFFFE082)` — Light amber reason (×1)
+- `Color(0xFF4CAF50)` — Green status (referenced)
+- `Color.Black.copy(alpha=...)` — Semi-transparent overlays (×2)
+
+**Impact:** Theming/rebranding is inconsistent; these colors won't adapt to any future light/dark theme changes.
+
+**Action:** Replace with `AppColors` semantic tokens (e.g., `AppColors.ErrorColor`, `AppColors.Warning`, `AppColors.TextSecondary`).
+
+---
+
+## HIGH-2: Hardcoded Colors — DashboardScreen Shortcuts
+
+**File:** `app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt` (Lines ~351-353)
+
+**Description:**
+`DashboardShortcutType` uses hardcoded colors:
+- `0xFFFFC857` (Favorites)
+- `0xFF4FD1C5` (Recent)
+- `0xFF60A5FA` (Last Group)
+
+**Action:** Map to `AppColors` tokens.
+
+---
+
+## HIGH-3: Missing Android TV Platform Integration
+
+**Description:**
+Several expected Android TV platform features are completely absent:
+
+| Feature | Status | Impact |
+|---------|--------|--------|
+| **Voice Search** (SearchManager / ACTION_ASSIST) | ❌ Not implemented | Users can't search by voice on the home screen |
+| **Watch Next** (TvProvider integration) | ❌ Not implemented | App doesn't appear in the TV home screen's "Watch Next" row |
+| **Recommendation Channels** | ❌ Not implemented | No content surfaces on the Android TV launcher |
+| **TV Input Framework** (TvInputService) | ❌ Not implemented | App can't integrate with the system TV guide |
+| **Chromecast/Cast Support** | ❌ Not implemented | Can't cast to other devices |
+
+**Impact:** These are differentiators for a premium TV app. Watch Next and recommendations especially drive engagement by surfacing content on the Android TV home screen.
+
+**Action:** Prioritize Watch Next integration and voice search as minimum requirements for a premium TV experience.
+
+---
+
+## HIGH-4: Parental Control — In-Memory Only, No Persistence
+
+**File:** `domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt`
+
+**Description:**
+`ParentalControlManager` stores unlocked categories in memory only:
+- State is lost on app restart, process kill, or activity recreation
+- No integration with a repository for persistence
+- No unlock expiration/timeout (once unlocked, stays unlocked until process dies)
+- No brute-force protection (no attempt tracking or lockout)
+
+**Impact:** Users must re-enter PIN on every app launch for every locked category. No protection against PIN guessing.
+
+**Action:**
+1. Add session-scoped persistence (encrypted preferences with TTL)
+2. Implement attempt tracking with lockout (e.g., 5 attempts → 15 min lockout)
+3. Add configurable unlock timeout (e.g., 30 min auto-relock)
+
+---
+
+## HIGH-5: ConcurrentHashMap Check-Then-Act Race in SeriesRepository
+
+**File:** `data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt` (Lines ~32-39)
+
+**Description:**
+```kotlin
+private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()
+
+private fun getOrCreateXtreamProvider(...): XtreamProvider {
+ val cached = xtreamProviderCache[providerId]
+ if (cached != null && cached.signature == signature) return cached.provider
+ // Both threads can reach here simultaneously
+ return XtreamProvider(...).also {
+ xtreamProviderCache[providerId] = CachedXtreamProvider(...)
+ }
+}
+```
+The check-then-act pattern is not atomic despite using `ConcurrentHashMap`.
+
+**Impact:** Multiple unnecessary XtreamProvider creations; wasted CPU on password decryption.
+
+**Action:** Use `ConcurrentHashMap.computeIfAbsent()` or add a synchronized block.
+
+---
+
+## HIGH-6: SyncManager State Race — Multi-Provider Sync Overwrites Status
+
+**File:** `data/src/main/java/com/streamvault/data/sync/SyncManager.kt` (Line ~64)
+
+**Description:**
+A single `_syncState` StateFlow is shared across all provider syncs. When syncing multiple providers concurrently:
+1. Provider A starts → state = `Syncing("Live TV...")`
+2. Provider B starts → state = `Syncing("Movies...")` (overwrites A's status)
+3. Provider A finishes → state = `Success` (but B is still running)
+
+**Impact:** UI shows incorrect sync status; user thinks sync is complete when it isn't.
+
+**Action:** Track per-provider sync state, or serialize provider syncs.
+
+---
+
+## HIGH-7: CredentialCrypto Silent Failure on Decryption
+
+**File:** `data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt`
+
+**Description:**
+When decryption fails (corrupted data, key rotation, device factory reset), the method returns an empty string silently. No warning is shown to the user that their credentials need re-entry.
+
+**Impact:** User experiences mysterious login failures without understanding the cause.
+
+**Action:** Return a `Result` type or throw a specific exception that the UI can translate to "Please re-enter your credentials."
+
+---
+
+## HIGH-8: Network Error Classification — JSON vs Network vs Auth Errors
+
+**File:** `data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt` (Line ~36)
+
+**Description:**
+```kotlin
+private suspend inline fun <reified T> get(endpoint: String): T {
+ // ...
+ json.decodeFromString<T>(body) // Could throw JsonException
+}
+```
+All failures (network timeout, HTTP 401/403 auth errors, malformed JSON) are treated as generic `IOException`. The retry logic (`SyncManager.retryTransient`) then retries non-retryable errors like authentication failures.
+
+**Impact:** Wasted retries on auth errors; wrong error messages shown to users.
+
+**Action:** Catch and classify errors separately: network (retryable), auth (non-retryable), parsing (non-retryable).
diff --git a/docs/audit/02_PLAYER_ENGINE.md b/docs/audit/02_PLAYER_ENGINE.md
deleted file mode 100644
index b8bf0c17..00000000
--- a/docs/audit/02_PLAYER_ENGINE.md
+++ /dev/null
@@ -1,256 +0,0 @@
-# 02 — Player Engine Issues
-
-All issues related to media playback, decoding, buffering, and streaming.
-
----
-
-## 1. ✅ FIXED — Decoder Mode Logic Is Reversed
-
-> See [01_CRITICAL_BLOCKERS.md #2](01_CRITICAL_BLOCKERS.md#2-decoder-mode-logic-is-reversed)
-
----
-
-## 2. ✅ FIXED — Buffer Configuration Too Low for IPTV
-
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (lines 90–97)
-**Severity:** 🟠 HIGH
-
-```kotlin
-val loadControl = DefaultLoadControl.Builder()
- .setBufferDurationsMs(
- 15000, // min buffer — 15s
- 30000, // max buffer — 30s
- 2500, // playback start threshold
- 5000 // rebuffer threshold
- )
- .build()
-```
-
-- 15-second minimum buffer is inadequate for live IPTV streams over variable-quality networks
-- 30-second max buffer doesn't provide enough runway for network jitter
-- Users will experience frequent rebuffering
-
-**Recommendation:** Make buffer sizes configurable per use case:
-- **Single-stream playback:** 30s min / 60s max / 5s start / 10s rebuffer
-- **Multi-view (4 streams):** Keep current 15s/30s to manage memory
-- Expose as a user-facing setting (Low/Medium/High buffer)
-
----
-
-## 3. ✅ FIXED — No MediaSession Integration
-
-> See [01_CRITICAL_BLOCKERS.md #3](01_CRITICAL_BLOCKERS.md#3-no-mediasession-integration--tv-remote-wont-work)
-
----
-
-## 4. ✅ FIXED — No Network Error Recovery
-
-> See [01_CRITICAL_BLOCKERS.md #16](01_CRITICAL_BLOCKERS.md#16-no-error-recovery-strategy-in-player)
-
----
-
-## 5. ✅ FIXED — Video Format Frame Rate Is Wrong
-
-> See [01_CRITICAL_BLOCKERS.md #4](01_CRITICAL_BLOCKERS.md#4-pixelwidthheightratio-stored-as-frame-rate)
-
----
-
-## 6. ✅ FIXED — Error Classification Is Fragile (String Matching)
-
-**File:** `player/src/main/java/com/streamvault/player/PlayerEngine.kt` (lines 44–56)
-**Severity:** 🟠 HIGH
-
-```kotlin
-fun fromException(e: Throwable): PlayerError {
- val msg = e.message ?: "Unknown playback error"
- return when {
- msg.contains("Unable to connect", ignoreCase = true) -> NetworkError(msg)
- msg.contains("timeout", ignoreCase = true) -> NetworkError(msg)
- msg.contains("Response code: 4", ignoreCase = true) -> SourceError(msg)
- msg.contains("Response code: 5", ignoreCase = true) -> NetworkError(msg)
- msg.contains("decoder", ignoreCase = true) -> DecoderError(msg)
- msg.contains("codec", ignoreCase = true) -> DecoderError(msg)
- else -> UnknownError(msg)
- }
-}
-```
-
-String-matching error messages is fragile — messages change across Media3 versions. This also misclassifies:
-- 401/403 as generic `SourceError` (should be `AuthError`)
-- DRM failures as `UnknownError`
-- Manifest parse errors as `UnknownError`
-
-**Fix:** Use `PlaybackException.errorCode` for reliable classification:
-```kotlin
-fun fromException(e: Throwable): PlayerError = when (e) {
- is PlaybackException -> when (e.errorCode) {
- ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
- ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT -> NetworkError(e.message ?: "Network error")
- ERROR_CODE_DECODER_INIT_FAILED,
- ERROR_CODE_DECODER_QUERY_FAILED -> DecoderError(e.message ?: "Decoder error")
- ERROR_CODE_IO_BAD_HTTP_STATUS -> SourceError(e.message ?: "Source error")
- else -> UnknownError(e.message ?: "Unknown error")
- }
- else -> UnknownError(e.message ?: "Unknown error")
-}
-```
-
----
-
-## 7. ✅ FIXED — No Explicit Network Timeout on Data Source
-
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (lines 218–237)
-**Severity:** 🟠 HIGH
-
-The `OkHttpDataSource.Factory` relies on the injected OkHttpClient's timeouts. If that client has generous defaults (e.g., 30s connect, 60s read), live streams stuck in buffering won't timeout for a very long time. Users will see an infinite spinner.
-
-**Fix:** Set explicit timeouts appropriate for live streaming:
-```kotlin
-OkHttpDataSource.Factory(okHttpClient)
- .setDefaultRequestProperties(headers)
- .setConnectTimeoutMs(10_000)
- .setReadTimeoutMs(15_000)
-```
-
----
-
-## 8. ✅ FIXED — No Background/Foreground Lifecycle Handling
-
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt`
-**Severity:** 🟠 HIGH
-
-The player has no awareness of app lifecycle transitions. When the user presses the Home button on the TV remote:
-- Player continues buffering and decoding in the background
-- Battery/power drain on TV devices
-- Network bandwidth consumed unnecessarily
-- No pause-on-background for provider connection limits
-
-**Fix:** Make the player lifecycle-aware or ensure the hosting ViewModel/Activity pauses playback on `ON_STOP`.
-
----
-
-## 9. ✅ FIXED — Track Selection Has Redundant API Calls
-
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (lines 347–413)
-**Severity:** 🟡 MEDIUM
-
-Both `selectAudioTrack()` and `selectSubtitleTrack()` first disable-then-enable track types in separate `trackSelectionParameters` assignments, causing two parameter updates when one would suffice.
-
-```kotlin
-// Step 1: Enable type (unnecessary extra update)
-player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, false)
- .build()
-
-// Step 2: Then set override
-player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .setOverrideForType(...)
- .build()
-```
-
-These should be combined into a single parameter update to avoid an intermediate track selection state.
-
----
-
-## 10. ✅ FIXED — Polling Redundant with Position Discontinuity Listener
-
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (lines 427–437)
-**Severity:** 🟡 MEDIUM
-
-A 500ms polling loop updates `_currentPosition` and `_duration`, but `onPositionDiscontinuity()` already updates position. This creates redundant StateFlow emissions.
-
-For multi-view (4 players), this means 4 × 2Hz = 8 position updates per second on the main thread, plus redundant emissions from the discontinuity listener.
-
-**Recommendation:** Either remove polling and rely on the listener (less smooth) or reduce polling to 1Hz and sync with listener events.
-
----
-
-## 11. ✅ FIXED — No Bitrate / Quality Metrics for Diagnostics
-
-**File:** `player/src/main/java/com/streamvault/player/PlayerEngine.kt` (PlayerStats data class)
-**Severity:** 🟡 MEDIUM
-
-```kotlin
-data class PlayerStats(
- val videoCodec: String = "Unknown",
- val audioCodec: String = "Unknown",
- val videoBitrate: Int = 0,
- val droppedFrames: Int = 0,
- val width: Int = 0,
- val height: Int = 0
-)
-```
-
-Missing for premium diagnostics:
-- Current bandwidth estimate
-- Buffered duration percentage
-- Adaptive bitrate switching events
-- Rebuffering count and cumulative time
-- Audio sample rate and channel count
-- Latency (for live streams)
-
----
-
-## 12. ✅ FIXED — Stream Type Detection Incomplete
-
-**File:** `player/src/main/java/com/streamvault/player/StreamTypeDetector.kt` (lines 14–32)
-**Severity:** 🟡 MEDIUM
-
-The URL-based detection misses:
-- Smooth Streaming (`.ism` / `.isml`)
-- WebRTC streams
-- RTSP/RTMP (common in IPTV)
-- URLs with query parameters masking the extension (e.g., `http://x.com/stream?token=abc`)
-
-The fallback `StreamType.UNKNOWN` delegates to ExoPlayer's content-type sniffing, which works but adds startup latency for the first chunk download.
-
----
-
-## 13. ✅ FIXED — Audio Content Type Not Stream-Aware
-
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (lines 106–110)
-**Severity:** 🔵 LOW
-
-```kotlin
-.setAudioAttributes(
- AudioAttributes.Builder()
- .setUsage(C.USAGE_MEDIA)
- .setContentType(C.CONTENT_TYPE_MOVIE)
- .build(),
- true
-)
-```
-
-`CONTENT_TYPE_MOVIE` is always used regardless of whether the content is live TV, music, or a movie. While functionally fine, the Android audio system can optimize audio routing differently for `CONTENT_TYPE_MUSIC` vs `CONTENT_TYPE_MOVIE`.
-
----
-
-## 14. ⏭️ DEFERRED — No Chromecast / Cast Support
-
-**Severity:** 🟡 MEDIUM (for premium release)
-
-No Google Cast integration exists. Premium IPTV apps typically support casting from a phone/tablet to a Chromecast or TV. While this app targets Android TV directly, the Media3 Cast extension could enable cross-device scenarios.
-
----
-
-## 15. ✅ FIXED — Decoder Reuse Evaluation Not Logged
-
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (lines 117–130)
-**Severity:** 🔵 LOW
-
-The `DecoderReuseEvaluation` parameter in `onVideoInputFormatChanged` is never inspected. On some TV chipsets, decoder reuse failures are the root cause of black screens between channel switches. Logging this would aid debugging.
-
----
-
-## 16. ✅ FIXED — Coroutine Scope Cleanup Not Guaranteed
-
-**File:** `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt` (line 46)
-**Severity:** 🔵 LOW
-
-```kotlin
-private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
-```
-
-If `release()` is never called (e.g., due to a leak in the hosting ViewModel), the coroutine scope runs indefinitely. Consider using `LifecycleCoroutineScope` or adding a finalizer.
diff --git a/docs/audit/02_SECURITY_REVIEW.md b/docs/audit/02_SECURITY_REVIEW.md
new file mode 100644
index 00000000..fbf7981a
--- /dev/null
+++ b/docs/audit/02_SECURITY_REVIEW.md
@@ -0,0 +1,149 @@
+# StreamVault Pre-Release Audit: Security Review
+
+> **Audit Date:** March 17, 2026
+> **Focus:** OWASP Top 10, credential handling, network security, data protection
+
+---
+
+## Overview
+
+The app demonstrates strong security fundamentals (AES-GCM credential encryption, PBKDF2 PIN hashing, input sanitization). However, several gaps must be addressed for production hardening.
+
+---
+
+## SEC-1: No Certificate Pinning [MEDIUM-HIGH]
+
+**Location:** `app/src/main/java/com/streamvault/app/di/NetworkModule.kt`
+
+**Description:**
+OkHttp client accepts any CA-signed certificate. No certificate pinning is configured for any connections.
+
+**Risk:** Man-in-the-middle attacks on Xtream API login requests could intercept credentials even over HTTPS.
+
+**Recommendation:**
+Certificate pinning for IPTV providers is complex (providers use many different servers/domains) but at minimum the app should:
+1. Log certificate fingerprints on first connection
+2. Warn users if a certificate changes unexpectedly
+3. Consider Trust-on-First-Use (TOFU) model
+
+---
+
+## SEC-2: Global Cleartext HTTP Permitted [MEDIUM]
+
+**Location:** `app/src/main/res/xml/network_security_config.xml`
+
+```xml
+<base-config cleartextTrafficPermitted="true">
+```
+
+**Description:**
+HTTP traffic is permitted globally. While necessary for IPTV stream URLs (many providers use HTTP), this means API/control traffic could also use HTTP in edge cases.
+
+**Current Mitigation:** `UrlSecurityPolicy.validateXtreamServerUrl()` enforces HTTPS for Xtream API URLs.
+
+**Recommendation:**
+The mitigation is adequate for Xtream, but document clearly why cleartext is globally enabled and ensure all non-stream network calls enforce HTTPS at the code level.
+
+---
+
+## SEC-3: Database Not Encrypted at Rest [MEDIUM]
+
+**Location:** `data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt`
+
+**Description:**
+Room database is stored as plaintext SQLite. While credentials are encrypted separately via `CredentialCrypto`, the database still contains:
+- Provider server URLs and usernames (in the providers table)
+- Complete channel/movie/series catalogs
+- Viewing history and favorites
+- Parental control category flags
+
+**Recommendation:**
+Consider SQLCipher integration for database-level encryption. Evaluate trade-off against performance impact (SQLCipher adds ~5-15% overhead).
+
+---
+
+## SEC-4: PIN Stored as String in Memory [LOW]
+
+**Location:** `data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt`
+
+**Description:**
+Parental control PIN is received as `String` parameter and processed through PBKDF2. While hashing is correct (120k iterations, random salt), the PIN string itself remains in JVM heap memory until garbage collected.
+
+**Recommendation:**
+Accept `CharArray` instead of `String`, zero it after hashing. Low risk on Android TV (physical access needed), but best practice.
+
+---
+
+## SEC-5: No Key Rotation Mechanism [LOW]
+
+**Location:** `data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt`
+
+**Description:**
+The encryption key (`KEY_ALIAS = "streamvault_credentials"`) has no rotation mechanism. If the Android Keystore is compromised, all stored credentials remain exposed until the user manually re-enters them.
+
+**Recommendation:**
+Add a key rotation function that re-encrypts all credentials with a new key, triggered periodically or on security events.
+
+---
+
+## SEC-6: GSON Reflection Still in Use [LOW]
+
+**Location:** `gradle/libs.versions.toml`, various DTO classes
+
+**Description:**
+GSON uses runtime reflection for (de)serialization, which:
+1. Can bypass ProGuard obfuscation if rules aren't perfectly configured
+2. Exposes class structure at runtime
+3. Conflicts with the app's shift to `kotlinx.serialization` (used in `OkHttpXtreamApiService`)
+
+**Recommendation:**
+Complete migration from GSON to `kotlinx.serialization` for consistency and better obfuscation support.
+
+---
+
+## SEC-7: HTTP Logging Could Leak Sensitive Data [LOW]
+
+**Location:** `app/src/main/java/com/streamvault/app/di/NetworkModule.kt`
+
+**Description:**
+`HttpLoggingInterceptor` is configured at `BASIC` level in releases, which logs URLs. Xtream API URLs contain credentials in query parameters (`username`, `password`).
+
+**Current Mitigation:** `XtreamUrlFactory.sanitizeLogMessage()` is used. Verify it covers all code paths.
+
+**Recommendation:**
+Ensure `sanitizeLogMessage()` is applied to ALL OkHttp logging, not just explicit calls. Consider stripping query parameters entirely from logs.
+
+---
+
+## SEC-8: Missing CI/CD Security Pipeline [MEDIUM]
+
+**Location:** `.github/workflows/android.yml`
+
+**Description:**
+The CI/CD pipeline runs only `assembleDebug` and unit tests. Missing:
+- Secret scanning (TruffleHog or similar)
+- Dependency vulnerability scanning (OWASP dependency-check)
+- Lint security checks
+- Release build validation with ProGuard
+- Code coverage reporting
+
+**Recommendation:**
+Add security-focused CI steps before first production release.
+
+---
+
+## Security Strengths ✅
+
+The following security practices are well-implemented:
+
+| Feature | Implementation | Assessment |
+|---------|---------------|------------|
+| **Credential Encryption** | AES-256-GCM with Android Keystore, randomized 12-byte IV | Excellent |
+| **PIN Hashing** | PBKDF2-SHA256, 120k iterations, 16-byte random salt | Industry standard |
+| **Legacy PIN Migration** | Auto-migrates plaintext PIN to hashed on next verify | Good hygiene |
+| **Input Sanitization** | `ProviderInputSanitizer` enforces length limits, removes control chars | Solid |
+| **URL Validation** | `UrlSecurityPolicy` validates scheme, checks CRLF injection | Comprehensive |
+| **SQL Injection Prevention** | Room parameterized queries throughout; FTS queries properly escaped | Excellent |
+| **Manifest Permissions** | Minimal: INTERNET + NETWORK_STATE only | Best practice |
+| **Backup Prevention** | `android:allowBackup="false"` | Correct for security-sensitive app |
+| **Xtream URL Sanitization** | Credentials stripped from log output | Good practice |
diff --git a/docs/audit/03_ARCHITECTURE_QUALITY_PERFORMANCE.md b/docs/audit/03_ARCHITECTURE_QUALITY_PERFORMANCE.md
new file mode 100644
index 00000000..d1922fb0
--- /dev/null
+++ b/docs/audit/03_ARCHITECTURE_QUALITY_PERFORMANCE.md
@@ -0,0 +1,281 @@
+# StreamVault Pre-Release Audit: Architecture, Code Quality & Performance
+
+> **Audit Date:** March 17, 2026
+> **Focus:** Patterns, redundancy, performance, magic numbers, architectural inconsistencies
+
+---
+
+## 1. Magic Numbers — No Centralized Configuration
+
+**Severity:** MEDIUM
+**Scope:** Entire codebase
+
+Dozens of numeric constants are scattered inline across files with no centralized configuration. This makes tuning and debugging difficult.
+
+### Player Module
+| Value | File | Purpose |
+|-------|------|---------|
+| `30,000 ms` | Media3PlayerEngine.kt | Min buffer duration |
+| `60,000 ms` | Media3PlayerEngine.kt | Max buffer duration |
+| `2,500 ms` | Media3PlayerEngine.kt | Playback buffer |
+| `5,000 ms` | Media3PlayerEngine.kt | Rebuffer buffer |
+| `10 s` | Media3PlayerEngine.kt | OkHttp connect timeout |
+| `15 s` | Media3PlayerEngine.kt | OkHttp read timeout |
+| `250 ms` | Media3PlayerEngine.kt | Position polling interval |
+| `1,500 ms` | Media3PlayerEngine.kt | Bandwidth stats interval |
+| `MAX_RETRIES = 3` | Media3PlayerEngine.kt | Retry limit |
+| `2,000 ms` | Media3PlayerEngine.kt | Retry base delay |
+| `0.2f` | Media3PlayerEngine.kt | Audio ducking ratio (20%) |
+| `1280×720` | Media3PlayerEngine.kt | Multi-view resolution cap |
+
+### Data Module
+| Value | File | Purpose |
+|-------|------|---------|
+| `30 s` | NetworkTimeoutConfig.kt | Connect/read/write timeout |
+| `200 MB` | EpgRepositoryImpl.kt | Max EPG file size |
+| `1 hour` | EpgRepositoryImpl.kt | EPG lookback window |
+| `2 hours` | EpgRepositoryImpl.kt | EPG lookahead window |
+| `60 s` | EpgRepositoryImpl.kt | EPG refresh interval |
+| `1,000` | SyncManager.kt | M3U batch size |
+| `500` | EpgRepositoryImpl.kt | EPG batch size |
+| `3 / 700ms` | SyncManager.kt | Retry attempts / initial delay |
+| `120,000` | PreferencesRepository.kt | PBKDF2 iterations |
+
+### App Module
+| Value | File | Purpose |
+|-------|------|---------|
+| `0.15` | StreamVaultApp.kt | Image cache memory ratio |
+| `100 MB` | StreamVaultApp.kt | Image disk cache size |
+| `6` / `4` | StreamVaultApp.kt | Coroutine parallelism limits |
+| `64` / `10` | NetworkModule.kt | OkHttp max requests / per-host |
+| `120 ms` | HomeViewModel.kt | Debounce interval |
+| `150 ms` / `200 ms` / `500 ms` | Various dialogs | Focus delay magic numbers |
+| `30 s` | Cards.kt | EPG progress bar tick rate |
+| `1,000 ms` | SkeletonLoader.kt | Shimmer animation duration |
+
+### Recommendation
+Create a `ConfigConstants.kt` object in each module or a shared config:
+```kotlin
+object PlayerConfig {
+ const val MIN_BUFFER_MS = 30_000L
+ const val MAX_BUFFER_MS = 60_000L
+ const val PLAYBACK_BUFFER_MS = 2_500L
+ // ...
+}
+```
+
+---
+
+## 2. State Management Fragmentation in UI Screens
+
+**Severity:** MEDIUM
+**Files:** HomeScreen.kt, SettingsScreen.kt, MoviesScreen.kt, SeriesScreen.kt
+
+**Description:**
+Dialog state management uses multiple independent boolean flags instead of a sealed class:
+```kotlin
+// Current pattern (HomeScreen):
+uiState.showPinDialog
+uiState.showDeleteGroupDialog
+uiState.showRenameGroupDialog
+uiState.showCategoryOptionsDialog
+uiState.showMultiViewPlannerDialog
+uiState.selectedCategoryForOptions
+```
+
+This leads to:
+- Risk of multiple dialogs being open simultaneously
+- Complex conditional logic to manage transitions
+- Difficult to trace dialog state flow
+
+**Recommendation:**
+Use a sealed class for dialog state:
+```kotlin
+sealed class DialogState {
+ object None : DialogState()
+ data class PinEntry(val pendingAction: PendingAction) : DialogState()
+ data class CategoryOptions(val categoryId: Long) : DialogState()
+ data class RenameGroup(val groupId: Long, val currentName: String) : DialogState()
+ // ...
+}
+```
+
+---
+
+## 3. Focus Management — Brittle Exception Swallowing
+
+**Severity:** MEDIUM
+**Files:** PlayerScreen.kt, PlayerControlsChrome.kt, RenameGroupDialog.kt, PinDialog.kt
+
+**Description:**
+Multiple locations use the pattern:
+```kotlin
+try { focusRequester.requestFocus() } catch (_: Exception) {}
+```
+
+This silently swallows all exceptions including unexpected ones. At least 8 instances across the codebase.
+
+**Recommendation:**
+1. Catch only `IllegalStateException` (the expected failure when FocusRequester isn't attached)
+2. Log at debug level for diagnostics:
+```kotlin
+try {
+ focusRequester.requestFocus()
+} catch (e: IllegalStateException) {
+ Log.d(TAG, "Focus request failed: ${e.message}")
+}
+```
+
+---
+
+## 4. Inconsistent Error Handling Patterns Across Repositories
+
+**Severity:** MEDIUM
+**Scope:** `domain/src/main/java/com/streamvault/domain/repository/`
+
+**Description:**
+Repository interfaces are inconsistent about whether methods return `Result<T>` or throw exceptions:
+
+| Repository | Returns Result | Throws Exceptions | Returns Flow |
+|-----------|---------------|-------------------|-------------|
+| ProviderRepository | `addProvider`, `deleteProvider` | - | `getProviders` |
+| ChannelRepository | `refreshChannels` | - | `getChannels`, `searchChannels` |
+| EpgRepository | `refreshEpg` | - | `getProgramsForChannel` |
+| PlaybackHistoryRepository | - | `recordPlayback` (suspend) | `getRecentlyWatched` |
+| CategoryRepository | - | `setCategoryProtection` (suspend) | `getCategories` |
+
+Some suspend functions return `Result<T>`, others return raw values and rely on callers to catch exceptions.
+
+**Recommendation:**
+Standardize: all mutation operations return `Result<T>`, all query operations return `Flow<T>`.
+
+---
+
+## 5. Deprecated Methods Not Cleaned Up
+
+**Severity:** LOW
+**Files:** ChannelRepository.kt, MovieRepository.kt, SeriesRepository.kt
+
+**Description:**
+`getStreamUrl()` is deprecated in favor of `getStreamInfo()` but still exists with a default implementation that wraps the new method. These deprecated methods add confusion and code surface area.
+
+**Recommendation:**
+Remove deprecated methods in a release cleanup since all callers should be using `getStreamInfo()` by now.
+
+---
+
+## 6. Performance — Offset-Based Pagination
+
+**Severity:** LOW
+**Files:** MovieRepositoryImpl.kt, SeriesRepositoryImpl.kt (DAO queries)
+
+**Description:**
+Paginated queries use `LIMIT/OFFSET`, which requires scanning all prior rows for each page:
+- Page 1: Scans 0 rows, returns 50
+- Page 100: Scans 4,950 rows, returns 50
+
+With providers offering 50k-100k movies, deep pagination becomes increasingly slow.
+
+**Current Reality:** Users rarely browse past page 10-20. Not a blocking issue.
+
+**Future Optimization:** Consider keyset/cursor-based pagination for large catalogs.
+
+---
+
+## 7. Performance — EPG Progress Bar Tick Rate
+
+**Severity:** LOW
+**File:** `app/src/main/java/com/streamvault/app/ui/components/Cards.kt`
+
+**Description:**
+Channel cards update EPG progress every 30 seconds via `delay(30_000)`. With many visible channels, this creates periodic recomposition waves.
+
+**Recommendation:**
+Only run the timer for visible cards (LazyList already helps with this, but verify with profiling).
+
+---
+
+## 8. Performance — Channel Grouping In-Memory
+
+**Severity:** LOW
+**File:** `data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt`
+
+**Description:**
+Channel grouping creates full in-memory maps:
+```kotlin
+entities.groupBy { channelGroupKey(it) }
+ .values.map { group ->
+ group.sortedWith(compareBy({ it.errorCount }, { it.name.length }))
+ }
+```
+
+With 10k+ channels per provider, this creates significant temporary allocations.
+
+**Recommendation:**
+Accept for now; optimize with database-side grouping if profiling shows issues.
+
+---
+
+## 9. Missing Database Indexes
+
+**Severity:** LOW
+**File:** `data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt`
+
+**Missing indexes that could improve query performance:**
+
+| Table | Missing Index | Affected Query |
+|-------|--------------|----------------|
+| Programs | `(provider_id, start_time, end_time)` | Broad EPG time-window queries |
+| Categories | `(provider_id, type)` | Category type filtering |
+| Virtual Groups | `content_type` | Favorites by content type |
+
+**Recommendation:**
+Add these indexes in the next database migration.
+
+---
+
+## 10. ProGuard — Incomplete Protection Rules
+
+**Severity:** LOW
+**File:** `app/proguard-rules.pro`
+
+**Description:**
+ProGuard rules are well-written but missing explicit protection for:
+- `CredentialCrypto` internal class names (could break Keystore alias lookup if reflection used)
+- OkHttp certificate validator implementations
+
+**Current Reality:** This likely works fine with standard R8-defaults. Test a release APK to verify.
+
+---
+
+## 11. Compose TV Alpha Dependency
+
+**Severity:** MEDIUM
+**File:** `gradle/libs.versions.toml`
+
+**Description:**
+`androidx.tv:tv-material` is at version `1.0.0-alpha12` — still in alpha. Breaking API changes are possible with updates.
+
+**Risk:** Future updates may require migration effort. Alpha APIs may have bugs or performance issues.
+
+**Recommendation:**
+Pin the version and only update after thorough testing. Document which specific alpha APIs are in use for future migration planning.
+
+---
+
+## 12. Accessibility Gaps for Android TV
+
+**Severity:** MEDIUM
+**Scope:** Entire UI layer
+
+| Feature | Status | Impact |
+|---------|--------|--------|
+| **Content descriptions** | ✅ Good coverage | Most interactive elements labeled |
+| **High contrast mode** | ❌ Not implemented | Low-vision users can't distinguish focus |
+| **Reduced motion** | ❌ Not implemented | Shimmer animations can be problematic |
+| **Text size configuration** | ❌ Not implemented | Fixed text sizes throughout |
+| **Screen reader navigation** | ⚠️ Partial | Focus system works but no TalkBack testing documented |
+| **Focus ring visibility** | ⚠️ Borderline | 3dp border may be too faint on large displays |
+
+**Recommendation:**
+At minimum, respect `Settings.Global.ANIMATOR_DURATION_SCALE` for reduced motion, and test with TalkBack enabled.
diff --git a/docs/audit/03_DATA_LAYER.md b/docs/audit/03_DATA_LAYER.md
deleted file mode 100644
index 9d78914b..00000000
--- a/docs/audit/03_DATA_LAYER.md
+++ /dev/null
@@ -1,233 +0,0 @@
-# 03 — Data Layer Issues
-
-Database, parsing, sync, data integrity, and repository implementation issues.
-
----
-
-## 1. ✅ FIXED — EPG Date Parsing Silently Returns Epoch 0
-
-> See [01_CRITICAL_BLOCKERS.md #13](01_CRITICAL_BLOCKERS.md#13-xml-date-parsing-returns-epoch-0-silently)
-
----
-
-## 2. ✅ FIXED — M3U Input Not Length-Bounded
-
-> See [01_CRITICAL_BLOCKERS.md #14](01_CRITICAL_BLOCKERS.md#14-m3u-input-not-length-bounded-dos-vector)
-
----
-
-## 3. ⚠️ MITIGATED — EPG Staging Uses Negative Provider IDs
-
-> See [01_CRITICAL_BLOCKERS.md #5](01_CRITICAL_BLOCKERS.md#5-epg-staging-uses-negative-provider-ids--data-corruption-risk)
-
----
-
-## 4. ✅ FIXED — Category ID Collision Across Providers
-
-> See [01_CRITICAL_BLOCKERS.md #6](01_CRITICAL_BLOCKERS.md#6-m3u-category-id-collision-across-providers)
-
----
-
-## 5. ⏭️ DEFERRED — Database Migration 8→9 Unsafe ID Remapping
-
-> See [01_CRITICAL_BLOCKERS.md #7](01_CRITICAL_BLOCKERS.md#7-database-migration-89-id-remapping-can-corrupt-references)
-
----
-
-## 6. ✅ FIXED — Credentials Can Leak in Logs
-
-> See [01_CRITICAL_BLOCKERS.md #9](01_CRITICAL_BLOCKERS.md#9-credentials-can-leak-into-crash-logs)
-
----
-
-## 7. ✅ FIXED — No Foreign Key Constraints
-
-> See [01_CRITICAL_BLOCKERS.md #12](01_CRITICAL_BLOCKERS.md#12-no-foreign-key-constraints-in-room-database)
-
----
-
-## 8. ✅ FIXED — M3U URL Validation Insufficient
-
-**File:** `data/src/main/java/com/streamvault/data/parser/M3uParser.kt` (lines 312–320)
-**File:** `data/src/main/java/com/streamvault/data/sync/SyncManager.kt` (lines 448–451)
-**Severity:** 🟠 HIGH
-
-While `UrlSecurityPolicy.isAllowedImportedUrl()` exists, M3U entries can still contain:
-- Encoded newlines (`%0A`, `%0D%0A`) for HTTP header injection
-- `file:///` protocol for local file access
-- `javascript:` or `data:` URIs (if rendered in any UI context)
-
-**Fix:** After URL parsing, validate with `URI.create()` and explicitly reject non-`http`/`https` schemes:
-```kotlin
-val uri = try { URI.create(url) } catch (_: Exception) { return null }
-if (uri.scheme !in listOf("http", "https")) return null
-```
-
----
-
-## 9. ✅ FIXED — FTS Search Results Silently Truncated at 300
-
-**File:** `data/src/main/java/com/streamvault/data/local/dao/Daos.kt` (lines 83–100)
-**Severity:** 🟠 HIGH
-
-All search queries use `LIMIT 300` with no indication to the user that more results exist. If a provider has 10,000 channels and the search matches 2,000, the user only sees 300 with no "load more" or "showing X of Y" indicator.
-
-**Fix:** Either implement paginated search or return the total count alongside results:
-```sql
-SELECT COUNT(*) FROM channels_fts WHERE channels_fts MATCH :query
-```
-
----
-
-## 10. ⚠️ MITIGATED — Large EPG Files Can Cause OOM
-
-**File:** `data/src/main/java/com/streamvault/data/sync/SyncManager.kt` (lines 561–576)
-**Severity:** 🟠 HIGH
-
-The EPG download uses a 64KB `GZIPInputStream` buffer, but for very large EPG files (500MB+ compressed, common with large IPTV providers), the full decompressed XML can exhaust the Java heap on memory-constrained TV devices.
-
-**Mitigation:** The XMLTV parser does use streaming (XmlPullParser), which is good. But the download response body itself may buffer significant amounts. Add:
-1. A file size check before download (HEAD request)
-2. A maximum file size limit (e.g., 200MB compressed)
-3. Progress reporting during EPG parse
-
----
-
-## 11. ✅ FIXED — PlaybackHistory Restore Uses N+1 Query Pattern
-
-**File:** `data/src/main/java/com/streamvault/data/local/dao/Daos.kt` (lines 248–264)
-**Severity:** 🟠 HIGH
-
-```sql
-UPDATE movies SET watch_progress = (
- SELECT resume_position_ms FROM playback_history
- WHERE playback_history.content_id = movies.id
- AND playback_history.content_type = 'MOVIE'
- AND playback_history.provider_id = :providerId
-) WHERE id IN (...)
-```
-
-The correlated subquery executes once per matched movie row. With 10,000+ movies, this query can take several seconds on low-end TV hardware.
-
-**Fix:** Use a JOIN-based UPDATE or batch the operation with explicit chunking.
-
----
-
-## 12. ✅ FIXED — RecordingManager Race Condition
-
-**File:** `data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt` (lines 50–52)
-**Severity:** 🟠 HIGH
-
-The `stateMutex` protects `itemsState` but `activeJobs` is accessed from multiple coroutines without consistent mutex protection. Multiple concurrent recording operations could cause `ConcurrentModificationException` or lost updates.
-
----
-
-## 13. ✅ FIXED — M3U Parser Unquoted Attribute Values
-
-**File:** `data/src/main/java/com/streamvault/data/parser/M3uParser.kt` (lines 309–330)
-**Severity:** 🟡 MEDIUM
-
-If an M3U file uses unquoted attribute values with spaces:
-```
-#EXTINF:-1 group-title=My Group Name,Channel Name
-```
-
-The parser will extract only "My" as the group title because whitespace terminates unquoted value parsing. This causes channels to be placed in fragmented/wrong categories.
-
----
-
-## 14. ✅ FIXED — Adult Content Classifier Is English-Only
-
-**File:** `data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt` (lines 6–19)
-**Severity:** 🟡 MEDIUM
-
-The classifier uses a hardcoded English keyword list. Content in Spanish, German, French, Russian, Arabic, etc. will bypass classification entirely. For an app with 26 language locales, this is a significant gap in parental controls.
-
----
-
-## 15. ✅ FIXED — XMLTV Date Format Support Limited
-
-**File:** `data/src/main/java/com/streamvault/data/parser/XmltvParser.kt` (lines 39–43)
-**Severity:** 🟡 MEDIUM
-
-Only 3 date patterns are supported. Real-world XMLTV files use many more formats:
-- `20240315` (date only, no time)
-- `2024-03-15T15:30:00+01:00` (ISO 8601)
-- Timezone offsets with minutes (`+0530`)
-
-Missing formats cause programs to fall through to the epoch-0 fallback.
-
----
-
-## 16. ✅ FIXED — Backup File Has No Integrity Check
-
-**File:** `data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt` (lines 53–101)
-**Severity:** 🟡 MEDIUM
-
-Exported and imported backup files have no checksum, signature, or version validation. A corrupted backup will import corrupted data silently. A backup from an incompatible version could break the database.
-
-**Fix:** Add a CRC32 checksum and a schema version header to backup files.
-
----
-
-## 17. ✅ FIXED — SimpleDateFormat Thread Safety
-
-**File:** `data/src/main/java/com/streamvault/data/parser/XmltvParser.kt` (lines 39–43)
-**Severity:** 🔵 LOW
-
-```kotlin
-private val dateFormats = listOf(
- SimpleDateFormat("yyyyMMddHHmmss Z", Locale.US),
-)
-```
-
-`SimpleDateFormat` is not thread-safe. While each parser instance creates its own, if shared or reused across coroutines, date parsing will silently produce wrong results. Consider using `java.time.DateTimeFormatter`.
-
----
-
-## 18. ✅ FIXED — No Pagination Metadata in Repositories
-
-**File:** `data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt` (lines 150–162)
-**Severity:** 🟡 MEDIUM
-
-Movie/Series pagination queries don't return the total count. The UI has no way to know if more pages exist, so it either loads too many pages or shows no "load more" option.
-
----
-
-## 19. ✅ FIXED — PIN Hashing - RNG Initialization
-
-**File:** `data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt` (lines 28–31)
-**Severity:** 🔵 LOW
-
-```kotlin
-val salt = ByteArray(PIN_SALT_BYTES).also { SecureRandom().nextBytes(it) }
-```
-
-Creating a new `SecureRandom()` instance per call may use a weaker default provider on some older Android versions. Using `SecureRandom.getInstanceStrong()` or caching the instance would be more robust.
-
----
-
-## 20. ✅ N/A — Migration 2→3 Lacks Data Validation
-
-**File:** `data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt` (lines 47–57)
-**Severity:** 🔵 LOW
-
-ALTER TABLE migrations add columns but don't validate whether existing data satisfies any new constraints or defaults that the code expects. This could leave the database in an inconsistent state after upgrade.
-
----
-
-## 21. ✅ FIXED — Unused Extra Attributes in M3U Entries
-
-**File:** `data/src/main/java/com/streamvault/data/parser/M3uParser.kt` (line 40)
-**Severity:** 🔵 LOW
-
-The parser captures unknown M3U attributes into an `extraAttributes` map that is never consumed anywhere. This adds memory overhead per entry for no benefit. Either remove it or document intended future use.
-
----
-
-## 22. ✅ N/A — Xtream Unknown Status Not Logged
-
-**File:** `data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt` (lines 82–90)
-**Severity:** 🔵 LOW
-
-When the Xtream API returns an unknown account status, it maps to `UNKNOWN` without logging. This makes it difficult to diagnose provider compatibility issues.
diff --git a/docs/audit/04_DOMAIN_LAYER.md b/docs/audit/04_DOMAIN_LAYER.md
deleted file mode 100644
index 4b7ad350..00000000
--- a/docs/audit/04_DOMAIN_LAYER.md
+++ /dev/null
@@ -1,267 +0,0 @@
-# 04 — Domain Layer Issues
-
-Architecture, models, use cases, and validation issues.
-
----
-
-## 1. ✅ FIXED — Domain Model Contains UI Logic
-
-**File:** `domain/src/main/java/com/streamvault/domain/model/Program.kt` (lines 15–25)
-**Severity:** 🟠 HIGH
-
-```kotlin
-val progressPercent: Float
- get() {
- if (!isNowPlaying) return 0f
- val now = System.currentTimeMillis() // ← Domain accessing system clock
- if (now < startTime || endTime <= startTime) return 0f
- return ((now - startTime).toFloat() / (endTime - startTime).toFloat()).coerceIn(0f, 1f)
- }
-```
-
-This violates Clean Architecture — the domain model directly calls `System.currentTimeMillis()`. This makes unit testing non-deterministic and couples the domain to the Android runtime.
-
-**Fix:** Move progress calculation to a utility function that accepts `currentTimeMs` as a parameter, or compute in the ViewModel.
-
----
-
-## 2. ⏭️ DEFERRED — Severely Under-Developed Use Case Layer
-
-**File:** `domain/src/main/java/com/streamvault/domain/usecase/`
-**Severity:** 🟠 HIGH
-
-Only **1 use case** exists: `GetCustomCategories`. An IPTV app of this scope should have 15–20+ use cases to properly encapsulate business logic. Without them, business logic is scattered across repositories and ViewModels.
-
-**Missing use cases:**
-| Use Case | Purpose |
-|----------|---------|
-| `GetLiveChannels` | Filter, sort, paginate channels |
-| `GetMovies` / `GetSeries` | Browse content with filters |
-| `SearchContent` | Cross-content-type search |
-| `ToggleFavorite` | Add/remove with validation |
-| `ManageProvider` | Add/update/delete with auth |
-| `GetEpgForChannel` | EPG with timezone handling |
-| `RecordPlaybackHistory` | Track with dedup logic |
-| `ValidateStreamUrl` | URL validation and type detection |
-| `ExportBackup` / `ImportBackup` | Data backup with integrity |
-| `SetParentalControls` | PIN management and category locking |
-
-**Impact:** Business logic duplication, harder to test, harder to maintain.
-
----
-
-## 3. ✅ FIXED (race) / ⚠️ BY DESIGN (persistence) — ParentalControlManager — Race Condition and No Persistence
-
-> See [01_CRITICAL_BLOCKERS.md #11](01_CRITICAL_BLOCKERS.md#11-parentalcontrolmanager-has-race-condition-and-no-persistence)
-
----
-
-## 4. ✅ FIXED — No Data Validation Across Domain Models
-
-**Severity:** 🟠 HIGH
-
-Multiple domain models accept semantically invalid values without validation:
-
-### PlaybackHistory
-```kotlin
-val resumePositionMs: Long = 0 // Could be negative
-val totalDurationMs: Long = 0 // Could be negative
-val watchCount: Int = 1 // Could be 0 or negative
-val seasonNumber: Int? = null // Could be 0 (seasons start at 1)
-val episodeNumber: Int? = null // Could be 0
-```
-No invariant: `resumePositionMs ≤ totalDurationMs`
-
-### Movie
-```kotlin
-val duration: String? = null // Ambiguous format
-val durationSeconds: Int = 0 // Could be negative
-val rating: Float = 0f // No range (0–10? 0–100?)
-```
-Two duration fields with no documented precedence.
-
-### Channel
-```kotlin
-val streamUrl: String = "" // Empty string useless — should be nullable
-val errorCount: Int = 0 // View concern in domain model
-```
-
-### Series / Season / Episode
-```kotlin
-val seasonNumber: Int // No positive validation
-val episodeNumber: Int // No positive validation
-val durationSeconds: Int = 0 // Could be negative
-val airDate: String? = null // Format not specified
-```
-
-### VideoFormat
-```kotlin
-val width: Int // Could be negative
-val height: Int // Could be negative
-val frameRate: Float = 0f // Could be negative
-val bitrate: Int = 0 // Could be negative
-```
-
-### RecordingRequest
-```kotlin
-val scheduledStartMs: Long // Could be in the past
-val scheduledEndMs: Long // Could be ≤ scheduledStartMs
-```
-
-**Fix:** Add `init` blocks with `require()` for invariants, or validate at the creation site (mapper/repository).
-
----
-
-## 5. ✅ FIXED — Repository API Design Issues
-
-### 5a. FavoriteRepository — Ambiguous API
-
-**File:** `domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.kt`
-
-```kotlin
-fun getFavorites(contentType: ContentType? = null): Flow<List<Favorite>>
-fun getAllFavorites(contentType: ContentType): Flow<List<Favorite>>
-```
-
-What's the difference? `getFavorites(null)` vs `getAllFavorites(type)` — the naming is confusing and the behavior overlap is unclear. Consolidate into one method.
-
-### 5b. ChannelRepository — Wrong Return Type
-
-**File:** `domain/src/main/java/com/streamvault/domain/repository/ChannelRepository.kt`
-
-```kotlin
-suspend fun getStreamUrl(channel: Channel): Result<String>
-```
-
-Returns a bare URL string, but `StreamInfo` data class already exists with `url`, `headers`, `userAgent`, and `streamType`. This method should return `Result<StreamInfo>`.
-
-### 5c. EpgRepository — "Now Playing" Returns Lists
-
-**File:** `domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt`
-
-```kotlin
-fun getNowPlayingForChannels(...): Flow<Map<String, List<Program>>>
-```
-
-Why `List<Program>` per channel? "Now playing" should be a single program: `Map<String, Program?>`.
-
-### 5d. MovieRepository — Asymmetric Progress API
-
-```kotlin
-suspend fun updateWatchProgress(movieId: Long, progress: Long)
-// Missing: getWatchProgress()
-```
-
-Can update progress but can't read it back through the repository.
-
-### 5e. ProviderRepository — Callback vs Flow Inconsistency
-
-```kotlin
-suspend fun loginXtream(
- ...,
- onProgress: ((String) -> Unit)? = null // ← Callback
-): Result<Provider>
-```
-
-All other repositories use `Flow` for streaming data. Provider operations use callbacks, breaking the reactive pattern.
-
-### 5f. PlaybackHistoryRepository — No Result Wrapper
-
-```kotlin
-suspend fun recordPlayback(history: PlaybackHistory) // ← No Result<>
-suspend fun updateResumePosition(history: PlaybackHistory) // ← No Result<>
-```
-
-These can fail (database full, constraint violation) but the caller has no way to detect failure.
-
----
-
-## 6. ✅ FIXED — ChannelNormalizer Algorithm Flawed
-
-**File:** `domain/src/main/java/com/streamvault/domain/util/ChannelNormalizer.kt` (lines 12–40)
-**Severity:** 🟡 MEDIUM
-
-The normalizer strips quality tags (HD, FHD, SD, 4K) to group "same" channels together, but:
-
-1. **False merges:** "BBC One HD" and "BBC One SD" map to the same ID — these are distinct channels with different stream qualities the user may want to choose between
-2. **No accent normalization:** "Télé" and "Tele" are treated as different
-3. **Doesn't handle:** bitrate indicators, server names, timezone suffixes
-4. **Numbers mishandled:** "HBO 2" stripped differently than "HBO2"
-
----
-
-## 7. ⚠️ MITIGATED — Category Model Has Redundant Protection Fields
-
-**File:** `domain/src/main/java/com/streamvault/domain/model/Category.kt`
-**Severity:** 🟡 MEDIUM
-
-```kotlin
-data class Category(
- val isAdult: Boolean = false,
- val isUserProtected: Boolean = false // ← Redundant with ParentalControlManager
-)
-```
-
-Parental protection is tracked in two places: the `Category` model and the `ParentalControlManager`. These can get out of sync — one says protected, the other says unlocked.
-
----
-
-## 8. ⏭️ DEFERRED — Missing Domain Features for Premium IPTV
-
-**Severity:** 🟡 MEDIUM
-
-No domain models or repository interfaces exist for:
-
-| Feature | Impact |
-|---------|--------|
-| Subtitle track selection | Users can't select subtitles |
-| Audio track metadata | No language labels in track picker |
-| Adaptive bitrate preferences | No quality control |
-| Watch history search/filter | Can't find previously watched content |
-| Cross-device sync | No resume across devices |
-| Content recommendations | No discovery beyond categories |
-| Provider health/status model | No way to show connection quality |
-
----
-
-## 9. ✅ FIXED — `GetCustomCategories` Swallows Exceptions
-
-**File:** `domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt`
-**Severity:** 🟡 MEDIUM
-
-```kotlin
-}.getOrElse {
- emptyList() // ← Exception silently discarded
-}
-```
-
-If the categories query fails, the UI shows "no categories" with no error indication. The user has no way to know something went wrong.
-
----
-
-## 10. ✅ FIXED — Provider Model Stores Credentials in Plain Data Class
-
-**File:** `domain/src/main/java/com/streamvault/domain/model/Provider.kt`
-**Severity:** 🟡 MEDIUM
-
-```kotlin
-data class Provider(
- val username: String = "",
- val password: String = "",
- val m3uUrl: String = "",
- val epgUrl: String = "",
-)
-```
-
-While credentials are encrypted at the storage layer (`CredentialCrypto`), the domain model carries plaintext credentials in memory. Any memory dump, debug log, or crash report that serializes this object will expose them.
-
-**Mitigation:** The `toString()` auto-generated by `data class` will include username and password in any log statement. Consider overriding `toString()` to redact sensitive fields.
-
----
-
-## 11. ✅ FIXED — `StreamInfo` Model Exists but Underutilized
-
-**File:** `domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt`
-**Severity:** 🔵 LOW
-
-A comprehensive `StreamInfo` data class exists with `url`, `headers`, `userAgent`, `streamType`, etc. But `ChannelRepository.getStreamUrl()` returns `Result<String>` instead of `Result<StreamInfo>`, bypassing all the rich metadata.
diff --git a/docs/audit/04_MISSING_FEATURES_COMPLETENESS.md b/docs/audit/04_MISSING_FEATURES_COMPLETENESS.md
new file mode 100644
index 00000000..f1c42092
--- /dev/null
+++ b/docs/audit/04_MISSING_FEATURES_COMPLETENESS.md
@@ -0,0 +1,271 @@
+# StreamVault Pre-Release Audit: Missing Features & Completeness
+
+> **Audit Date:** March 17, 2026
+> **Focus:** Missing functionality, partial implementations, feature gaps for a premium IPTV player
+
+---
+
+## 1. Player Module — Missing Premium Features
+
+### 1.1 No Quality/Bitrate Selection [HIGH]
+
+**Current:** Player uses Media3's default adaptive bitrate selection with no user control.
+**Expected:** Premium IPTV players allow users to:
+- View available quality options (Auto, 1080p, 720p, 480p, etc.)
+- Lock to a specific quality
+- Set quality preferences per network type (WiFi vs Ethernet)
+
+**Implementation Path:** Use `DefaultTrackSelector.parameters.setMaxVideoSize()` with user preference. The `constrainResolutionForMultiView` boolean already demonstrates this capability.
+
+### 1.2 No Playback Speed Control [MEDIUM]
+
+**Current:** No speed controls exposed.
+**Expected:** 0.5x, 0.75x, 1x, 1.25x, 1.5x, 2x for VOD content.
+**Implementation Path:** `ExoPlayer.setPlaybackParameters(PlaybackParameters(speed))` — trivial to add.
+
+### 1.3 No Audio Track Language Auto-Selection [MEDIUM]
+
+**Current:** Audio track can be selected manually but doesn't default to user's locale.
+**Expected:** Auto-select audio track matching device/app language.
+**Implementation Path:** Use `DefaultTrackSelector.Parameters.setPreferredAudioLanguage()`.
+
+### 1.4 No Subtitle Styling [LOW]
+
+**Current:** Subtitle track can be toggled but styling (size, color, background) is not configurable.
+**Expected:** Standard TV apps allow subtitle customization per accessibility requirements.
+
+### 1.5 No Stream Failover [MEDIUM]
+
+**Current:** `Channel.alternativeStreams` exists as `List<String>` but the player doesn't use it.
+**Expected:** When primary stream fails, automatically try alternative stream URLs.
+**Implementation Path:** On `PlayerError.NetworkError`, try next URL from `alternativeStreams` before showing error.
+
+### 1.6 No Seek Thumbnails / Trick Play [LOW]
+
+**Current:** Seek bar shows position but no visual preview.
+**Expected:** Premium players show thumbnails while scrubbing for VOD content.
+
+### 1.7 No DRM Support [LOW for IPTV]
+
+**Current:** No Widevine, PlayReady, or ClearKey DRM scaffolding.
+**Expected:** Some premium IPTV providers use DRM-protected streams.
+**Note:** Most IPTV providers don't use DRM. Lower priority unless targeting premium content providers.
+
+---
+
+## 2. Domain Module — Severely Underdeveloped Use Case Layer
+
+### 2.1 Only 1 Use Case Exists [HIGH]
+
+**Current:** `GetCustomCategories` is the only use case in the entire domain layer.
+**Expected:** A well-architected app should have 15-25+ use cases encapsulating business logic.
+
+**Critical missing use cases:**
+
+| Use Case | Purpose |
+|----------|---------|
+| `SearchContent` | Cross-provider, cross-content-type search |
+| `GetContinueWatching` | Smart resume list with series awareness |
+| `MarkAsWatched` | Explicit watched marking with progress threshold |
+| `ValidateAndAddProvider` | Full validation → login → sync orchestration |
+| `SyncProvider` | Orchestrated sync with progress and error handling |
+| `GetRecommendations` | Based on watch history and favorites |
+| `ScheduleRecording` | With conflict detection and storage checks |
+| `ExportBackup` / `ImportBackup` | With encryption and conflict resolution |
+| `UnlockParentalCategory` | PIN validation with attempt tracking |
+
+**Impact:** Business logic is spread across ViewModels and repositories instead of being centralized in testable use cases.
+
+### 2.2 Domain Models Missing Fields [MEDIUM]
+
+| Model | Missing Field | Purpose |
+|-------|--------------|---------|
+| `Program` | `rating` | Content rating (PG-13, R, etc.) |
+| `Program` | `imageUrl` | Program thumbnail for EPG grid |
+| `Program` | `genre` / `category` | EPG filtering by genre |
+| `Channel` | `qualityOptions` | Available stream qualities |
+| `StreamInfo` | `expirationTime` | Token-based stream URL expiry |
+| `StreamInfo` | `drmInfo` | DRM license/config |
+| `PlaybackHistory` | `watchedStatus` | Explicit watched vs auto-detected |
+| `Provider` | `apiVersion` | Xtream API version compatibility |
+
+### 2.3 Backup Data Incomplete [MEDIUM]
+
+**File:** `domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt`
+
+`BackupData` is missing:
+- Parental control PIN (critical — lost on restore)
+- Recording schedules
+- Blocked channels/categories
+- Playback preferences (quality, subtitle language)
+
+### 2.4 Repository Interface Gaps
+
+**Missing methods across repositories:**
+
+| Repository | Missing Method | Purpose |
+|-----------|---------------|---------|
+| ChannelRepository | `getChannelsByNumber()` | EPG guides organize by channel number |
+| ChannelRepository | `getChannelsWithoutErrors()` | Skip problematic streams |
+| EpgRepository | `searchPrograms()` | Find programs across all channels |
+| EpgRepository | `getProgramsByCategory()` | Category-based EPG browsing |
+| MovieRepository | `getRecommendations()` | Based on watch history |
+| MovieRepository | `getRelatedContent()` | Similar genre/cast |
+| PlaybackHistoryRepository | `markAsWatched()` | Explicit watched marking |
+| PlaybackHistoryRepository | `getUnwatchedCount()` | For series tracking |
+| LibraryBrowseQuery | `sortBy` field | Name, date, rating, watch count |
+| LibraryBrowseQuery | `filterBy` field | Unwatched, incomplete, language |
+| LibraryBrowseQuery | `searchQuery` field | Combined search + browse |
+
+---
+
+## 3. Data Module — Implementation Gaps
+
+### 3.1 Watch Progress Inconsistency [MEDIUM]
+
+**Description:**
+Movie watch progress is duplicated between two locations:
+- `movies.watch_progress` column (updated via `movieDao.updateWatchProgress()`)
+- `playback_history.resume_position_ms` (updated during playback)
+
+These can get out of sync. Episode watch progress in particular may show `watch_progress=0` in the episodes table while `playback_history` has a valid resume position.
+
+**Action:** Single source of truth — either use playback_history exclusively, or add a sync mechanism.
+
+### 3.2 Stale Favorite Cleanup Not Automated [MEDIUM]
+
+**Description:**
+`FavoriteRepositoryImpl` has methods to clean up favorites for deleted content:
+- `deleteMissingLiveFavorites()`
+- `deleteMissingMovieFavorites()`
+- `deleteMissingSeriesFavorites()`
+
+But these are **never called** by any visible code path. The `SyncWorker` → `DatabaseMaintenanceManager` chain doesn't seem to invoke them.
+
+**Impact:** Favorites for deleted channels/movies/series remain in the database forever as orphaned entries.
+
+**Action:** Wire cleanup methods into the maintenance worker or post-sync hook.
+
+### 3.3 Xtream Expiration Date — Limited Format Support [LOW]
+
+**File:** `data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt`
+
+Only 2 date formats are tried (`yyyy-MM-dd HH:mm:ss`, `yyyy-MM-dd`). Some Xtream providers use additional formats. Also missing timezone handling (assumes local time instead of UTC).
+
+### 3.4 Search Results Not Ranked [LOW]
+
+**Description:**
+FTS4 search queries return results in arbitrary order. Room FTS4 doesn't provide ranking by default.
+
+**Impact:** Search for "Sports" may show "Sports Bar" before "Sports Channel" with no relevance ordering.
+
+**Recommendation:**
+Consider adding a simple relevance heuristic (exact match first, prefix match second, contains match third).
+
+---
+
+## 4. Test Coverage Gaps
+
+### 4.1 Current Test Inventory
+
+| Module | Unit Tests | Android Tests | Coverage Estimate |
+|--------|-----------|---------------|-------------------|
+| **domain** | 3 files (25 tests) | 0 | ~10% |
+| **data** | 6 files | 3 files | ~25% |
+| **app** | 4 files | 4 files | ~15% |
+| **player** | 1 file (18 tests) | 0 | ~20% |
+| **TOTAL** | **14 files** | **7 files** | **~15-20%** |
+
+### 4.2 Critical Missing Tests
+
+| Test Category | What's Missing | Priority |
+|--------------|----------------|----------|
+| **Security** | CredentialCrypto encrypt/decrypt, UrlSecurityPolicy validation, ProviderInputSanitizer bounds | HIGH |
+| **Database Migrations** | Full v1→v13 data integrity verification | HIGH |
+| **Error Paths** | Network failure handling, malformed data recovery, timeout behavior | HIGH |
+| **Player Engine** | Playback lifecycle, error recovery, audio focus, track selection | MEDIUM |
+| **ViewModels** | MoviesViewModel, SeriesViewModel, SettingsViewModel, PlayerViewModel | MEDIUM |
+| **Repositories** | Full CRUD operations with edge cases | MEDIUM |
+| **Integration** | Provider login → sync → display → playback end-to-end flow | LOW |
+| **UI/Golden** | More composable snapshot tests for visual regression | LOW |
+
+### 4.3 CI/CD Test Pipeline Issues
+
+- `--continue` flag masks individual test failures
+- No code coverage reporting (Jacoco)
+- No release build testing
+- No ProGuard/R8 validation for release APK
+
+---
+
+## 5. Recording System — Interface vs Implementation Gaps
+
+### 5.1 RecordingManager Implementation Exists ✅
+
+The `RecordingManagerImpl` is fully implemented with:
+- Manual recording start/stop
+- Scheduled recording
+- Storage state monitoring
+- Active job management
+
+### 5.2 Missing Recording Features [LOW]
+
+| Feature | Status |
+|---------|--------|
+| Recurring recordings (daily/weekly) | ❌ Not implemented |
+| Recording conflict detection | ❌ Not implemented |
+| Automatic storage cleanup | ❌ Not implemented |
+| Pause/resume recording | ❌ Not implemented |
+| Series recording rules | ❌ Not implemented |
+
+---
+
+## 6. Backup System — Interface vs Implementation Gaps
+
+### 6.1 BackupManager Implementation Exists ✅
+
+The `BackupManagerImpl` is fully implemented with:
+- Export with checksum verification
+- Import with conflict detection
+- Version handling
+
+### 6.2 Missing Backup Features [LOW]
+
+| Feature | Status |
+|---------|--------|
+| Encrypted backup | ❌ Not implemented |
+| Cloud backup (Google Drive) | ❌ Not implemented |
+| Automatic scheduled backup | ❌ Not implemented |
+| Selective restore (only favorites, only providers, etc.) | ❌ Not implemented |
+
+---
+
+## 7. Localization Completeness
+
+**Status:** ✅ Well-implemented — 25+ languages supported via translation scripts.
+
+All user-facing strings use `stringResource(R.string.*)`. Only non-localizable symbols (`+`, `!`, `•`) are hardcoded.
+
+**Note:** RTL support (Hebrew, Arabic) was implemented in Phase 5 with proper mirroring.
+
+---
+
+## 8. Summary: Feature Readiness Matrix
+
+| Feature Area | Readiness | Blocking? |
+|-------------|-----------|-----------|
+| Live TV Playback | 90% | No |
+| VOD (Movies/Series) | 80% | **Yes** — dead code in category browsing |
+| EPG Guide | 85% | No |
+| Provider Management | 90% | No |
+| Favorites & Groups | 85% | No |
+| Parental Controls | 70% | **Yes** — in-memory only |
+| Search | 75% | No |
+| Multi-View | 80% | No |
+| Settings | 85% | No |
+| Player Controls | 75% | No — but missing quality selection |
+| Recording | 60% | No — functional but basic |
+| Backup/Restore | 70% | No — functional but missing PIN backup |
+| Android TV Platform | 50% | **Yes** — missing Watch Next, voice search |
+| Accessibility | 60% | No — functional but gaps |
+| Test Coverage | 20% | **Yes** — too low for production confidence |
diff --git a/docs/audit/05_UI_UX.md b/docs/audit/05_UI_UX.md
deleted file mode 100644
index 05282c65..00000000
--- a/docs/audit/05_UI_UX.md
+++ /dev/null
@@ -1,321 +0,0 @@
-# 05 — UI & UX Issues
-
-Screens, navigation, accessibility, focus management, and presentation issues.
-
----
-
-## 1. ✅ FIXED — D-Pad Focus Trap Scenarios
-
-**Severity:** 🔴 CRITICAL
-
-Multiple screens have scenarios where the D-Pad focus can become trapped or lost:
-
-### PlayerScreen — Overlay Focus Loss
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt` (lines 280–290)
-
-Complex nested overlay state (channel list, category list, EPG, channel info, track selection, program history, split dialog, diagnostics) makes it easy for focus to become lost when overlays are dismissed. No "default focus" fallback exists when the target of `FocusRequester.requestFocus()` is no longer in the composition.
-
-### HomeScreen — Category-Channel Focus Hand-off
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt` (lines 350–400)
-
-```kotlin
-var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }
-var shouldRestoreChannelFocus by remember { mutableStateOf(false) }
-```
-
-When a user selects a category, focus moves to the first channel. Pressing D-Pad left should return to the category sidebar. But if the category list has scrolled, the target category may not be visible, and `requestFocus()` fails silently.
-
-### MultiViewScreen — Grid Escape
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt` (lines 120–140)
-
-If the user navigates out of the 2×2 player grid, there's no safe path back in. No focus restoration is attempted.
-
-### Modal Dialogs — Post-Delete Focus
-**PinDialog** and **CategoryOptionsDialog** can dismiss after deleting the underlying content (e.g., deleting a category group). Focus restoration tries to focus the deleted item — fails silently.
-
----
-
-## 2. ✅ FIXED — Missing Error State UI on Content Screens
-
-**Severity:** 🔴 CRITICAL
-
-### MoviesScreen
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt` (lines 90–110)
-
-```kotlin
-if (uiState.isLoading) { /* loading */ }
-else if (uiState.moviesByCategory.isEmpty()) { /* empty */ }
-else { /* content */ }
-// ← No error state branch
-```
-
-If the API call fails, the user sees a blank screen with no retry option. Same issue in **SeriesScreen**.
-
-### HomeScreen
-No error state if category load fails. No timeout indicator for slow EPG loads. No skeleton loading for the category sidebar.
-
-### FavoritesScreen
-No UI for:
-- Empty favorites (blank screen)
-- All items filtered out by parental controls
-- Favorite content that became unavailable
-
-### SearchScreen
-When query is under 2 characters, shows blank instead of a search hint or suggestion.
-
----
-
-## 3. ✅ FIXED — Accessibility — Missing Content Descriptions
-
-**Severity:** 🔴 CRITICAL
-
-### FocusableCard — No Semantics
-**File:** `app/src/main/java/com/streamvault/app/ui/components/Cards.kt`
-
-The primary card component used throughout the app has no `contentDescription` parameter and no `Modifier.semantics` block. TalkBack announces "button" with no context for every card.
-
-### ChannelCard — Image Not Labeled
-Channel logos have no `contentDescription`. TalkBack cannot announce what channel is focused.
-
-### CategoryRow — No Heading Semantics
-```kotlin
-Text(text = title, style = MaterialTheme.typography.titleMedium)
-```
-Missing `Modifier.semantics { heading() }` — TalkBack won't navigate by section headings.
-
-### CustomKeyboard — Keys Not Announced
-```kotlin
-KeyboardButton(text = key, onClick = { onKeyPress(key) })
-```
-TalkBack says "button" for every key instead of announcing the letter.
-
-### PinDialog — No Input Feedback
-No announcement of current PIN length, no feedback on invalid PIN.
-
-### Player Controls — No State Announcements
-Control buttons lack descriptions. No announcement when playback state changes (play/pause/buffering).
-
----
-
-## 4. ✅ N/A — RTL Layout Not Fully Mirrored
-
-**Severity:** 🟠 HIGH
-
-While `MainActivity` correctly sets `LayoutDirection.Rtl` based on locale, several components don't respond:
-
-### HomeScreen Sidebar
-```kotlin
-Row(modifier = Modifier.fillMaxSize()) {
- Column(modifier = Modifier.width(280.dp)) { /* sidebar - always left */ }
- Column(modifier = Modifier.weight(1f)) { /* content - always right */ }
-}
-```
-In RTL locales (Arabic, Hebrew), the sidebar should be on the right. Currently hardcoded to the left.
-
-### SearchInput Icon
-```kotlin
-Icon(imageVector = Icons.Default.Search, modifier = Modifier.padding(end = 6.dp))
-```
-Search icon is always on the left side, should be on the right in RTL.
-
-### CategoryRow
-Row header (title on left, "See All" on right) doesn't flip in RTL.
-
----
-
-## 5. ✅ FIXED — ViewModel Memory Leaks — Jobs Not Cancelled
-
-> See [01_CRITICAL_BLOCKERS.md #8](01_CRITICAL_BLOCKERS.md#8-viewmodels-never-cancel-background-jobs--memory-leaks)
-
----
-
-## 6. ✅ FIXED — LazyRow/LazyColumn Missing Stable Keys
-
-**Severity:** 🟠 HIGH
-
-### CategoryRow
-**File:** `app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt` (lines 30–50)
-
-```kotlin
-LazyRow(...) {
- items(items = items, key = { it.hashCode() }) { // ← WRONG
- itemContent(it)
- }
-}
-```
-
-`hashCode()` is not a stable unique key. On data refresh, even identical items get different hash codes → entire row re-composes, causing visible flicker and dropped frames.
-
-**Fix:** Use item's stable ID: `key = { it.id }`
-
-### HomeScreen Channel Grid
-```kotlin
-LazyVerticalGrid(columns = GridCells.Adaptive(180.dp)) {
- items(channels) { channel ->
- ChannelCard(channel = channel)
- }
-}
-```
-No `key` specified — any data change causes full re-composition of the grid.
-
-### FavoritesScreen
-No keys during reorder operations → full re-compose on every reorder step.
-
----
-
-## 7. ✅ FIXED — Hardcoded English Strings in UI Code
-
-**Severity:** 🟠 HIGH
-
-| File | String | Should Be |
-|------|--------|-----------|
-| `HomeScreen.kt:1119` | `"Save"` | `stringResource(R.string.action_save)` |
-| `HomeScreen.kt:1128` | `"Cancel"` | `stringResource(R.string.action_cancel)` |
-| `HomeScreen.kt:405,1190` | `"SPLIT"`, `"MOVE"` | `stringResource(R.string.action_split)` |
-| `ReorderTopBar.kt:82` | `"Cancel"` | `stringResource(R.string.action_cancel)` |
-| `CustomKeyboard.kt:62` | `"Delete"` | `stringResource(R.string.action_delete)` |
-| `SettingsViewModel.kt:195+` | `"Watch history and recents cleared"` | `R.string.settings_cleared_history` |
-| `SettingsViewModel.kt` | `"PIN changed successfully"` | `R.string.settings_pin_changed` |
-| `PlayerViewModel.kt:210+` | `"The stream stopped responding..."` | `R.string.player_error_*` |
-
-These strings are visible to users and will appear in English regardless of locale, breaking the localization for 25 non-English languages.
-
----
-
-## 8. ✅ FIXED — Player Error Recovery Not Visible to User
-
-**Severity:** 🟠 HIGH
-
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt`
-
-When playback errors occur:
-1. Error is silently logged
-2. Decoder mode may be silently switched (software fallback)
-3. Channel may be silently changed (stall recovery)
-4. User notification (`PlayerNoticeBanner`) may not be visible if controls are hidden
-
-Users have no idea why their stream quality changed, why the channel switched, or what recovery was attempted. A premium app should provide clear, non-intrusive feedback.
-
----
-
-## 9. ✅ FIXED — DashboardScreen Missing States
-
-**Severity:** 🟡 MEDIUM
-
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt` (lines 90–120)
-
-- No indicator for provider sync in progress
-- No warning banners for provider sync errors
-- No "coming soon" placeholder for empty content shelves
-- No last-sync-time indicator
-
----
-
-## 10. ✅ FIXED — String Concatenation Pattern Breaks RTL
-
-**Severity:** 🟡 MEDIUM
-
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt` (lines 718–719)
-
-```kotlin
-stringResource(R.string.favorites_continue_short) + " ${summary.continueWatchingCount}"
-```
-
-String concatenation doesn't respect RTL text direction. In Arabic, the number should appear on the left, but concatenation always puts it on the right. Use parameterized strings: `"Continue (%1$d)"`.
-
----
-
-## 11. ✅ FIXED — HomeScreen Back Handler Missing
-
-**Severity:** 🟡 MEDIUM
-
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt`
-
-No `BackHandler` composable. When user presses back:
-- If channel list overlay is open → should close overlay first
-- If in reorder mode → should exit reorder first
-- If sidebar is focused → should move to channel grid
-- Otherwise → navigate back
-
-Currently relies on system default back behavior which may cause premature exit from the screen.
-
----
-
-## 12. ✅ FIXED — Focus Restoration Uses `remember` Instead of `rememberSaveable`
-
-**Severity:** 🟡 MEDIUM
-
-```kotlin
-var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }
-```
-
-Using `remember` means focus state is lost on configuration changes (language change, screen rotation). Should be `rememberSaveable` for robust focus restoration.
-
----
-
-## 13. ✅ FIXED — No Responsive Layout for Sidebar Width
-
-**Severity:** 🟡 MEDIUM
-
-**File:** `app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt` (lines 220–280)
-
-```kotlin
-Column(modifier = Modifier.width(280.dp)) { /* sidebar */ }
-```
-
-Hardcoded 280dp sidebar width. On large TV screens (65"+) this is too narrow; on smaller screens or tablets it may be too wide. Should scale based on screen dimensions.
-
----
-
-## 14. ✅ FIXED — No Animation on Category/Content Transitions
-
-**Severity:** 🟡 MEDIUM
-
-When selecting a category in HomeScreen, the channel grid content changes instantly with no animation. For premium polish, a crossfade or slide transition would create smoother experience. Player controls do have proper `AnimatedVisibility` — this pattern should be extended to content screens.
-
----
-
-## 15. ✅ FIXED — Missing Numeric Channel Switching in All Contexts
-
-**Severity:** 🟡 MEDIUM
-
-Quick channel switching via numeric pad (0-9) exists in the player but may not work consistently:
-- Works during full-screen playback
-- Missing during overlay (EPG, channel list, category list)
-- Not available from HomeScreen for direct channel entry
-
----
-
-## 16. ✅ FIXED — No Loading Skeleton for Category Sidebar
-
-**Severity:** 🔵 LOW
-
-Channel grid has skeleton loading, but the category sidebar shows nothing while loading. Premium apps show shimmer/skeleton placeholders for all loading sections.
-
----
-
-## 17. ⚠️ MITIGATED — No Wrapping Navigation in Horizontal Lists
-
-**Severity:** 🔵 LOW
-
-When the user reaches the last item in a LazyRow and presses D-Pad right, nothing happens. Premium TV apps typically wrap to the first item or provide a subtle "end of list" indicator.
-
----
-
-## 18. ✅ FIXED — Search Needs Minimum Query Length Hint
-
-**Severity:** 🔵 LOW
-
-```kotlin
-if (query.length < 2) { /* blank UI */ }
-```
-
-When the user types a single character, show a hint: "Type at least 2 characters to search" instead of showing nothing.
-
----
-
-## 19. ✅ FIXED — Multi-View Has No Slot Status Indicators
-
-**Severity:** 🔵 LOW
-
-In multi-view mode (4 players), there's no per-slot buffering indicator, no per-slot error state, and no way to see which slot is currently active without the border highlight.
diff --git a/docs/audit/06_SECURITY.md b/docs/audit/06_SECURITY.md
deleted file mode 100644
index e9629d0b..00000000
--- a/docs/audit/06_SECURITY.md
+++ /dev/null
@@ -1,121 +0,0 @@
-# 06 — Security Issues
-
-Credential handling, network security, file access, and data protection.
-
----
-
-## Overall Security Posture: ✅ GOOD with exceptions
-
-StreamVault's security foundation is solid — credentials are encrypted with AES-GCM via Android Keystore, cleartext traffic is disabled, permissions are minimal, and there are no WebViews or exported services. The issues below are the remaining gaps.
-
----
-
-## 1. ⚠️ FALSE POSITIVE — `file://` URI Exposure
-
-> See [01_CRITICAL_BLOCKERS.md #15](01_CRITICAL_BLOCKERS.md#15-file-uri-exposure)
-
----
-
-## 2. ✅ FIXED — Credentials Can Leak Into Crash Logs
-
-> See [01_CRITICAL_BLOCKERS.md #9](01_CRITICAL_BLOCKERS.md#9-credentials-can-leak-into-crash-logs)
-
----
-
-## 3. ✅ FIXED — M3U URL Injection Vectors
-
-**File:** `data/src/main/java/com/streamvault/data/parser/M3uParser.kt`
-**Severity:** 🟠 HIGH
-
-While `UrlSecurityPolicy.isAllowedImportedUrl()` exists, the following attack vectors are not fully mitigated:
-
-| Vector | Risk |
-|--------|------|
-| CRLF injection (`%0D%0A`) | HTTP request smuggling if URLs are used in raw HTTP |
-| `file:///` protocol entries | Local filesystem reads |
-| `javascript:` / `data:` URIs | XSS if ever rendered in WebView (currently no WebView) |
-| Extremely long URLs (>8KB) | Buffer overflow in HTTP clients |
-
-**Fix:** After parsing, validate all entry URLs with `URI.create()` and whitelist only `http`/`https` schemes.
-
----
-
-## 4. ✅ FIXED — Provider Credentials in Domain Model `toString()`
-
-**File:** `domain/src/main/java/com/streamvault/domain/model/Provider.kt`
-**Severity:** 🟡 MEDIUM
-
-```kotlin
-data class Provider(
- val username: String = "",
- val password: String = "",
- ...
-)
-```
-
-Kotlin `data class` auto-generates `toString()` that includes all fields. Any log statement, debug output, or crash report that calls `provider.toString()` will expose credentials in plaintext.
-
-**Fix:** Override `toString()`:
-```kotlin
-override fun toString(): String = "Provider(id=$id, name=$name, type=$type)"
-```
-
----
-
-## 5. ✅ FIXED — M3U Input Not Length-Bounded
-
-> See [01_CRITICAL_BLOCKERS.md #14](01_CRITICAL_BLOCKERS.md#14-m3u-input-not-length-bounded-dos-vector)
-
----
-
-## 6. ⏭️ N/A — No Certificate Pinning
-
-**Severity:** 🟡 MEDIUM
-
-No SSL/TLS certificate pinning is implemented for API communications. This is typical for IPTV apps (which connect to diverse user-provided servers), but if there are any first-party API endpoints (analytics, updates, license checks), they should use certificate pinning.
-
-**Note:** Certificate pinning for user-provided IPTV servers is impractical since each provider has different certificates. This is acceptable.
-
----
-
-## 7. ✅ FIXED — Backup File Not Encrypted
-
-**File:** `data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt`
-**Severity:** 🟡 MEDIUM
-
-Exported backup files contain:
-- Provider configurations (server URLs, potentially with embedded credentials in M3U URLs)
-- Favorites and watch history
-- Settings
-
-These are stored as plain JSON. If a user shares the backup file, their IPTV provider credentials could be exposed.
-
-**Fix:** Either encrypt the backup file or strip credentials before export, with an option to re-enter them on import.
-
----
-
-## 8. ✅ N/A — PIN Stored as Hash Without Iteration Count
-
-**File:** `data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt`
-**Severity:** 🔵 LOW
-
-The PIN hash uses a single-round hash (assumed from the code pattern). For a 4-digit PIN (only 10,000 possible values), even SHA-256 with salt is brute-forceable in milliseconds.
-
-**Fix:** Use PBKDF2 with high iterations or bcrypt. A 4-digit PIN should have at least 100,000 iterations of PBKDF2 to add meaningful delay.
-
-**Mitigation:** This is a parental control PIN, not a financial credential. The threat model is a child trying to bypass it, not a sophisticated attacker — so the current implementation is acceptable but could be stronger.
-
----
-
-## ✅ Strong Security Practices (No Action Needed)
-
-| Practice | Status |
-|----------|--------|
-| **AES-GCM encryption via Keystore** | ✅ Properly implemented in CredentialCrypto |
-| **Cleartext traffic disabled** | ✅ `network_security_config.xml` enforces HTTPS |
-| **Minimal permissions** | ✅ Only INTERNET + ACCESS_NETWORK_STATE |
-| **No exported services** | ✅ Only MainActivity exported with LAUNCHER filter |
-| **No WebView** | ✅ Zero WebView attack surface |
-| **No clipboard access** | ✅ Credentials never in clipboard |
-| **No hardcoded secrets** | ✅ No API keys, tokens, or passwords in source |
-| **Content provider safety** | ✅ Only AndroidX startup provider (framework-managed) |
diff --git a/docs/audit/07_TESTING_LOCALIZATION.md b/docs/audit/07_TESTING_LOCALIZATION.md
deleted file mode 100644
index aaa848a9..00000000
--- a/docs/audit/07_TESTING_LOCALIZATION.md
+++ /dev/null
@@ -1,163 +0,0 @@
-# 07 — Testing & Localization Issues
-
-Test coverage, test quality, translations, and resource issues.
-
----
-
-## Testing
-
-### 1. ⚠️ MITIGATED — Domain & Player Modules Have Zero Test Coverage
-
-**Severity:** 🔴 CRITICAL
-
-| Module | Unit Tests | Instrumented Tests | Status |
-|--------|-----------|-------------------|--------|
-| `:app` | 4 files | 6 files | ⚠️ Partial |
-| `:data` | 7 files | 3 files | ⚠️ Partial |
-| `:domain` | **0 files** | **0 files** | ❌ None |
-| `:player` | **0 files** | **0 files** | ❌ None |
-
-**Impact:** The most critical modules — business logic (domain) and media playback (player) — have zero automated tests. All bugs are found only through manual testing.
-
-**Untested critical code:**
-- `ParentalControlManager` (has known race condition — no test validates this)
-- `GetCustomCategories` use case (untested business logic)
-- `Media3PlayerEngine` (decoder switching, track selection, error recovery)
-- `StreamTypeDetector` (URL-based stream type detection)
-- All domain model invariants
-- `ChannelNormalizer` algorithm
-
----
-
-### 2. ⏭️ DEFERRED — Existing Tests Are Surface-Level
-
-**Severity:** 🟠 HIGH
-
-**App module ViewModels:**
-- `HomeViewModelTest` — Only tests basic state initialization, not user interactions
-- `EpgViewModelTest` — Minimal coverage of EPG state machine
-- `SearchViewModelTest` — Tests search query update, not search results
-
-**Missing ViewModel tests:**
-- `SettingsViewModel` (contains hardcoded strings, PIN management, sync operations)
-- `MoviesViewModel` / `SeriesViewModel` (pagination, filtering)
-- `PlayerViewModel` (error recovery, channel switching, multi-view)
-- `MultiViewViewModel` (slot management, focus, engine lifecycle)
-
----
-
-### 3. ⏭️ DEFERRED — No Integration Tests for Critical Flows
-
-**Severity:** 🟠 HIGH
-
-Missing end-to-end scenarios:
-- Provider setup → sync → channel display flow
-- M3U import → parse → store → display flow
-- Parental control PIN → lock → unlock → verify flow
-- Backup export → corrupt → import → verify failure handling
-- Provider delete → verify cascade cleanup flow
-- EPG sync → timezone handling → program display
-
----
-
-### 4. ⏭️ DEFERRED — No Performance/Stress Tests
-
-**Severity:** 🟡 MEDIUM
-
-No tests for:
-- Large M3U files (50,000+ channels)
-- Large EPG files (500MB+)
-- Rapid channel switching (100 switches in 30 seconds)
-- Low-memory conditions
-- Concurrent sync for multiple providers
-
----
-
-### 5. ✅ POSITIVE — Data Layer Tests Have Good Patterns
-
-**Severity:** ✅ POSITIVE
-
-- `SyncManagerTest` — Tests state machine transitions with fakes
-- `M3uParserTest` — Covers edge cases and assertions
-- `EntityMappersTest` — Validates round-trip mapping
-- `ProgramDaoTest` — Room integration tests
-
-These serve as good templates for expanding coverage.
-
----
-
-## Localization
-
-### 3. ✅ FIXED — Hardcoded English Strings in Code
-
-> See [05_UI_UX.md #7](05_UI_UX.md#7-hardcoded-english-strings-in-ui-code)
-
-**Count:** 15+ hardcoded English strings across ViewModels and Composables that will appear un-translated for 25 non-English locales.
-
----
-
-### 4. ✅ POSITIVE — 26 Languages Supported — Coverage Appears Good
-
-**Severity:** ✅ POSITIVE
-
-Supported locales:
-`ar`, `cs`, `da`, `de`, `el`, `es`, `fi`, `fr`, `hu`, `in`, `it`, `iw`, `ja`, `ko`, `nb`, `nl`, `pl`, `pt`, `ro`, `ru`, `sv`, `tr`, `uk`, `vi`, `zh`
-
-Spot-check of key strings across English, Spanish, French, and German shows proper translations. Parameterized strings use correct `%1$s` / `%1$d` format markers.
-
----
-
-### 5. ✅ FIXED — String Concatenation Breaks RTL
-
-> See [05_UI_UX.md #10](05_UI_UX.md#10-string-concatenation-pattern-breaks-rtl)
-
----
-
-## Resources
-
-### 6. ⚠️ MITIGATED — App Icon Missing Density Variants
-
-**Severity:** 🟠 HIGH
-
-| Density | Resolution | Present? |
-|---------|-----------|----------|
-| ldpi | 36×36 | ❌ |
-| mdpi | 48×48 | ❌ |
-| hdpi | 72×72 | ❌ |
-| xhdpi | 96×96 | ❌ |
-| xxhdpi | 144×144 | ❌ |
-| xxxhdpi | 192×192 | ✅ |
-
-Only the highest density icon is provided. On lower-density screens, the icon is downscaled from xxxhdpi, resulting in artifacts and an unprofessional appearance. While Android TV devices are typically hdpi/xhdpi, the Play Store listing shows the icon at various sizes.
-
-**Fix:** Use Android Studio's Image Asset Studio to generate all density variants from a source SVG/PNG.
-
-**Note:** The adaptive icon (`mipmap-anydpi-v26/ic_launcher.xml`) is properly configured with foreground/background separation, which is good.
-
----
-
-### 7. ✅ FIXED — Missing ProGuard Rules File
-
-> See [01_CRITICAL_BLOCKERS.md #1](01_CRITICAL_BLOCKERS.md#1-missing-proguard-rulespro--release-builds-will-fail)
-
----
-
-### 8. ✅ FIXED — No Release Signing Configuration
-
-> See [01_CRITICAL_BLOCKERS.md #10](01_CRITICAL_BLOCKERS.md#10-no-signing-configuration-for-release)
-
----
-
-## Test Coverage Improvement Priority
-
-| Priority | Area | Estimated Tests | Impact |
-|----------|------|----------------|--------|
-| 🔴 P0 | `Media3PlayerEngine` | 15–20 tests | Prevents playback regressions |
-| 🔴 P0 | `ParentalControlManager` | 10–12 tests | Verifies thread safety, persistence |
-| 🔴 P0 | `StreamTypeDetector` | 10 tests | Validates all URL patterns |
-| 🟠 P1 | `ChannelNormalizer` | 8–10 tests | Validates grouping algorithm |
-| 🟠 P1 | Domain model validation | 15–20 tests | Ensures data integrity |
-| 🟠 P1 | `PlayerViewModel` | 12–15 tests | Error recovery, channel switching |
-| 🟠 P1 | `SettingsViewModel` | 8–10 tests | PIN, sync, export |
-| 🟡 P2 | Navigation integration | 5–8 tests | Back stack, deep links |
-| 🟡 P2 | Backup/restore | 5–8 tests | Data integrity |
diff --git a/docs/audit/PRE_PUBLISH_AUDIT.md b/docs/audit/PRE_PUBLISH_AUDIT.md
deleted file mode 100644
index 8a914c2d..00000000
--- a/docs/audit/PRE_PUBLISH_AUDIT.md
+++ /dev/null
@@ -1,114 +0,0 @@
-# StreamVault — Pre-Publish Comprehensive Audit
-
-**Date:** March 15, 2026
-**Branch:** `review/pre-publish-audit-2026-03-15`
-**Auditor:** Automated Code Audit
-**Verdict:** ✅ READY — All critical blockers resolved across 25 fix batches
-
----
-
-## Executive Summary
-
-StreamVault is a well-architected Android TV IPTV player built with Kotlin, Compose for TV, Media3, Room, and Hilt. The overall code quality is high, dependencies are modern, and the Clean Architecture modular design is sound. This audit uncovered **76 issues** across all layers. After 15 fix batches, **all critical and high-severity code issues have been resolved**.
-
-| Severity | Found | Fixed | Remaining | Notes |
-|----------|-------|-------|-----------|-------|
-| 🔴 CRITICAL | 16 | 15 | 1 | Remaining: DB migration 8→9 (deferred — too risky pre-launch) |
-| 🟠 HIGH | 22 | 21 | 1 | Remaining: use case layer (post-launch) |
-| 🟡 MEDIUM | 20 | 18 | 2 | Remaining: deeper tests, missing domain features |
-| 🔵 LOW | 18 | 15 | 3 | Chromecast, integration tests, stress tests |
-
-### Detailed Finding Reports
-
-| Report | Contents |
-|--------|----------|
-| [01_CRITICAL_BLOCKERS.md](01_CRITICAL_BLOCKERS.md) | All Critical/Ship-blocker issues |
-| [02_PLAYER_ENGINE.md](02_PLAYER_ENGINE.md) | Media playback, decoder, buffering issues |
-| [03_DATA_LAYER.md](03_DATA_LAYER.md) | Database, parsing, sync, and data integrity |
-| [04_DOMAIN_LAYER.md](04_DOMAIN_LAYER.md) | Architecture, models, use cases, validation |
-| [05_UI_UX.md](05_UI_UX.md) | Screens, navigation, accessibility, focus management |
-| [06_SECURITY.md](06_SECURITY.md) | Credentials, network, file access |
-| [07_TESTING_LOCALIZATION.md](07_TESTING_LOCALIZATION.md) | Test coverage, translations, resources |
-
----
-
-## Architecture Overview
-
-```
-┌──────────────────────────────────────────────────────┐
-│ :app (UI Layer) │
-│ Compose for TV · ViewModels · Navigation · Hilt │
-├──────────────────────────────────────────────────────┤
-│ :domain (Business Logic) │
-│ Pure Kotlin · Models · Repository Interfaces │
-├──────────┬───────────────────────────────────────────┤
-│ :data │ :player │
-│ Room │ Media3 / ExoPlayer │
-│ Retrofit│ HLS / DASH / MPEG-TS │
-│ OkHttp │ Track Selection │
-│ Workers │ Buffering │
-└──────────┴───────────────────────────────────────────┘
-```
-
-**SDK:** Compile/Target 35 · Min 28 · Java 17 · Kotlin 2.1.0
-
----
-
-## Top 10 Issues — Resolution Status
-
-| # | Issue | Module | Severity | Status |
-|---|-------|--------|----------|--------|
-| 1 | Missing `proguard-rules.pro` | Build | 🔴 | ✅ Fixed (Batch 1) |
-| 2 | Decoder mode mapping reversed | Player | 🔴 | ✅ Fixed (Batch 2) |
-| 3 | `pixelWidthHeightRatio` stored as frame rate | Player | 🔴 | ✅ Fixed (Batch 2) |
-| 4 | No MediaSession integration | Player | 🔴 | ✅ Fixed (Batch 2) |
-| 5 | EPG staging negative IDs | Data | 🔴 | ⚠️ Mitigated — swap is transactional, queries filter by positive ID |
-| 6 | M3U category ID collision | Data | 🔴 | ✅ Fixed (Batch 3) |
-| 7 | ViewModels never cancel jobs | App | 🔴 | ✅ Fixed (Batch 4) |
-| 8 | D-Pad focus traps | App | 🔴 | ✅ Fixed (Batches 7, 14) — BackHandler + focusGroup |
-| 9 | Zero test coverage (domain/player) | Testing | 🔴 | ⚠️ Mitigated (Batch 24) — foundational unit tests added |
-| 10 | Hardcoded English strings | Localization | 🟠 | ✅ Fixed (Batches 8, 11, 13) |
-
----
-
-## Fix Log (25 Batches)
-
-| Batch | Commit | Summary |
-|-------|--------|---------|
-| 1 | — | Proguard rules, release signing |
-| 2 | — | Player engine: decoder mode, MediaSession, frame rate, error recovery, buffer config |
-| 3 | — | Category ID collision, credential redaction, M3U URL validation |
-| 4 | — | ViewModel onCleared(), ParentalControlManager race condition |
-| 5 | — | EPG date parsing (8 formats), M3U input length bounds, adult classifier i18n |
-| 6 | — | Recording race condition, ChannelNormalizer accent stripping |
-| 7 | — | Player error classification (errorCode), network timeouts, BackHandler, track selection |
-| 8 | — | Localization: RTL/i18n fixes, string extraction |
-| 9 | — | Provider toString() redaction, Domain Program.progressPercent testability |
-| 10 | `26667f8` | Backup CRC32 checksum, rememberSaveable, scope reuse, search LIMIT 1000, dashboard loading UI |
-| 11 | `45a1158` | 15+ RTL string concat fixes, HomeScreen error state UI |
-| 12 | `3f18d29` | Movies/Series error state UI (errorMessage + try/catch) |
-| 13 | `a8d708b` | N+1 query optimization (EXISTS), 3 hardcoded strings, stable LazyRow keys, sidebar width |
-| 14 | `f95aa70` | Accessibility contentDescription (7 components), sidebar focusGroup |
-| 15 | `6412892` | Audio content type, decoder reuse logging, M3U unquoted attr fix, SecureRandom cache, GetCustomCategories .catch, recovery notice duration, numeric switching in overlays, search hint, multi-view buffering indicator |
-| 16 | — | Domain model validation: init{} blocks with require() on 13 models |
-| 17 | — | Player metrics: bandwidth estimate, rebuffer count, buffered duration in PlayerStats |
-| 18 | — | UI animations: Crossfade on HomeScreen category transitions |
-| 19 | — | Repository API cleanup: getStreamInfo() with defaults, @Deprecated on getStreamUrl() |
-| 20 | — | Backup credential stripping: passwords cleared from exports |
-| 21 | — | DB foreign keys: FK constraints on 8 entities, MIGRATION_10_11 |
-| 22 | — | Pagination metadata: hasNextPage, hasPreviousPage, totalPages on PagedResult |
-| 23 | — | Removed unused extraAttributes from M3U parser |
-| 24 | — | Test coverage: domain model validation, Program, ParentalControlManager, ChannelNormalizer, StreamTypeDetector |
-| 25 | — | Icon density: verified vector adaptive icon handles all densities (API 26+ min) |
-
-## Remaining (Deferred / Post-Launch)
-
-| ID | Issue | Reason |
-|----|-------|--------|
-| C5 | EPG staging negative IDs | Mitigated (transactional swap, positive-only queries). Full fix needs schema migration |
-| C7 | Migration 8→9 unsafe ID remapping | Too risky to modify mid-release |
-| T2-T4 | Deeper test coverage | Post-launch test-writing effort |
-| DM2 | Thin use case layer | Architectural — post-launch refactor |
-| DM8 | Missing domain features | Feature-level — post-launch |
-| P14 | Chromecast / Cast support | Major feature — post-launch |
-| C15 | file:// URI usage | False positive — internal to app, not shared cross-process |
diff --git a/docs/qa/ANDROID_TV_FINAL_CERTIFICATION.md b/docs/qa/ANDROID_TV_FINAL_CERTIFICATION.md
deleted file mode 100644
index 128d63b5..00000000
--- a/docs/qa/ANDROID_TV_FINAL_CERTIFICATION.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# Android TV Final Certification Checklist
-
-Date: 2026-03-12
-Branch: `ui-change`
-Build under test: `appDebug`
-
-## Severity
-- `ship blocker`: must be fixed before release
-- `polish defect`: should be fixed before release unless explicitly waived
-- `minor follow-up`: acceptable for post-release follow-up
-
-## Environment
-- Device:
-- Android TV version:
-- Input device:
-- Build fingerprint:
-- Tester:
-
-## Global Checks
-- [ ] App launches without layout jumps or placeholder flashes.
-- [ ] Initial focus is visible on every major route.
-- [ ] `Back` behavior is deterministic and never traps focus.
-- [ ] Focus is restored after dialogs and sheets close.
-- [ ] Focus ring, text size, and contrast are readable from TV distance.
-- [ ] No clipped titles, buttons, or badges on 1080p and 4K outputs.
-- [ ] RTL layout mirrors rails, overlays, and aligned metadata correctly.
-- [ ] Search fields behave correctly with remote and soft keyboard input.
-
-## Welcome And Onboarding
-- [ ] Welcome screen first focus lands on the primary onboarding action.
-- [ ] Provider setup is fully navigable with remote only.
-- [ ] Xtream and playlist flows preserve validation and error messaging.
-- [ ] Long forms do not lose focus when validation errors appear.
-
-## Dashboard
-- [ ] Hero, shortcuts, continue-watching, and provider health are all reachable by D-pad.
-- [ ] Shelf-to-shelf traversal does not skip or trap focus.
-- [ ] Provider health messaging remains readable at TV distance.
-
-## Live TV
-- [ ] Category rail initial focus is correct.
-- [ ] Rail-to-channel-pane crossing is stable in both directions.
-- [ ] Large channel lists remain smooth while scrolling.
-- [ ] Channel search and category search both preserve focus correctly.
-- [ ] Reorder mode is remote-friendly and exits cleanly with `Back`.
-- [ ] Group rename/delete flows restore focus to the triggering item.
-- [ ] Multiview entry works from live browse and returns cleanly.
-- [ ] Locked channels clearly communicate protected state.
-
-## Movies And Series
-- [ ] Landing state is navigable without hidden focus jumps.
-- [ ] Category selection enters the paged grid correctly.
-- [ ] `Back` exits selected-category browse before leaving the route.
-- [ ] Load-more behavior remains correct and focusable.
-- [ ] Long-press actions still work on posters and shortcuts.
-- [ ] Locked titles remain readable and visually distinct.
-
-## Series Detail
-- [ ] Hero CTA, season rail, and episodes are all reachable by remote only.
-- [ ] Season changes keep focus in a predictable place.
-- [ ] Episode rows preserve hierarchy and readable metadata.
-
-## Saved
-- [ ] Preset chips, provider scope, and grouped shelves are all reachable.
-- [ ] Manage or reorder mode is visually distinct from browse mode.
-- [ ] Continue-watching and live recall sections keep consistent focus styling.
-
-## Guide
-- [ ] Filter strip, timeline grid, and details panel all have deterministic focus.
-- [ ] Focused program details always match the selected program cell.
-- [ ] Archive-ready states are clearly communicated.
-- [ ] Timeline scrolling remains performant on dense schedules.
-
-## Settings And Parental Controls
-- [ ] Provider cards, diagnostics, and management actions are all reachable.
-- [ ] Backup and restore actions are understandable without pointer input.
-- [ ] Parental group management keeps correct focus after PIN or dialog dismissal.
-
-## Player
-- [ ] Controls open with the intended primary focus target.
-- [ ] Transport, quick actions, and side overlays feel like one system.
-- [ ] Channel list overlay restores focus when reopened.
-- [ ] Guide and info overlays close in the correct `Back` order.
-- [ ] Track selection dialog and diagnostics sheet are fully remote-operable.
-- [ ] Resume prompt, numeric channel input, and error notices render cleanly.
-- [ ] Live playback, VOD playback, and archive playback all preserve the same control language.
-
-## Large Library Validation
-- [ ] Live browse remains responsive with representative 50k-100k channel data.
-- [ ] Movie browse remains on the paged library path under large datasets.
-- [ ] Series browse remains on the paged library path under large datasets.
-- [ ] No route shows whole-list loading or focus lag under large datasets.
-
-## Findings
-| Area | Severity | Result | Notes |
-| --- | --- | --- | --- |
-| Welcome | | | |
-| Dashboard | | | |
-| Live TV | | | |
-| Movies | | | |
-| Series | | | |
-| Series Detail | | | |
-| Saved | | | |
-| Guide | | | |
-| Settings | | | |
-| Player | | | |
-| RTL | | | |
-| Accessibility | | | |
-
-## Sign-Off
-- [ ] No unresolved ship blockers remain.
-- [ ] All polish defects are fixed or explicitly waived.
-- [ ] Final build/test bar has been re-run after the last fix.
diff --git a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt
index 441aaf06..95cc87db 100644
--- a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt
+++ b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt
@@ -14,4 +14,5 @@ interface RecordingManager {
suspend fun scheduleRecording(request: RecordingRequest): Result<RecordingItem>
suspend fun stopRecording(recordingId: String): Result<Unit>
suspend fun cancelRecording(recordingId: String): Result<Unit>
+ suspend fun deleteRecording(recordingId: String): Result<Unit>
}
diff --git a/domain/src/main/java/com/streamvault/domain/model/Category.kt b/domain/src/main/java/com/streamvault/domain/model/Category.kt
index 7783ed6b..0a6f005c 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Category.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Category.kt
@@ -2,6 +2,7 @@ package com.streamvault.domain.model
data class Category(
val id: Long,
+ val roomId: Long = id,
val name: String,
val parentId: Long? = null,
val type: ContentType = ContentType.LIVE,
diff --git a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt
index 5de66542..557b1d8d 100644
--- a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt
@@ -37,7 +37,8 @@ data class RecordingItem(
val programTitle: String? = null,
val outputPath: String? = null,
val status: RecordingStatus = RecordingStatus.SCHEDULED,
- val failureReason: String? = null
+ val failureReason: String? = null,
+ val terminalAtMs: Long? = null
) {
init {
require(id.isNotBlank()) { "id must not be blank" }
diff --git a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt
index f06d3620..e626d965 100644
--- a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt
@@ -2,6 +2,7 @@ package com.streamvault.domain.model
data class StreamInfo(
val url: String,
+ val title: String? = null,
val headers: Map<String, String> = emptyMap(),
val userAgent: String? = null,
val streamType: StreamType = StreamType.UNKNOWN,
@@ -18,6 +19,7 @@ enum class StreamType {
DASH,
MPEG_TS,
PROGRESSIVE,
+ RTSP, // PE-H03: native RTSP via Media3 RtspMediaSource
UNKNOWN
}
diff --git a/domain/src/test/java/com/streamvault/domain/model/DomainModelValidationTest.kt b/domain/src/test/java/com/streamvault/domain/model/DomainModelValidationTest.kt
deleted file mode 100644
index 0149f5d6..00000000
--- a/domain/src/test/java/com/streamvault/domain/model/DomainModelValidationTest.kt
+++ /dev/null
@@ -1,214 +0,0 @@
-package com.streamvault.domain.model
-
-import com.google.common.truth.Truth.assertThat
-import org.junit.Assert.assertThrows
-import org.junit.Test
-
-class DomainModelValidationTest {
-
- // --- Channel ---
-
- @Test
- fun `Channel - valid defaults`() {
- val channel = Channel(id = 1, name = "Test")
- assertThat(channel.number).isEqualTo(0)
- assertThat(channel.catchUpDays).isEqualTo(0)
- assertThat(channel.errorCount).isEqualTo(0)
- }
-
- @Test
- fun `Channel - negative number throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Channel(id = 1, name = "Test", number = -1)
- }
- }
-
- @Test
- fun `Channel - negative catchUpDays throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Channel(id = 1, name = "Test", catchUpDays = -1)
- }
- }
-
- @Test
- fun `Channel - negative errorCount throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Channel(id = 1, name = "Test", errorCount = -1)
- }
- }
-
- // --- Movie ---
-
- @Test
- fun `Movie - valid defaults`() {
- val movie = Movie(id = 1, name = "Test")
- assertThat(movie.durationSeconds).isEqualTo(0)
- assertThat(movie.rating).isEqualTo(0f)
- }
-
- @Test
- fun `Movie - negative durationSeconds throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Movie(id = 1, name = "Test", durationSeconds = -1)
- }
- }
-
- @Test
- fun `Movie - rating above 10 throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Movie(id = 1, name = "Test", rating = 10.1f)
- }
- }
-
- @Test
- fun `Movie - negative rating throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Movie(id = 1, name = "Test", rating = -0.1f)
- }
- }
-
- @Test
- fun `Movie - rating at boundary is valid`() {
- val movie = Movie(id = 1, name = "Test", rating = 10f)
- assertThat(movie.rating).isEqualTo(10f)
- }
-
- @Test
- fun `Movie - negative watchProgress throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Movie(id = 1, name = "Test", watchProgress = -1)
- }
- }
-
- @Test
- fun `Movie - negative lastWatchedAt throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Movie(id = 1, name = "Test", lastWatchedAt = -1)
- }
- }
-
- // --- Provider ---
-
- @Test
- fun `Provider - valid construction`() {
- val provider = Provider(
- name = "My Provider",
- type = ProviderType.XTREAM_CODES,
- serverUrl = "http://example.com"
- )
- assertThat(provider.name).isEqualTo("My Provider")
- }
-
- @Test
- fun `Provider - blank name throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Provider(name = " ", type = ProviderType.M3U, serverUrl = "http://example.com")
- }
- }
-
- @Test
- fun `Provider - zero maxConnections throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Provider(
- name = "Test",
- type = ProviderType.M3U,
- serverUrl = "http://example.com",
- maxConnections = 0
- )
- }
- }
-
- @Test
- fun `Provider - negative lastSyncedAt throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Provider(
- name = "Test",
- type = ProviderType.M3U,
- serverUrl = "http://example.com",
- lastSyncedAt = -1
- )
- }
- }
-
- // --- Category ---
-
- @Test
- fun `Category - valid defaults`() {
- val category = Category(id = 1, name = "Movies")
- assertThat(category.count).isEqualTo(0)
- }
-
- @Test
- fun `Category - negative count throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- Category(id = 1, name = "Movies", count = -1)
- }
- }
-
- // --- StreamInfo ---
-
- @Test
- fun `StreamInfo - valid construction`() {
- val info = StreamInfo(url = "http://stream.example.com/live.m3u8")
- assertThat(info.url).isEqualTo("http://stream.example.com/live.m3u8")
- }
-
- @Test
- fun `StreamInfo - blank url throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- StreamInfo(url = "")
- }
- }
-
- @Test
- fun `StreamInfo - whitespace-only url throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- StreamInfo(url = " ")
- }
- }
-
- // --- PagedResult ---
-
- @Test
- fun `PagedResult - hasNextPage true when more items`() {
- val result = PagedResult(items = listOf(1, 2, 3), totalCount = 10, offset = 0, limit = 3)
- assertThat(result.hasNextPage).isTrue()
- }
-
- @Test
- fun `PagedResult - hasNextPage false when at end`() {
- val result = PagedResult(items = listOf(1, 2), totalCount = 5, offset = 3, limit = 3)
- assertThat(result.hasNextPage).isFalse()
- }
-
- @Test
- fun `PagedResult - hasPreviousPage false at start`() {
- val result = PagedResult(items = listOf(1, 2, 3), totalCount = 10, offset = 0, limit = 3)
- assertThat(result.hasPreviousPage).isFalse()
- }
-
- @Test
- fun `PagedResult - hasPreviousPage true after first page`() {
- val result = PagedResult(items = listOf(4, 5, 6), totalCount = 10, offset = 3, limit = 3)
- assertThat(result.hasPreviousPage).isTrue()
- }
-
- @Test
- fun `PagedResult - totalPages calculated correctly`() {
- val result = PagedResult(items = listOf(1), totalCount = 10, offset = 0, limit = 3)
- assertThat(result.totalPages).isEqualTo(4) // ceil(10/3)
- }
-
- @Test
- fun `PagedResult - currentPage calculated correctly`() {
- val result = PagedResult(items = listOf(1), totalCount = 10, offset = 6, limit = 3)
- assertThat(result.currentPage).isEqualTo(2)
- }
-
- @Test
- fun `PagedResult - negative totalCount throws`() {
- assertThrows(IllegalArgumentException::class.java) {
- PagedResult(items = emptyList<Int>(), totalCount = -1, offset = 0, limit = 10)
- }
- }
-}
diff --git a/err.txt b/err.txt
deleted file mode 100644
index a84a64fc..00000000
--- a/err.txt
+++ /dev/null
@@ -1,64 +0,0 @@
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:kspDebugKotlin UP-TO-DATE
-> Task :app:compileDebugKotlin UP-TO-DATE
-
-BUILD SUCCESSFUL in 2s
-47 actionable tasks: 47 up-to-date
diff --git a/err_assemble.txt b/err_assemble.txt
deleted file mode 100644
index 7f565104..00000000
--- a/err_assemble.txt
+++ /dev/null
@@ -1,113 +0,0 @@
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :app:mergeDebugNativeDebugMetadata NO-SOURCE
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:kspDebugKotlin UP-TO-DATE
-> Task :app:compileDebugKotlin UP-TO-DATE
-> Task :app:javaPreCompileDebug UP-TO-DATE
-> Task :app:compileDebugJavaWithJavac UP-TO-DATE
-> Task :app:mergeDebugShaders UP-TO-DATE
-> Task :app:compileDebugShaders NO-SOURCE
-> Task :app:generateDebugAssets UP-TO-DATE
-> Task :data:mergeDebugShaders UP-TO-DATE
-> Task :data:compileDebugShaders NO-SOURCE
-> Task :data:generateDebugAssets UP-TO-DATE
-> Task :data:packageDebugAssets UP-TO-DATE
-> Task :player:mergeDebugShaders UP-TO-DATE
-> Task :player:compileDebugShaders NO-SOURCE
-> Task :player:generateDebugAssets UP-TO-DATE
-> Task :player:packageDebugAssets UP-TO-DATE
-> Task :app:mergeDebugAssets UP-TO-DATE
-> Task :app:compressDebugAssets UP-TO-DATE
-> Task :data:bundleLibRuntimeToJarDebug UP-TO-DATE
-> Task :player:bundleLibRuntimeToJarDebug UP-TO-DATE
-> Task :app:desugarDebugFileDependencies UP-TO-DATE
-> Task :app:hiltAggregateDepsDebug UP-TO-DATE
-
-> Task :app:hiltJavaCompileDebug
-C:\Users\david\.gemini\antigravity\scratch\iptv-player\app\build\generated\hilt\component_sources\debug\com\streamvault\app\StreamVaultApp_HiltComponents.java:155: error: [Dagger/MissingBinding] com.google.gson.Gson cannot be provided without an @Inject constructor or an @Provides-annotated method.
- public abstract static class SingletonC implements StreamVaultApp_GeneratedInjector,
- ^
-
- com.google.gson.Gson is injected at
- [com.streamvault.app.StreamVaultApp_HiltComponents.SingletonC] com.streamvault.data.manager.BackupManagerImpl(…, gson)
- com.streamvault.data.manager.BackupManagerImpl is injected at
- [com.streamvault.app.StreamVaultApp_HiltComponents.SingletonC] com.streamvault.app.di.RepositoryModule.bindBackupManager(impl)
- com.streamvault.domain.manager.BackupManager is injected at
- [com.streamvault.app.StreamVaultApp_HiltComponents.ViewModelC] com.streamvault.app.ui.screens.settings.SettingsViewModel(…, backupManager)
- com.streamvault.app.ui.screens.settings.SettingsViewModel is injected at
- [com.streamvault.app.StreamVaultApp_HiltComponents.ViewModelC] com.streamvault.app.ui.screens.settings.SettingsViewModel_HiltModules.BindsModule.binds(arg0)
- @dagger.hilt.android.internal.lifecycle.HiltViewModelMap java.util.Map<java.lang.Class<?>,javax.inject.Provider<androidx.lifecycle.ViewModel>> is requested at
- [com.streamvault.app.StreamVaultApp_HiltComponents.ViewModelC] dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.streamvault.app.StreamVaultApp_HiltComponents.SingletonC → com.streamvault.app.StreamVaultApp_HiltComponents.ActivityRetainedC → com.streamvault.app.StreamVaultApp_HiltComponents.ViewModelC]
-1 error
-
-> Task :app:hiltJavaCompileDebug FAILED
-
-FAILURE: Build failed with an exception.
-
-* What went wrong:
-Execution failed for task ':app:hiltJavaCompileDebug'.
-> Compilation failed; see the compiler error output for details.
-
-* Try:
-> Run with --info option to get more log output.
-> Run with --scan to get full insights.
-
-BUILD FAILED in 7s
-61 actionable tasks: 1 executed, 60 up-to-date
diff --git a/error.log b/error.log
deleted file mode 100644
index b67814cc..00000000
--- a/error.log
+++ /dev/null
@@ -1,123 +0,0 @@
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :app:mergeDebugNativeDebugMetadata NO-SOURCE
-> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :domain:compileKotlin UP-TO-DATE
-> Task :domain:compileJava NO-SOURCE
-> Task :domain:processResources NO-SOURCE
-> Task :domain:classes UP-TO-DATE
-> Task :domain:jar UP-TO-DATE
-> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:preBuild UP-TO-DATE
-> Task :data:preDebugBuild UP-TO-DATE
-> Task :data:writeDebugAarMetadata UP-TO-DATE
-> Task :player:preBuild UP-TO-DATE
-> Task :player:preDebugBuild UP-TO-DATE
-> Task :player:writeDebugAarMetadata UP-TO-DATE
-> Task :app:checkDebugAarMetadata UP-TO-DATE
-> Task :app:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResValues UP-TO-DATE
-> Task :data:generateDebugResources UP-TO-DATE
-> Task :data:packageDebugResources UP-TO-DATE
-> Task :player:generateDebugResValues UP-TO-DATE
-> Task :player:generateDebugResources UP-TO-DATE
-> Task :player:packageDebugResources UP-TO-DATE
-> Task :app:mapDebugSourceSetPaths UP-TO-DATE
-> Task :app:generateDebugResources UP-TO-DATE
-> Task :app:mergeDebugResources UP-TO-DATE
-> Task :app:packageDebugResources UP-TO-DATE
-> Task :app:parseDebugLocalResources UP-TO-DATE
-> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
-> Task :app:extractDeepLinksDebug UP-TO-DATE
-> Task :data:extractDeepLinksDebug UP-TO-DATE
-> Task :data:processDebugManifest UP-TO-DATE
-> Task :player:extractDeepLinksDebug UP-TO-DATE
-> Task :player:processDebugManifest UP-TO-DATE
-> Task :app:processDebugMainManifest UP-TO-DATE
-> Task :app:processDebugManifest UP-TO-DATE
-> Task :app:processDebugManifestForPackage UP-TO-DATE
-> Task :data:compileDebugLibraryResources UP-TO-DATE
-> Task :data:parseDebugLocalResources UP-TO-DATE
-> Task :data:generateDebugRFile UP-TO-DATE
-> Task :player:compileDebugLibraryResources UP-TO-DATE
-> Task :player:parseDebugLocalResources UP-TO-DATE
-> Task :player:generateDebugRFile UP-TO-DATE
-> Task :app:processDebugResources UP-TO-DATE
-> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :data:kspDebugKotlin UP-TO-DATE
-> Task :data:compileDebugKotlin UP-TO-DATE
-> Task :data:javaPreCompileDebug UP-TO-DATE
-> Task :data:compileDebugJavaWithJavac UP-TO-DATE
-> Task :data:copyRoomSchemas NO-SOURCE
-> Task :data:transformDebugClassesWithAsm UP-TO-DATE
-> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
-> Task :player:kspDebugKotlin UP-TO-DATE
-> Task :player:compileDebugKotlin UP-TO-DATE
-> Task :player:javaPreCompileDebug UP-TO-DATE
-> Task :player:compileDebugJavaWithJavac UP-TO-DATE
-> Task :player:transformDebugClassesWithAsm UP-TO-DATE
-> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:javaPreCompileDebug UP-TO-DATE
-> Task :app:mergeDebugShaders UP-TO-DATE
-> Task :app:compileDebugShaders NO-SOURCE
-> Task :app:generateDebugAssets UP-TO-DATE
-> Task :data:mergeDebugShaders UP-TO-DATE
-> Task :data:compileDebugShaders NO-SOURCE
-> Task :data:generateDebugAssets UP-TO-DATE
-> Task :data:packageDebugAssets UP-TO-DATE
-> Task :player:mergeDebugShaders UP-TO-DATE
-> Task :player:compileDebugShaders NO-SOURCE
-> Task :player:generateDebugAssets UP-TO-DATE
-> Task :player:packageDebugAssets UP-TO-DATE
-> Task :app:mergeDebugAssets UP-TO-DATE
-> Task :app:compressDebugAssets UP-TO-DATE
-> Task :data:bundleLibRuntimeToJarDebug UP-TO-DATE
-> Task :player:bundleLibRuntimeToJarDebug UP-TO-DATE
-> Task :app:desugarDebugFileDependencies UP-TO-DATE
-> Task :data:processDebugJavaRes UP-TO-DATE
-> Task :player:processDebugJavaRes UP-TO-DATE
-> Task :app:checkDebugDuplicateClasses UP-TO-DATE
-> Task :app:mergeExtDexDebug UP-TO-DATE
-> Task :data:bundleLibRuntimeToDirDebug UP-TO-DATE
-> Task :player:bundleLibRuntimeToDirDebug UP-TO-DATE
-> Task :app:mergeDebugJniLibFolders UP-TO-DATE
-> Task :app:mergeLibDexDebug UP-TO-DATE
-> Task :data:mergeDebugJniLibFolders UP-TO-DATE
-> Task :data:mergeDebugNativeLibs NO-SOURCE
-> Task :data:copyDebugJniLibsProjectOnly UP-TO-DATE
-> Task :player:mergeDebugJniLibFolders UP-TO-DATE
-> Task :player:mergeDebugNativeLibs NO-SOURCE
-> Task :player:copyDebugJniLibsProjectOnly UP-TO-DATE
-> Task :app:mergeDebugNativeLibs UP-TO-DATE
-> Task :app:stripDebugDebugSymbols UP-TO-DATE
-> Task :app:validateSigningDebug UP-TO-DATE
-> Task :app:writeDebugAppMetadata UP-TO-DATE
-> Task :app:writeDebugSigningConfigVersions UP-TO-DATE
-> Task :data:stripDebugDebugSymbols NO-SOURCE
-> Task :data:copyDebugJniLibsProjectAndLocalJars UP-TO-DATE
-> Task :data:extractDebugAnnotations UP-TO-DATE
-> Task :data:extractDeepLinksForAarDebug UP-TO-DATE
-> Task :data:mergeDebugGeneratedProguardFiles UP-TO-DATE
-> Task :data:mergeDebugConsumerProguardFiles UP-TO-DATE
-> Task :data:prepareDebugArtProfile UP-TO-DATE
-> Task :data:prepareLintJarForPublish UP-TO-DATE
-> Task :data:mergeDebugJavaResource UP-TO-DATE
-> Task :data:syncDebugLibJars UP-TO-DATE
-> Task :data:bundleDebugAar UP-TO-DATE
-> Task :data:assembleDebug UP-TO-DATE
-> Task :player:stripDebugDebugSymbols NO-SOURCE
-> Task :player:copyDebugJniLibsProjectAndLocalJars UP-TO-DATE
-> Task :player:extractDebugAnnotations UP-TO-DATE
-> Task :player:extractDeepLinksForAarDebug UP-TO-DATE
-> Task :player:mergeDebugGeneratedProguardFiles UP-TO-DATE
-> Task :player:mergeDebugConsumerProguardFiles UP-TO-DATE
-> Task :player:prepareDebugArtProfile UP-TO-DATE
-> Task :player:prepareLintJarForPublish UP-TO-DATE
-> Task :player:mergeDebugJavaResource UP-TO-DATE
-> Task :player:syncDebugLibJars UP-TO-DATE
-> Task :player:bundleDebugAar UP-TO-DATE
-> Task :player:assembleDebug UP-TO-DATE
-
-> Task :app:kspDebugKotlin FAILED
-94 actionable tasks: 1 executed, 93 up-to-date
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 03f1ea19..f5607f56 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -18,6 +18,7 @@ lifecycle = "2.8.7"
navigation-compose = "2.8.5"
datastore = "1.1.1"
gson = "2.11.0"
+kotlinx-serialization = "1.8.0"
work = "2.9.0"
# Test
junit = "4.13.2"
@@ -26,6 +27,7 @@ kxml2 = "2.3.0"
mockito-kotlin = "5.4.0"
androidx-test-ext-junit = "1.2.1"
espresso = "3.6.1"
+androidx-test-runner = "1.6.2"
[libraries]
# Compose BOM
@@ -43,6 +45,7 @@ compose-tv-material = { group = "androidx.tv", name = "tv-material", version.ref
media3-exoplayer = { group = "androidx.media3", name = "media3-exoplayer", version.ref = "media3" }
media3-exoplayer-hls = { group = "androidx.media3", name = "media3-exoplayer-hls", version.ref = "media3" }
media3-exoplayer-dash = { group = "androidx.media3", name = "media3-exoplayer-dash", version.ref = "media3" }
+media3-exoplayer-rtsp = { group = "androidx.media3", name = "media3-exoplayer-rtsp", version.ref = "media3" }
media3-datasource-okhttp = { group = "androidx.media3", name = "media3-datasource-okhttp", version.ref = "media3" }
media3-session = { group = "androidx.media3", name = "media3-session", version.ref = "media3" }
media3-ui = { group = "androidx.media3", name = "media3-ui", version.ref = "media3" }
@@ -51,6 +54,7 @@ media3-ui = { group = "androidx.media3", name = "media3-ui", version.ref = "medi
room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
+room-testing = { group = "androidx.room", name = "room-testing", version.ref = "room" }
# Hilt
hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
@@ -65,6 +69,7 @@ retrofit-gson = { group = "com.squareup.retrofit2", name = "converter-gson", ver
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" }
+kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinx-serialization" }
# Image Loading
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
@@ -97,6 +102,7 @@ coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-
kxml2 = { group = "net.sf.kxml", name = "kxml2", version.ref = "kxml2" }
mockito-kotlin = { group = "org.mockito.kotlin", name = "mockito-kotlin", version.ref = "mockito-kotlin" }
androidx-test-ext-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidx-test-ext-junit" }
+androidx-test-runner = { group = "androidx.test", name = "runner", version.ref = "androidx-test-runner" }
espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espresso" }
[plugins]
@@ -105,6 +111,7 @@ android-library = { id = "com.android.library", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
+kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }
room = { id = "androidx.room", version.ref = "room" }
diff --git a/player/build.gradle.kts b/player/build.gradle.kts
index 01e97a9e..bb357f2b 100644
--- a/player/build.gradle.kts
+++ b/player/build.gradle.kts
@@ -30,6 +30,7 @@ dependencies {
implementation(libs.media3.exoplayer)
implementation(libs.media3.exoplayer.hls)
implementation(libs.media3.exoplayer.dash)
+ implementation(libs.media3.exoplayer.rtsp) // PE-H03: RTSP stream support
implementation(libs.media3.datasource.okhttp)
implementation(libs.media3.session)
implementation(libs.media3.ui)
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index 1522559f..19a59ea5 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -1,7 +1,10 @@
package com.streamvault.player
import android.content.Context
+import android.media.AudioFocusRequest
+import android.media.AudioManager
import android.net.Uri
+import android.view.View
import androidx.annotation.OptIn
import androidx.media3.common.C
import androidx.media3.common.MediaItem
@@ -15,10 +18,13 @@ import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.dash.DashMediaSource
import androidx.media3.exoplayer.hls.HlsMediaSource
+import androidx.media3.exoplayer.rtsp.RtspMediaSource
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.exoplayer.analytics.AnalyticsListener
import androidx.media3.exoplayer.DecoderReuseEvaluation
+import androidx.media3.ui.AspectRatioFrameLayout
+import androidx.media3.ui.PlayerView
import androidx.media3.common.Format
import androidx.media3.session.MediaSession
import com.streamvault.domain.model.DecoderMode
@@ -26,13 +32,15 @@ import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.StreamType
import com.streamvault.domain.model.VideoFormat
import androidx.media3.exoplayer.DefaultLoadControl
-import androidx.media3.common.AudioAttributes
+import androidx.media3.common.AudioAttributes as Media3AudioAttributes
import android.os.Handler
import android.os.Looper
+import android.os.SystemClock
import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
+import kotlin.math.abs
import okhttp3.OkHttpClient
import javax.inject.Inject
import javax.inject.Singleton
@@ -48,16 +56,65 @@ class Media3PlayerEngine @Inject constructor(
private var exoPlayer: ExoPlayer? = null
private var mediaSession: MediaSession? = null
private var currentDecoderMode: DecoderMode = DecoderMode.AUTO
+ /**
+ * When true the track selector caps video at 720p.
+ * Set to true for multi-view slots so each instance doesn't compete for 4K bandwidth.
+ */
+ var constrainResolutionForMultiView: Boolean = false
private var pollingJob: Job? = null
private var lastStreamInfo: StreamInfo? = null
private var retryCount = 0
private var lastFrameRate: Float = 0f
private val handler = Handler(Looper.getMainLooper())
+ private var lastBandwidthStatsUpdateMs: Long = 0L
+ private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ private var audioFocusRequest: AudioFocusRequest? = null
+ private var hasAudioFocus = false
+ private var shouldResumeOnAudioFocusGain = false
+ private var currentVolume = 1f
+ private var isDucked = false
+
+ private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
+ when (focusChange) {
+ AudioManager.AUDIOFOCUS_GAIN -> {
+ hasAudioFocus = true
+ isDucked = false
+ exoPlayer?.volume = currentVolume
+ if (shouldResumeOnAudioFocusGain) {
+ shouldResumeOnAudioFocusGain = false
+ exoPlayer?.playWhenReady = true
+ }
+ }
+
+ AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
+ isDucked = true
+ exoPlayer?.volume = (currentVolume * 0.2f).coerceAtLeast(0.05f)
+ }
+
+ AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
+ hasAudioFocus = false
+ isDucked = false
+ shouldResumeOnAudioFocusGain = exoPlayer?.isPlaying == true
+ exoPlayer?.playWhenReady = false
+ exoPlayer?.volume = currentVolume
+ }
+
+ AudioManager.AUDIOFOCUS_LOSS -> {
+ hasAudioFocus = false
+ isDucked = false
+ shouldResumeOnAudioFocusGain = false
+ exoPlayer?.playWhenReady = false
+ exoPlayer?.volume = currentVolume
+ }
+ }
+ }
companion object {
private const val TAG = "Media3PlayerEngine"
private const val MAX_RETRIES = 3
private const val RETRY_BASE_DELAY_MS = 2000L
+ private const val BANDWIDTH_STATS_MIN_INTERVAL_MS = 1500L
+ private const val BUFFERED_DURATION_PUBLISH_STEP_MS = 1000L
}
private val _playbackState = MutableStateFlow(PlaybackState.IDLE)
@@ -116,20 +173,22 @@ class Media3PlayerEngine @Inject constructor(
.build()
val trackSelector = androidx.media3.exoplayer.trackselection.DefaultTrackSelector(context).apply {
- parameters = parameters.buildUpon()
- .setMaxVideoSize(1280, 720) // Multi-View optimization: don't request 1080p/4K per slot
- .build()
+ if (constrainResolutionForMultiView) {
+ parameters = parameters.buildUpon()
+ .setMaxVideoSize(1280, 720) // Multi-view: cap each slot at 720p
+ .build()
+ }
}
return ExoPlayer.Builder(context, renderersFactory)
.setTrackSelector(trackSelector)
.setLoadControl(loadControl)
.setAudioAttributes(
- AudioAttributes.Builder()
+ Media3AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA)
.setContentType(C.AUDIO_CONTENT_TYPE_UNKNOWN)
.build(),
- true // handleAudioFocus
+ false // Explicitly managed via AudioManager below.
)
.build()
.apply {
@@ -183,8 +242,14 @@ class Media3PlayerEngine @Inject constructor(
totalBytesLoaded: Long,
bitrateEstimate: Long
) {
- _playerStats.update {
- it.copy(bandwidthEstimate = bitrateEstimate)
+ val now = SystemClock.elapsedRealtime()
+ updatePlayerStats { current ->
+ if (!shouldPublishBandwidthEstimate(current.bandwidthEstimate, bitrateEstimate, now)) {
+ current
+ } else {
+ lastBandwidthStatsUpdateMs = now
+ current.copy(bandwidthEstimate = bitrateEstimate)
+ }
}
}
})
@@ -227,8 +292,10 @@ class Media3PlayerEngine @Inject constructor(
if (retryCount < MAX_RETRIES && isRecoverableError(error)) {
retryCount++
Log.w(TAG, "Recoverable error (attempt $retryCount/$MAX_RETRIES), retrying...")
+ val streamInfoSnapshot = lastStreamInfo
+ _playerStats.update { it.copy(droppedFrames = 0) }
handler.postDelayed({
- lastStreamInfo?.let { prepare(it) }
+ streamInfoSnapshot?.let { prepare(it) }
}, retryCount * RETRY_BASE_DELAY_MS)
} else {
_error.tryEmit(PlayerError.fromException(error))
@@ -288,6 +355,7 @@ class Media3PlayerEngine @Inject constructor(
lastStreamInfo = streamInfo
retryCount = 0
lastFrameRate = 0f
+ lastBandwidthStatsUpdateMs = 0L
handler.removeCallbacksAndMessages(null)
val player = getOrCreatePlayer()
_error.tryEmit(null)
@@ -297,12 +365,12 @@ class Media3PlayerEngine @Inject constructor(
val streamType = streamInfo.streamType.takeIf { it != StreamType.UNKNOWN }
?: StreamTypeDetector.detect(streamInfo.url)
- val mediaSource = createMediaSource(streamInfo.url, streamType, dataSourceFactory)
+ val mediaSource = createMediaSource(streamInfo.url, streamType, dataSourceFactory, streamInfo.title)
player.setMediaSource(mediaSource)
player.prepare()
_videoFormat.value = VideoFormat(0, 0) // Reset format
- player.playWhenReady = true
+ player.playWhenReady = requestAudioFocusIfNeeded()
}
private fun createDataSourceFactory(streamInfo: StreamInfo): DataSource.Factory {
@@ -328,10 +396,18 @@ class Media3PlayerEngine @Inject constructor(
private fun createMediaSource(
url: String,
streamType: StreamType,
- dataSourceFactory: DataSource.Factory
+ dataSourceFactory: DataSource.Factory,
+ title: String? = null
): MediaSource {
val uri = Uri.parse(url)
- val mediaItem = MediaItem.fromUri(uri)
+ val mediaItem = MediaItem.Builder()
+ .setUri(uri)
+ .setMediaMetadata(
+ androidx.media3.common.MediaMetadata.Builder()
+ .setTitle(title)
+ .build()
+ )
+ .build()
return when (streamType) {
StreamType.HLS -> HlsMediaSource.Factory(dataSourceFactory)
@@ -341,6 +417,10 @@ class Media3PlayerEngine @Inject constructor(
StreamType.DASH -> DashMediaSource.Factory(dataSourceFactory)
.createMediaSource(mediaItem)
+ // PE-H03: RTSP uses its own built-in transport, not OkHttp.
+ StreamType.RTSP -> RtspMediaSource.Factory()
+ .createMediaSource(mediaItem)
+
StreamType.MPEG_TS, StreamType.PROGRESSIVE, StreamType.UNKNOWN ->
ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(mediaItem)
@@ -348,16 +428,22 @@ class Media3PlayerEngine @Inject constructor(
}
override fun play() {
- exoPlayer?.playWhenReady = true
+ if (requestAudioFocusIfNeeded()) {
+ exoPlayer?.playWhenReady = true
+ }
}
override fun pause() {
exoPlayer?.playWhenReady = false
+ shouldResumeOnAudioFocusGain = false
+ abandonAudioFocusIfHeld()
}
override fun stop() {
exoPlayer?.stop()
_playbackState.value = PlaybackState.IDLE
+ shouldResumeOnAudioFocusGain = false
+ abandonAudioFocusIfHeld()
}
override fun seekTo(positionMs: Long) {
@@ -366,7 +452,13 @@ class Media3PlayerEngine @Inject constructor(
override fun seekForward(ms: Long) {
exoPlayer?.let { player ->
- val newPos = (player.currentPosition + ms).coerceAtMost(player.duration)
+ val duration = player.duration
+ // C.TIME_UNSET (-1) is returned for live/unbounded streams — don't coerce against it.
+ val newPos = if (duration != C.TIME_UNSET) {
+ (player.currentPosition + ms).coerceAtMost(duration)
+ } else {
+ player.currentPosition + ms
+ }
player.seekTo(newPos)
}
}
@@ -381,26 +473,30 @@ class Media3PlayerEngine @Inject constructor(
override fun setDecoderMode(mode: DecoderMode) {
if (currentDecoderMode != mode) {
currentDecoderMode = mode
- // Recreate player with new decoder settings
+ val streamInfo = lastStreamInfo ?: return // Nothing playing — just update mode
val wasPlaying = exoPlayer?.isPlaying ?: false
val position = exoPlayer?.currentPosition ?: 0
- val mediaSource = exoPlayer?.currentMediaItem
exoPlayer?.release()
exoPlayer = null
-
- if (mediaSource != null) {
- val player = getOrCreatePlayer()
- player.setMediaItem(mediaSource)
- player.prepare()
- player.seekTo(position)
- player.playWhenReady = wasPlaying
- }
+ mediaSession?.release()
+ mediaSession = null
+
+ // Re-prepare using the original StreamInfo so the custom data source factory
+ // (headers, user-agent) is fully rebuilt — not just the bare MediaItem.
+ prepare(streamInfo)
+ if (position > 0) exoPlayer?.seekTo(position)
+ if (!wasPlaying) exoPlayer?.playWhenReady = false
}
}
override fun setVolume(volume: Float) {
- exoPlayer?.volume = volume.coerceIn(0f, 1f)
+ currentVolume = volume.coerceIn(0f, 1f)
+ exoPlayer?.volume = if (isDucked) {
+ (currentVolume * 0.2f).coerceAtLeast(0.05f)
+ } else {
+ currentVolume
+ }
}
override fun selectAudioTrack(trackId: String) {
@@ -468,6 +564,8 @@ class Media3PlayerEngine @Inject constructor(
override fun release() {
stopPolling()
handler.removeCallbacksAndMessages(null)
+ shouldResumeOnAudioFocusGain = false
+ abandonAudioFocusIfHeld()
mediaSession?.release()
mediaSession = null
exoPlayer?.release()
@@ -499,17 +597,111 @@ class Media3PlayerEngine @Inject constructor(
_duration.value = player.duration.coerceAtLeast(0L)
// Update buffered duration for diagnostics
val buffered = player.bufferedPosition - player.currentPosition
- _playerStats.update { it.copy(bufferedDurationMs = buffered.coerceAtLeast(0L)) }
+ updatePlayerStats { current ->
+ val bufferedDurationMs = buffered.coerceAtLeast(0L)
+ if (shouldPublishBufferedDuration(current.bufferedDurationMs, bufferedDurationMs)) {
+ current.copy(bufferedDurationMs = bufferedDurationMs)
+ } else {
+ current
+ }
+ }
}
- delay(1000) // Poll every 1s — supplements onPositionDiscontinuity for continuous updates
+ delay(250) // PE-M02: 250ms polling for smooth seek-bar animation
}
}
}
+ private inline fun updatePlayerStats(transform: (PlayerStats) -> PlayerStats) {
+ _playerStats.update { current ->
+ val updated = transform(current)
+ if (updated == current) current else updated
+ }
+ }
+
+ private fun shouldPublishBandwidthEstimate(
+ currentEstimate: Long,
+ newEstimate: Long,
+ nowMs: Long
+ ): Boolean {
+ if (newEstimate <= 0L) return false
+ if (currentEstimate <= 0L) return true
+ val absoluteDelta = abs(newEstimate - currentEstimate)
+ val relativeThreshold = (currentEstimate / 8).coerceAtLeast(250_000L)
+ return absoluteDelta >= relativeThreshold || nowMs - lastBandwidthStatsUpdateMs >= BANDWIDTH_STATS_MIN_INTERVAL_MS
+ }
+
+ private fun shouldPublishBufferedDuration(currentDurationMs: Long, newDurationMs: Long): Boolean {
+ return currentDurationMs == 0L || newDurationMs == 0L || abs(newDurationMs - currentDurationMs) >= BUFFERED_DURATION_PUBLISH_STEP_MS
+ }
+
private fun stopPolling() {
pollingJob?.cancel()
pollingJob = null
}
- override fun getPlayerView(): Any? = exoPlayer
+ override fun createRenderView(context: Context, resizeMode: PlayerSurfaceResizeMode): View {
+ return PlayerView(context).apply {
+ useController = false
+ setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER)
+ player = exoPlayer
+ applyResizeMode(resizeMode)
+ }
+ }
+
+ override fun bindRenderView(renderView: View, resizeMode: PlayerSurfaceResizeMode) {
+ val playerView = renderView as? PlayerView ?: return
+ if (playerView.player !== exoPlayer) {
+ playerView.player = exoPlayer
+ }
+ playerView.applyResizeMode(resizeMode)
+ }
+
+ private fun PlayerView.applyResizeMode(surfaceResizeMode: PlayerSurfaceResizeMode) {
+ resizeMode = when (surfaceResizeMode) {
+ PlayerSurfaceResizeMode.FIT -> AspectRatioFrameLayout.RESIZE_MODE_FIT
+ PlayerSurfaceResizeMode.FILL -> AspectRatioFrameLayout.RESIZE_MODE_FILL
+ PlayerSurfaceResizeMode.ZOOM -> AspectRatioFrameLayout.RESIZE_MODE_ZOOM
+ }
+ }
+
+ private fun requestAudioFocusIfNeeded(): Boolean {
+ if (hasAudioFocus) {
+ if (isDucked) {
+ isDucked = false
+ exoPlayer?.volume = currentVolume
+ }
+ return true
+ }
+ val focusRequest = audioFocusRequest ?: buildAudioFocusRequest().also { audioFocusRequest = it }
+ val focusResult = audioManager.requestAudioFocus(focusRequest)
+ hasAudioFocus = focusResult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
+ if (!hasAudioFocus) {
+ Log.w(TAG, "Audio focus request denied; playback will remain paused")
+ return false
+ }
+ isDucked = false
+ exoPlayer?.volume = currentVolume
+ return true
+ }
+
+ private fun abandonAudioFocusIfHeld() {
+ if (!hasAudioFocus) return
+ audioFocusRequest?.let { audioManager.abandonAudioFocusRequest(it) }
+ hasAudioFocus = false
+ isDucked = false
+ }
+
+ private fun buildAudioFocusRequest(): AudioFocusRequest {
+ val platformAudioAttributes = android.media.AudioAttributes.Builder()
+ .setUsage(android.media.AudioAttributes.USAGE_MEDIA)
+ .setContentType(android.media.AudioAttributes.CONTENT_TYPE_MOVIE)
+ .build()
+ return AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
+ .setAudioAttributes(platformAudioAttributes)
+ .setAcceptsDelayedFocusGain(false)
+ .setWillPauseWhenDucked(false)
+ .setOnAudioFocusChangeListener(audioFocusChangeListener)
+ .build()
+ }
+
}
diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
index 5f0ea71c..bf4ab38b 100644
--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
@@ -1,5 +1,7 @@
package com.streamvault.player
+import android.content.Context
+import android.view.View
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.VideoFormat
@@ -37,8 +39,14 @@ interface PlayerEngine {
fun selectSubtitleTrack(trackId: String?) // null to disable subtitles
fun release()
- /** Returns the underlying player view for Compose embedding */
- fun getPlayerView(): Any?
+ fun createRenderView(context: Context, resizeMode: PlayerSurfaceResizeMode): View
+ fun bindRenderView(renderView: View, resizeMode: PlayerSurfaceResizeMode)
+}
+
+enum class PlayerSurfaceResizeMode {
+ FIT,
+ FILL,
+ ZOOM
}
enum class PlaybackState {
diff --git a/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt b/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt
index 8cf33489..b1cf2d43 100644
--- a/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt
+++ b/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt
@@ -10,6 +10,10 @@ object StreamTypeDetector {
fun detect(url: String): StreamType {
val cleanUrl = url.lowercase().substringBefore("?").substringBefore("#")
+ val scheme = cleanUrl.substringBefore("://")
+
+ // RTSP / RTSPs — must be handled first; RtspMediaSource doesn't use OkHttp
+ if (scheme == "rtsp" || scheme == "rtsps") return StreamType.RTSP
return when {
// HLS