Skip to content

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

fix: narrow Stalker soft-throttle detection

David Nashashf04b8b7352f4
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.kt
index c66083e1..35645562 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
@@ -212,20 +212,22 @@ class OkHttpStalkerApiService @Inject constructor(
val token = handshakePayload.findString("token")
?.takeIf { it.isNotBlank() }
?: run {
- // A 200 without a token is a soft throttle. Stop discovery rather
- // than firing more handshakes into the portal limiter.
- val throttled = StalkerApiError.RateLimited(
- message = "Portal handshake did not return a token.",
- httpStatus = 200
- )
+ // A tokenless 200 is ambiguous: it may be a soft throttle, but it
+ // may also be an incompatible endpoint or a portal response that
+ // needs another discovery recipe. Explicit throttle markers are
+ // handled by ensureNoPortalError(); keep the generic case eligible
+ // for endpoint/recipe fallback.
+ val missingToken = IOException("Portal handshake did not return a token.")
+ failedHandshakeAttempts += handshakeAttemptKey
StalkerTelemetry.authenticationAttempt(
profile.providerId,
recipe.compatibilityProfileId,
endpointFamily,
"HANDSHAKE",
- authenticationFailureOutcome(throttled)
+ authenticationFailureOutcome(missingToken)
)
- return Result.error(throttled.message.orEmpty(), throttled)
+ lastError = preferredAuthenticationFailure(lastError, missingToken)
+ continue
}
val handshakeRandom = handshakePayload.findString("random").orEmpty()
resolvedLoadUrl(loadUrl, attemptProfile)?.let { redirectedLoadUrl ->
@@ -2101,6 +2103,7 @@ class OkHttpStalkerApiService @Inject constructor(
if (findBoolean("not_valid_token") == true) {
throw invalidTokenError()
}
+ explicitRateLimitError()?.let { throw it }
// Some Ministra/Stalker families return workflow failures as a scalar `js`
// payload instead of the usual `{ "js": { "error": ... } }` envelope.
// Treat that scalar as a portal outcome so create_link cannot degrade
@@ -2121,6 +2124,50 @@ class OkHttpStalkerApiService @Inject constructor(
message?.let { authorizationMessage(it)?.let { error -> throw error } }
}
+ /**
+ * A tokenless HTTP 200 is not, by itself, evidence of throttling. Only classify a
+ * response as a soft rate limit when the portal provides an explicit signal.
+ */
+ private fun JsonElement.explicitRateLimitError(): StalkerApiError.RateLimited? {
+ val payload = payloadObjectOrNull() ?: return null
+ val message = listOf("error", "msg", "message", "reason", "detail")
+ .mapNotNull { key -> payload.findString(key) }
+ .firstOrNull()
+ val retryAfterMillis = payload.retryAfterMillisOrNull()
+ val hasRetryAfter = listOf(
+ "retry_after",
+ "retry-after",
+ "retryAfter",
+ "retry_after_ms",
+ "retryAfterMillis"
+ ).any { key -> payload.containsKey(key) }
+ val hasRateLimitFlag = listOf("rate_limit", "rate_limited", "ratelimited", "throttled", "throttle")
+ .any { key ->
+ payload.findBoolean(key) == true ||
+ payload.findString(key)?.lowercase(Locale.ROOT) in setOf(
+ "rate_limit",
+ "rate_limited",
+ "ratelimited",
+ "throttled",
+ "throttle",
+ "true",
+ "1",
+ "yes"
+ )
+ }
+ val hasRateLimitCode = listOf("status", "code", "http_status", "httpStatus")
+ .any { key -> payload.findString(key)?.toIntOrNull() == 429 }
+ val hasRateLimitText = message?.isExplicitRateLimitMessage() == true
+ if (!hasRetryAfter && !hasRateLimitFlag && !hasRateLimitCode && !hasRateLimitText) {
+ return null
+ }
+ return StalkerApiError.RateLimited(
+ message = message ?: "Portal handshake was rate limited.",
+ httpStatus = 200,
+ retryAfterMillis = retryAfterMillis
+ )
+ }
+
/**
* Ministra reports workflow failures as HTTP 200 with a `status`/`msg`/`block_msg`
* envelope instead of an HTTP error or an `error` field. Well-known examples:
@@ -2380,6 +2427,8 @@ class OkHttpStalkerApiService @Inject constructor(
if (raw.isBlank() || isPlaceholderErrorValue(raw)) return null
val normalized = raw.lowercase(Locale.ROOT)
return when {
+ raw.isExplicitRateLimitMessage() ->
+ StalkerApiError.RateLimited(message = raw, httpStatus = 200)
normalized == "nothing_to_play" || normalized.contains("nothing to play") ->
StalkerApiError.ContentUnavailable(portalReason = "nothing_to_play")
listOf("not valid mac", "invalid mac").any(normalized::contains) ->
@@ -3605,6 +3654,38 @@ class OkHttpStalkerApiService @Inject constructor(
return element.contentOrNull?.trim()?.toIntOrNull()
}
+ private fun JsonObject.retryAfterMillisOrNull(): Long? {
+ val milliseconds = listOf("retry_after_ms", "retryAfterMillis")
+ .firstOrNull { key -> containsKey(key) }
+ ?.let { key -> findString(key) }
+ ?.toLongOrNull()
+ ?.coerceAtLeast(0L)
+ if (milliseconds != null) return milliseconds
+ return listOf("retry_after", "retry-after", "retryAfter")
+ .firstOrNull { key -> containsKey(key) }
+ ?.let { key -> findString(key) }
+ ?.toLongOrNull()
+ ?.coerceAtLeast(0L)
+ ?.times(1000L)
+ }
+
+ private fun String.isExplicitRateLimitMessage(): Boolean {
+ val normalized = lowercase(Locale.ROOT)
+ .replace('_', ' ')
+ .replace('-', ' ')
+ return normalized == "429" || listOf(
+ "rate limit",
+ "rate limited",
+ "ratelimited",
+ "too many requests",
+ "request throttled",
+ "throttled",
+ "throttle",
+ "http 429",
+ "status 429"
+ ).any(normalized::contains)
+ }
+
private fun GsonJsonObject.findString(key: String): String? {
val element = get(key) ?: return null
if (!element.isJsonPrimitive) return null
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.kt
index 94b9fd82..6e232f4e 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
@@ -2953,7 +2953,7 @@ class OkHttpStalkerApiServiceTest {
}
@Test
- fun authenticate_tokenlessHandshake_abortsAsRateLimitedWithoutFurtherHandshakes() = runTest {
+ fun authenticate_explicitTokenlessThrottle_abortsAsRateLimitedWithoutFurtherHandshakes() = runTest {
val requestedActions = mutableListOf<String>()
val service = OkHttpStalkerApiService(
okHttpClient = OkHttpClient.Builder()
@@ -2965,7 +2965,10 @@ class OkHttpStalkerApiServiceTest {
.protocol(Protocol.HTTP_1_1)
.code(200)
.message("OK")
- .body("""{"js":{}}""".toResponseBody("application/json".toMediaType()))
+ .body(
+ """{"js":{"msg":"Too many requests","retry_after":30}}"""
+ .toResponseBody("application/json".toMediaType())
+ )
.build()
}
.build(),
@@ -2975,10 +2978,50 @@ class OkHttpStalkerApiServiceTest {
val result = service.authenticate(stalkerProfile())
assertThat(result).isInstanceOf(Result.Error::class.java)
- assertThat((result as Result.Error).exception).isInstanceOf(StalkerApiError.RateLimited::class.java)
+ val error = (result as Result.Error).exception
+ assertThat(error).isInstanceOf(StalkerApiError.RateLimited::class.java)
+ assertThat((error as StalkerApiError.RateLimited).retryAfterMillis).isEqualTo(30_000L)
assertThat(requestedActions).containsExactly("handshake")
}
+ @Test
+ fun authenticate_genericTokenlessHandshake_continuesEndpointAndRecipeDiscovery() = runTest {
+ val requestedActions = mutableListOf<String>()
+ var handshakeCount = 0
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ requestedActions += action
+ val body = when (action) {
+ "handshake" -> if (++handshakeCount == 1) {
+ """{"js":{}}"""
+ } else {
+ """{"js":{"token":"token-123","random":"abc"}}"""
+ }
+ "get_profile" -> """{"js":{"status":1,"name":"Living Room"}}"""
+ else -> """{"js":{}}"""
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ assertThat(handshakeCount).isAtLeast(2)
+ assertThat(requestedActions).contains("get_profile")
+ }
+
@Test
fun restoreSession_rehydratesServerCookiesForNormalApiRequests() = runTest {
var requestCookie = ""
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 49dfab2a..bdf7a4fc 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -20,7 +20,8 @@ All notable product changes are recorded in this document.
- Fixed grouped VOD browse pagination and infinite scroll by using cursor windows, deduplicating before offset/limit application, and handling zero-timestamp catalog entries consistently.
- Fixed provider configuration decoding after typed-provider migrations that omitted the embedded configuration type, preserving access to existing provider settings and credentials.
- Added measured frame-rate and stream-bitrate diagnostics for IPTV playback, including MPEG-TS streams that omit these values from their metadata.
-- Improved Stalker authentication resilience by stopping repeated handshakes after soft throttles, reusing short-lived encrypted sessions across provider instances and process restarts, and restoring session cookies for resumed API requests.
+- Improved Stalker authentication resilience by stopping repeated handshakes after explicit soft-throttle signals, reusing short-lived encrypted sessions across provider instances and process restarts, and restoring session cookies for resumed API requests.
+- Fixed Stalker compatibility discovery treating every tokenless HTTP 200 response as a rate limit; generic endpoint or recipe responses now continue through fallback discovery.
- Fixed Stalker VOD category layout drift by retargeting stale stored category types before synchronization instead of forcing an unnecessary catalog re-download.
## [1.0.17]