StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
fix: add Stalker VOD file fallback
David Nashash18d30fd11b05
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.ktindex 82f93a29..77adc58b 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt@@ -780,6 +780,27 @@ class OkHttpStalkerApiService @Inject constructor()}+ override suspend fun getVodFiles(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ movieId: String+ ): Result<List<StalkerItemRecord>> = runApiCall("Failed to load movie files") {+ fetchPagedItemPage(+ session = session,+ profile = profile,+ page = 1,+ baseQuery = mapOf(+ "type" to "vod",+ "action" to "get_ordered_list",+ "movie_id" to movieId,+ "season_id" to "0",+ "episode_id" to "0",+ "row" to "0",+ "JsHttpRequest" to "1-xml"+ )+ ).items+ }+override suspend fun getSeriesCategories(session: StalkerSession,profile: StalkerDeviceProfilediff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.ktindex 99b5caed..a3c5431d 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt@@ -346,6 +346,15 @@ interface StalkerApiService {searchQuery: String?): Result<StalkerPagedItems> = getVodStreamsPage(session, profile, categoryId, page)+ /** Returns the playable file rows exposed when opening a video-club movie. */+ suspend fun getVodFiles(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ movieId: String+ ): Result<List<StalkerItemRecord>> {+ return Result.error("VOD file lookup is not supported by this transport.")+ }+suspend fun getSeriesCategories(session: StalkerSession,profile: StalkerDeviceProfilediff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.ktindex 15be28b7..69ac3731 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt@@ -141,6 +141,10 @@ internal companion object {private const val AUTH_FAILURE_COOLDOWN_MILLIS = 2_000Lprivate const val FALLBACK_SURROGATE_FLOOR = 4_000_000_000Lconst val CATALOG_LAYOUT_DETECTION_VERSION = 1+ private const val VOD_FILE_SOURCE_KEY = "vod_file"+ private val BARE_VOD_MOVIE_CMD_REGEX = Regex("^/media/(\\d+)\\.mpg$", RegexOption.IGNORE_CASE)+ private val BARE_VOD_FILE_CMD_REGEX = Regex("^/media/file_(\\d+)\\.mpg$", RegexOption.IGNORE_CASE)+ private val NUMERIC_ID_REGEX = Regex("^\\d+$")private val sharedAuthCache = ConcurrentHashMap<String, CachedAuth>()private val sharedPortalAuthCache = ConcurrentHashMap<String, CachedAuth>()private val sharedAuthFailureCache = ConcurrentHashMap<String, CachedAuthFailure>()@@ -902,6 +906,62 @@ internal companion object {)}+ /**+ * Looks up the file rows for a bare video-club movie command after the portal rejects+ * the existing command with `nothing_to_play`.+ *+ * This is deliberately lazy so portals where the existing command already works keep+ * the original request count and playback ordering.+ */+ private suspend fun loadMovieFileFallbackCandidates(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ descriptor: StalkerPlaybackDescriptor+ ): Result<List<StalkerCommandVariant>> {+ if (descriptor.candidates.any {+ detectStalkerPlaybackMode(it.cmd, descriptor.capabilities) == StalkerPlaybackMode.DIRECT_URL+ }+ ) {+ return Result.success(emptyList())+ }+ val movieId = descriptor.candidates+ .mapNotNull(::extractBareVodMovieId)+ .firstOrNull()+ ?: return Result.success(emptyList())+ return when (val result = api.getVodFiles(session, profile, movieId)) {+ is Result.Success -> Result.success(+ result.data+ .mapIndexedNotNull { index, record ->+ vodFileCmdForRecord(record)?.let { cmd ->+ StalkerCommandVariant(+ cmd = cmd,+ playbackMode = detectStalkerPlaybackMode(cmd, descriptor.capabilities),+ sourceKey = VOD_FILE_SOURCE_KEY,+ priority = index+ )+ }+ }+ .distinctBy { it.cmd.trim() }+ )+ is Result.Error -> {+ Log.d(TAG, "Stalker VOD file lookup failed movie=$movieId reason=${result.message}")+ Result.error(result.message, result.exception)+ }+ is Result.Loading -> Result.error("Unexpected loading state")+ }+ }++ private fun extractBareVodMovieId(variant: StalkerCommandVariant): String? {+ val cmd = variant.cmd.substringAfter(' ', missingDelimiterValue = variant.cmd).trim()+ return BARE_VOD_MOVIE_CMD_REGEX.matchEntire(cmd)?.groupValues?.getOrNull(1)+ }++ private fun vodFileCmdForRecord(record: StalkerItemRecord): String? {+ record.cmd?.trim()?.takeIf { BARE_VOD_FILE_CMD_REGEX.matches(it) }?.let { return it }+ val numericId = record.id.trim().takeIf { it.matches(NUMERIC_ID_REGEX) } ?: return null+ return "/media/file_${numericId}.mpg"+ }+private suspend fun resolvePlaybackInfoInternal(kind: StalkerStreamKind,descriptor: StalkerPlaybackDescriptor,@@ -919,7 +979,12 @@ internal companion object {.sortedBy { variant ->if (preferredPlaybackMode != null && variant.playbackMode == preferredPlaybackMode) 0 else 1}- orderedCandidates.forEach { variant ->+ .toMutableList()+ var candidateIndex = 0+ var vodFileFallbackAttempted = false+ var vodFileFallbackCandidatesAdded = false+ while (candidateIndex < orderedCandidates.size) {+ val variant = orderedCandidates[candidateIndex++]val adapter = resolveStalkerPlaybackAdapter(descriptor = descriptor,variant = variant,@@ -969,7 +1034,7 @@ internal companion object {if (!adapter.requiresCreateLink(variant)) {lastError = Result.error("This portal requires a different playback path than the default command.")- return@forEach+ continue}consultResolvedStreamUrlCache(kind, variant.cmd)?.let { cachedResolvedUrl ->@@ -1032,9 +1097,45 @@ is Result.Success -> {}is Result.Error -> {lastError = linkResult- if (generateSequence(linkResult.exception) { it.cause }- .any { it is StalkerApiError.ContentUnavailable }- ) {+ val contentUnavailable = generateSequence(linkResult.exception) { it.cause }+ .any { it is StalkerApiError.ContentUnavailable }+ if (contentUnavailable) {+ if (+ kind == StalkerStreamKind.MOVIE &&+ variant.sourceKey != VOD_FILE_SOURCE_KEY &&+ !vodFileFallbackAttempted+ ) {+ vodFileFallbackAttempted = true+ val fallbackResult = loadMovieFileFallbackCandidates(+ session = session,+ profile = profile,+ descriptor = descriptor+ )+ when (fallbackResult) {+ is Result.Success -> {+ if (fallbackResult.data.isNotEmpty()) {+ // Keep all pre-existing command variants ahead of the+ // recovery rows so the fallback cannot change their order.+ orderedCandidates.addAll(fallbackResult.data)+ vodFileFallbackCandidatesAdded = true+ continue+ }+ }+ is Result.Error -> {+ lastError = fallbackResult+ if (isAuthorizationFailure(fallbackResult.message, fallbackResult.exception)) {+ // Let the existing rebootstrap path handle an auth failure+ // from the secondary lookup instead of hiding it as a+ // content-unavailable response.+ break+ }+ }+ is Result.Loading -> Unit+ }+ }+ if (variant.sourceKey == VOD_FILE_SOURCE_KEY || vodFileFallbackCandidatesAdded) {+ continue+ }val message = linkResult.message.takeIf(String::isNotBlank)?: "The provider reported that this item is currently unavailable."return Result.error(diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.ktindex 7d190855..55661d4c 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt@@ -1925,6 +1925,59 @@ class OkHttpStalkerApiServiceTest {assertThat(page.isTruncated).isFalse()}+ @Test+ fun getVodFiles_requests_movie_files_by_movie_id() = runTest {+ var requestedMovieId: String? = null+ var requestedAction: String? = null+ var requestedType: String? = null+ var requestedSeasonId: String? = null+ var requestedEpisodeId: String? = null+ var requestedRow: String? = null+ var requestedJsHttpRequest: String? = null+ val service = OkHttpStalkerApiService(+ okHttpClient = OkHttpClient.Builder()+ .addInterceptor { chain ->+ requestedMovieId = chain.request().url.queryParameter("movie_id")+ requestedAction = chain.request().url.queryParameter("action")+ requestedType = chain.request().url.queryParameter("type")+ requestedSeasonId = chain.request().url.queryParameter("season_id")+ requestedEpisodeId = chain.request().url.queryParameter("episode_id")+ requestedRow = chain.request().url.queryParameter("row")+ requestedJsHttpRequest = chain.request().url.queryParameter("JsHttpRequest")+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body(+ """{"js":{"total_items":1,"max_page_items":14,"data":[{"id":"3199303","name":"Punjabi / Ultra high quality (4K)","cmd":"http://cdn.example.com/8be12/index.m3u8"}]}}"""+ .toResponseBody("application/json".toMediaType())+ )+ .build()+ }+ .build(),+ json = Json { ignoreUnknownKeys = true }+ )++ val result = service.getVodFiles(+ stalkerSession(),+ stalkerProfile(),+ movieId = "568068"+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(requestedAction).isEqualTo("get_ordered_list")+ assertThat(requestedMovieId).isEqualTo("568068")+ assertThat(requestedType).isEqualTo("vod")+ assertThat(requestedSeasonId).isEqualTo("0")+ assertThat(requestedEpisodeId).isEqualTo("0")+ assertThat(requestedRow).isEqualTo("0")+ assertThat(requestedJsHttpRequest).isEqualTo("1-xml")+ val files = (result as Result.Success).data+ assertThat(files).hasSize(1)+ assertThat(files.first().id).isEqualTo("3199303")+ }+@Testfun getVodStreamsPage_treats_199_as_incomplete_and_200_as_complete_when_total_is_200() = runTest {val service = OkHttpStalkerApiService(diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.ktindex 5d297445..6bc3533d 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt@@ -1355,6 +1355,204 @@ class StalkerProviderTest {assertThat(api.createLinkCalls).isEqualTo(1)}+ @Test+ fun resolvePlaybackInfo_preserves_existing_movie_resolution_without_file_lookup() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodFiles = listOf(StalkerItemRecord(id = "3199303", name = "4K"))+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG322",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.resolvePlaybackInfo(+ kind = StalkerStreamKind.MOVIE,+ descriptor = checkNotNull(+ buildStalkerPlaybackDescriptor(primaryCmd = "/media/568068.mpg")+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(api.vodFileLookupCalls).isEmpty()+ assertThat(api.createLinkCmds).containsExactly("/media/568068.mpg")+ }++ @Test+ fun resolvePlaybackInfo_uses_file_lookup_after_bare_movie_reports_nothing_to_play() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ createLinkResultsByCmd = mapOf(+ "/media/568068.mpg" to Result.error(+ "nothing_to_play",+ StalkerApiError.ContentUnavailable(portalReason = "nothing_to_play")+ ),+ "/media/file_3199303.mpg" to Result.success("http://cdn.example.com/movie.m3u8")+ ),+ vodFiles = listOf(StalkerItemRecord(id = "3199303", name = "4K"))+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG322",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.resolvePlaybackInfo(+ kind = StalkerStreamKind.MOVIE,+ descriptor = checkNotNull(+ buildStalkerPlaybackDescriptor(primaryCmd = "/media/568068.mpg")+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(api.vodFileLookupCalls).containsExactly("568068")+ assertThat(api.createLinkCmds)+ .containsExactly("/media/568068.mpg", "/media/file_3199303.mpg")+ .inOrder()+ assertThat((result as Result.Success).data.url)+ .isEqualTo("http://cdn.example.com/movie.m3u8")+ }++ @Test+ fun resolvePlaybackInfo_continues_through_failed_file_rows() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ createLinkResultsByCmd = mapOf(+ "/media/568068.mpg" to Result.error(+ "nothing_to_play",+ StalkerApiError.ContentUnavailable(portalReason = "nothing_to_play")+ ),+ "/media/file_3199303.mpg" to Result.error(+ "nothing_to_play",+ StalkerApiError.ContentUnavailable(portalReason = "nothing_to_play")+ ),+ "/media/file_3199304.mpg" to Result.success("http://cdn.example.com/movie.m3u8")+ ),+ vodFiles = listOf(+ StalkerItemRecord(id = "3199303", name = "Broken 4K"),+ StalkerItemRecord(id = "3199303", name = "Duplicate Broken 4K"),+ StalkerItemRecord(id = "3199304", name = "Working 4K")+ )+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG322",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.resolvePlaybackInfo(+ kind = StalkerStreamKind.MOVIE,+ descriptor = checkNotNull(+ buildStalkerPlaybackDescriptor(primaryCmd = "/media/568068.mpg")+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(api.createLinkCmds)+ .containsExactly(+ "/media/568068.mpg",+ "/media/file_3199303.mpg",+ "/media/file_3199304.mpg"+ )+ .inOrder()+ }++ @Test+ fun resolvePlaybackInfo_keeps_legacy_variants_before_file_fallback() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ createLinkResultsByCmd = mapOf(+ "/media/568068.mpg" to Result.error(+ "nothing_to_play",+ StalkerApiError.ContentUnavailable(portalReason = "nothing_to_play")+ ),+ "/media/legacy-568068.mpg" to Result.success("http://cdn.example.com/legacy.m3u8"),+ "/media/file_3199303.mpg" to Result.success("http://cdn.example.com/file.m3u8")+ ),+ vodFiles = listOf(StalkerItemRecord(id = "3199303", name = "4K"))+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG322",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.resolvePlaybackInfo(+ kind = StalkerStreamKind.MOVIE,+ descriptor = checkNotNull(+ buildStalkerPlaybackDescriptor(+ primaryCmd = "/media/568068.mpg",+ alternateCommands = listOf("legacy" to "/media/legacy-568068.mpg")+ )+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(api.createLinkCmds)+ .containsExactly("/media/568068.mpg", "/media/legacy-568068.mpg")+ .inOrder()+ }++ @Test+ fun resolvePlaybackInfo_retries_authentication_when_file_lookup_is_unauthorized() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodFilesResult = Result.error(+ "Portal token is invalid",+ StalkerApiError.Authorization("Portal token is invalid", portalReason = "not_valid_token")+ ),+ createLinkResultsByCmd = mapOf(+ "/media/568068.mpg" to Result.error(+ "nothing_to_play",+ StalkerApiError.ContentUnavailable(portalReason = "nothing_to_play")+ )+ )+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG322",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.resolvePlaybackInfo(+ kind = StalkerStreamKind.MOVIE,+ descriptor = StalkerPlaybackDescriptor(+ primaryMode = StalkerPlaybackMode.MULTI_CMD,+ candidates = listOf(+ StalkerCommandVariant(+ cmd = "/media/568068.mpg",+ playbackMode = StalkerPlaybackMode.LOCALHOST_CMD+ )+ )+ )+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat(api.authenticateCalls).isEqualTo(2)+ assertThat(api.vodFileLookupCalls).containsExactly("568068", "568068")+ }+@Testfun authenticate_persists_effective_learned_mag_identity() = runTest {val provider = StalkerProvider(@@ -1443,7 +1641,10 @@ class StalkerProviderTest {private val shortEpgResultsByChannel: Map<String, Result<List<StalkerProgramRecord>>> = emptyMap(),private val epgByChannel: Map<String, List<StalkerProgramRecord>> = emptyMap(),private var authenticationFailuresBeforeSuccess: Int = 0,- private val authenticationError: Throwable? = null+ private val authenticationError: Throwable? = null,+ private val vodFiles: List<StalkerItemRecord> = emptyList(),+ private val vodFilesResult: Result<List<StalkerItemRecord>>? = null,+ private val createLinkResultsByCmd: Map<String, Result<String>> = emptyMap()) : StalkerApiService {var createLinkCalls: Int = 0private set@@ -1455,6 +1656,8 @@ class StalkerProviderTest {private setval shortEpgCalls: MutableList<String> = mutableListOf()val epgCalls: MutableList<String> = mutableListOf()+ val vodFileLookupCalls: MutableList<String> = mutableListOf()+ val createLinkCmds: MutableList<String> = mutableListOf()var lastVodSearchQuery: String? = nulloverride suspend fun authenticate(profile: StalkerDeviceProfile): Result<Pair<StalkerSession, StalkerProviderProfile>> {@@ -1525,6 +1728,15 @@ class StalkerProviderTest {Result.success(StalkerPagedItems(vodPageItems, page, page, vodPageItems.size))}+ override suspend fun getVodFiles(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ movieId: String+ ): Result<List<StalkerItemRecord>> {+ vodFileLookupCalls += movieId+ return vodFilesResult ?: Result.success(vodFiles)+ }+override suspend fun getSeriesCategories(session: StalkerSession,profile: StalkerDeviceProfile@@ -1605,7 +1817,8 @@ class StalkerProviderTest {archiveEndSeconds: Long?): Result<String> {createLinkCalls += 1- return Result.success(createLinkUrl)+ createLinkCmds += cmd+ return createLinkResultsByCmd[cmd] ?: Result.success(createLinkUrl)}override fun currentCookieHeader(session: StalkerSession): String = currentCookieHeader