Skip to content

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

some stalker fixes

David Nashash93c705c7ea97
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 0be32547..ee53b98c 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
@@ -71,67 +71,81 @@ class OkHttpStalkerApiService @Inject constructor(
override suspend fun authenticate(profile: StalkerDeviceProfile): Result<Pair<StalkerSession, StalkerProviderProfile>> {
var lastError: Throwable? = null
var lockedLoadUrl: String? = null
+ val failedHandshakeLoadUrls = mutableSetOf<String>()
+ val bootstrapSessions = mutableMapOf<String, StalkerBootstrapSession>()
val authModes = candidateAuthModes(profile)
for (effectiveAuthMode in authModes) {
- if (lockedLoadUrl == null) {
- lockedLoadUrl = probeReachableLoadUrl(profile, effectiveAuthMode)
- }
for (attempt in candidateAuthAttempts(profile, effectiveAuthMode)) {
val recipeIndex = attempt.recipeIndex
val recipe = attempt.recipe
val loadUrl = attempt.loadUrl
if (lockedLoadUrl != null && lockedLoadUrl != loadUrl) {
continue
+ }
+ if (lockedLoadUrl == null && loadUrl in failedHandshakeLoadUrls) {
+ continue
}
cookieJar.clear()
val referer = StalkerUrlFactory.portalReferer(loadUrl)
val evidence = mutableListOf<String>()
val recipeEvidence = mutableListOf("recipe:${recipe.recipe.name}", "preset:${recipe.magPreset.name}")
val attemptProfile = profile.withRecipe(recipe, effectiveAuthMode)
- val handshakePayload = runCatching {
- requestJson(
- url = loadUrl,
- profile = attemptProfile,
- referer = referer,
- query = mapOf(
- "type" to "stb",
- "action" to "handshake",
- "token" to "",
- "JsHttpRequest" to "1-xml"
- )
- )
- }.getOrElse { error ->
- lastError = error
- continue
- }
- evidence += "handshake"
- val token = handshakePayload.findString("token")
- ?.takeIf { it.isNotBlank() }
- ?: run {
- lastError = IOException("Portal handshake did not return a token.")
- continue
- }
- lockedLoadUrl = loadUrl
-
- if (recipe.authMode.requiresCredentials()) {
- if (attemptProfile.username.isBlank()) {
- lastError = IOException("Portal requires account credentials for this connection.")
- continue
- }
- val authPayload = runCatching {
- requestCredentialAuth(
+ val bootstrapSessionKey = "${effectiveAuthMode.name}|$loadUrl"
+ var bootstrapSession = bootstrapSessions[bootstrapSessionKey]
+ val token = bootstrapSession?.token ?: run {
+ val handshakePayload = runCatching {
+ requestJson(
url = loadUrl,
profile = attemptProfile,
referer = referer,
- token = token,
- allowAlternateEndpointRetry = false
+ query = mapOf(
+ "type" to "stb",
+ "action" to "handshake",
+ "token" to "",
+ "JsHttpRequest" to "1-xml"
+ )
)
}.getOrElse { error ->
+ failedHandshakeLoadUrls += loadUrl
lastError = error
continue
}
+ handshakePayload.findString("token")
+ ?.takeIf { it.isNotBlank() }
+ ?: run {
+ lastError = IOException("Portal handshake did not return a token.")
+ continue
+ }
+ }
+ evidence += "handshake"
+ lockedLoadUrl = loadUrl
+ if (bootstrapSession == null) {
+ bootstrapSession = StalkerBootstrapSession(token)
+ bootstrapSessions[bootstrapSessionKey] = bootstrapSession
+ }
+
+ if (recipe.authMode.requiresCredentials()) {
+ if (!bootstrapSession.credentialAuthenticated) {
+ if (attemptProfile.username.isBlank()) {
+ lastError = IOException("Portal requires account credentials for this connection.")
+ continue
+ }
+ val authPayload = runCatching {
+ requestCredentialAuth(
+ url = loadUrl,
+ profile = attemptProfile,
+ referer = referer,
+ token = token,
+ allowAlternateEndpointRetry = false
+ )
+ }.getOrElse { error ->
+ lastError = error
+ continue
+ }
+ authPayload.ensureNoPortalError()
+ bootstrapSession.credentialAuthenticated = true
+ }
evidence += "do_auth"
- authPayload.ensureNoPortalError()
}
var session = StalkerSession(
@@ -957,41 +971,6 @@ class OkHttpStalkerApiService @Inject constructor(
}.getOrElse { throw it }
}
- private suspend fun probeReachableLoadUrl(
- profile: StalkerDeviceProfile,
- effectiveAuthMode: StalkerAuthMode
- ): String? = withContext(Dispatchers.IO) {
- val recipe = candidateRecipes(profile, effectiveAuthMode).firstOrNull() ?: return@withContext null
- val attemptProfile = profile.withRecipe(recipe, effectiveAuthMode)
- val handshakeQuery = mapOf(
- "type" to "stb",
- "action" to "handshake",
- "token" to "",
- "JsHttpRequest" to "1-xml"
- )
- orderedLoadUrlCandidates(profile, recipe).firstOrNull { loadUrl ->
- val fullUrl = buildUrl(loadUrl, prepareQuery(attemptProfile, handshakeQuery))
- val request = Request.Builder()
- .url(fullUrl)
- .header("User-Agent", attemptProfile.userAgent)
- .header("X-User-Agent", attemptProfile.xUserAgent)
- .header("Referer", StalkerUrlFactory.portalReferer(loadUrl))
- .header("Accept", "*/*")
- .header("Cookie", buildCookieHeader(fullUrl, attemptProfile))
- .applyStalkerHeaderOverrides(
- headerOverrides = attemptProfile.headerOverrides,
- preserveUserAgent = attemptProfile.advancedOptions.apiUserAgent.isNotBlank()
- )
- .get()
- .build()
- runCatching {
- stalkerHttpClientFor(attemptProfile).newCall(request).execute().use { response ->
- response.code == 200
- }
- }.getOrDefault(false)
- }
- }
-
private fun executeJsonRequest(request: Request, action: String?, profile: StalkerDeviceProfile): JsonElement {
return stalkerHttpClientFor(profile).newCall(request).execute().use { response ->
captureResponseCookies(response)
@@ -2373,6 +2352,11 @@ class OkHttpStalkerApiService @Inject constructor(
val loadUrl: String
)
+ private data class StalkerBootstrapSession(
+ val token: String,
+ var credentialAuthenticated: Boolean = false
+ )
+
private fun endpointPreferenceFor(loadUrl: String): StalkerEndpointPreference =
when {
loadUrl.lowercase(Locale.ROOT).endsWith("/portal.php") -> StalkerEndpointPreference.PORTAL
@@ -2533,9 +2517,7 @@ internal fun buildStalkerDeviceProfile(
headerOverrides = headerOverrides
).orEmpty()
}
- val playerUserAgent = advancedOptions.playerUserAgent.trim().ifBlank {
- apiUserAgent
- }
+ val playerUserAgent = advancedOptions.playerUserAgent.trim()
return StalkerDeviceProfile(
portalUrl = portalUrl,
macAddress = normalizedMac,
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
index 3ba5fafa..153d6041 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
@@ -449,7 +449,7 @@ class StalkerProvider(
StalkerPlaybackInfo(
url = candidate,
headers = buildPlaybackHeaders(session, profile, candidate),
- userAgent = resolvePlaybackUserAgent(profile),
+ userAgent = resolveDirectPlaybackUserAgent(profile),
allowInvalidSsl = true,
proxyHost = profile.advancedOptions.proxy?.host.orEmpty(),
proxyPort = profile.advancedOptions.proxy?.port,
@@ -917,6 +917,18 @@ class StalkerProvider(
return profile.playerUserAgent.ifBlank { DEFAULT_PLAYER_USER_AGENT }
}
+ private fun resolveDirectPlaybackUserAgent(profile: StalkerDeviceProfile): String? {
+ profile.advancedOptions.playerUserAgent.trim().takeIf { it.isNotBlank() }?.let { return it }
+ parseStalkerHeaderOverrides(profile.advancedOptions.playerHeaders).entries.firstOrNull { (name, _) ->
+ name.equals("User-Agent", ignoreCase = true)
+ }?.let { (_, value) -> return value }
+ profile.headerOverrides.entries.firstOrNull { (name, _) ->
+ name.equals("User-Agent", ignoreCase = true)
+ }?.let { (_, value) -> return value }
+ profile.playerUserAgent.takeIf { it.isNotBlank() }?.let { return it }
+ return profile.userAgent.ifBlank { DEFAULT_PLAYER_USER_AGENT }
+ }
+
private fun buildPlaybackHostHeader(url: String): String? {
val uri = runCatching { URI(url) }.getOrNull() ?: return null
val host = uri.host?.trim()?.takeIf { it.isNotBlank() } ?: return null
@@ -1519,6 +1531,7 @@ class StalkerProvider(
signature.trim().uppercase(Locale.ROOT)
private fun authCacheKey(): String = listOf(
+ System.identityHashCode(api).toString(),
providerId.toString(),
StalkerUrlFactory.normalizePortalUrl(portalUrl),
normalizedMacAddress(),
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalReplayHarnessTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalReplayHarnessTest.kt
index 33b0178e..51ee4a27 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalReplayHarnessTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalReplayHarnessTest.kt
@@ -79,7 +79,7 @@ class StalkerPortalReplayHarnessTest {
.isEqualTo(fixture.expected.authMode)
assertWithFixture(path, authSuccess.data.first.portalProfile.name)
.isEqualTo(fixture.expected.portalProfile)
- assertThat(authSuccess.data.first.bootstrapEvidence)
+ assertWithMessage(path).that(authSuccess.data.first.bootstrapEvidence)
.containsExactlyElementsIn(fixture.expected.bootstrapEvidence)
.inOrder()
fixture.expected.portalFingerprint?.let { expectedFingerprint ->
@@ -202,7 +202,11 @@ class StalkerPortalReplayHarnessTest {
requestedActions += action
val key = "$method:$action"
val scripted = responsesByAction[key]?.removeFirstOrNull()
- ?: error("Missing replay response for $key in fixture ${fixture.name}")
+ ?: error(
+ "Missing replay response for $key in fixture ${fixture.name}; " +
+ "path=${request.url.encodedPath}; " +
+ "requested=${requestedActions.joinToString(",")}"
+ )
val builder = Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
diff --git a/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json b/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json
index 1d259530..4d2472b3 100644
--- a/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json
+++ b/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json
@@ -11,9 +11,6 @@
{ "action": "handshake", "body": "{\"js\":{\"token\":\"token-archive-fallback-a\"}}" },
{ "action": "do_auth", "method": "POST", "body": "{\"js\":{\"status\":1}}" },
{ "action": "get_profile", "body": "" },
- { "action": "get_profile", "body": "" },
- { "action": "handshake", "body": "{\"js\":{\"token\":\"token-archive-fallback-b\"}}" },
- { "action": "do_auth", "method": "POST", "body": "{\"js\":{\"status\":1}}" },
{ "action": "get_profile", "body": "{\"js\":{\"id\":\"504\",\"name\":\"Archive Fallback\",\"status\":\"1\",\"auth_access\":true}}" },
{ "action": "get_main_info", "body": "{\"js\":{\"id\":\"504\",\"name\":\"Archive Fallback\",\"status\":\"1\",\"auth_access\":true}}" },
{ "action": "get_localization", "body": "{\"js\":{\"lang\":\"en\",\"timezone\":\"UTC\"}}" },
@@ -28,7 +25,7 @@
"bootstrapRecipe": "PORTAL_PREFERRED",
"recipeEvidence": ["recipe:PORTAL_PREFERRED", "preset:MAG254_STRICT", "fallback_recipe", "rediscovery_attempted"],
"bootstrapEvidence": ["handshake", "do_auth", "get_profile", "get_account_info", "get_localization"],
- "requestOrder": ["handshake", "do_auth", "get_profile", "get_profile", "handshake", "do_auth", "get_profile", "get_main_info", "get_localization", "get_all_channels", "create_link"],
+ "requestOrder": ["handshake", "do_auth", "get_profile", "get_profile", "get_main_info", "get_localization", "get_all_channels", "create_link"],
"endpointPreference": "SERVER_LOAD",
"archiveRequiresBootstrapPrep": true,
"archiveViaCreateLink": true,
diff --git a/data/src/test/resources/stalker/fixtures/archive_strict_mag.json b/data/src/test/resources/stalker/fixtures/archive_strict_mag.json
index 75d1f478..2a29ba46 100644
--- a/data/src/test/resources/stalker/fixtures/archive_strict_mag.json
+++ b/data/src/test/resources/stalker/fixtures/archive_strict_mag.json
@@ -8,8 +8,6 @@
"responses": [
{ "action": "handshake", "body": "{\"js\":{\"token\":\"token-archive-strict-a\"}}" },
{ "action": "get_profile", "body": "" },
- { "action": "get_profile", "body": "" },
- { "action": "handshake", "body": "{\"js\":{\"token\":\"token-archive-strict-b\"}}" },
{ "action": "get_profile", "body": "{\"js\":{\"id\":\"503\",\"name\":\"Archive Strict\",\"status\":\"1\",\"auth_access\":true}}" },
{ "action": "get_main_info", "body": "{\"js\":{\"id\":\"503\",\"name\":\"Archive Strict\",\"status\":\"1\",\"auth_access\":true}}" },
{ "action": "get_all_channels", "body": "{\"js\":{\"data\":[{\"id\":\"403\",\"name\":\"Archive Strict\",\"tv_genre_id\":\"12\",\"cmd\":\"ffmpeg http://localhost/ch/403_\",\"archive\":\"1\",\"allow_local_timeshift\":\"1\",\"nginx_secure_link\":\"1\"}]}}" },
@@ -23,7 +21,7 @@
"bootstrapRecipe": "LEGACY_MAG",
"recipeEvidence": ["recipe:LEGACY_MAG", "preset:MAG250_LEGACY", "fallback_recipe", "rediscovery_attempted"],
"bootstrapEvidence": ["handshake", "get_profile", "get_account_info"],
- "requestOrder": ["handshake", "get_profile", "get_profile", "handshake", "get_profile", "get_main_info", "get_all_channels", "create_link"],
+ "requestOrder": ["handshake", "get_profile", "get_profile", "get_main_info", "get_all_channels", "create_link"],
"archiveViaCreateLink": true,
"archiveRequiresStrictCookies": false,
"streamKind": "ARCHIVE",
diff --git a/data/src/test/resources/stalker/fixtures/recipe_fallback.json b/data/src/test/resources/stalker/fixtures/recipe_fallback.json
index 8c7791f7..bc6bdeb2 100644
--- a/data/src/test/resources/stalker/fixtures/recipe_fallback.json
+++ b/data/src/test/resources/stalker/fixtures/recipe_fallback.json
@@ -11,9 +11,6 @@
{ "action": "handshake", "body": "{\"js\":{\"token\":\"token-fallback-a\"}}" },
{ "action": "do_auth", "method": "POST", "body": "{\"js\":{\"status\":1}}" },
{ "action": "get_profile", "body": "" },
- { "action": "get_profile", "body": "" },
- { "action": "handshake", "body": "{\"js\":{\"token\":\"token-fallback-b\"}}" },
- { "action": "do_auth", "method": "POST", "body": "{\"js\":{\"status\":1}}" },
{ "action": "get_profile", "body": "{\"js\":{\"id\":\"99\",\"name\":\"Recovered\",\"status\":\"1\",\"auth_access\":true}}" },
{ "action": "get_main_info", "body": "{\"js\":{\"id\":\"99\",\"name\":\"Recovered\",\"status\":\"1\",\"auth_access\":true}}" },
{ "action": "get_localization", "body": "{\"js\":{\"lang\":\"en\",\"timezone\":\"UTC\"}}" },
@@ -30,6 +27,6 @@
"cookieMode": "CREATE_LINK",
"playbackBackendHint": "TEMP_LINK_STRICT",
"bootstrapEvidence": ["handshake", "do_auth", "get_profile", "get_account_info", "get_localization"],
- "requestOrder": ["handshake", "do_auth", "get_profile", "get_profile", "handshake", "do_auth", "get_profile", "get_main_info", "get_localization"]
+ "requestOrder": ["handshake", "do_auth", "get_profile", "get_profile", "get_main_info", "get_localization"]
}
}
diff --git a/data/src/test/resources/stalker/fixtures/strict_mag_legacy.json b/data/src/test/resources/stalker/fixtures/strict_mag_legacy.json
index dd3e7865..2f7dbc35 100644
--- a/data/src/test/resources/stalker/fixtures/strict_mag_legacy.json
+++ b/data/src/test/resources/stalker/fixtures/strict_mag_legacy.json
@@ -8,8 +8,6 @@
"responses": [
{ "action": "handshake", "body": "{\"js\":{\"token\":\"token-legacy-a\"}}" },
{ "action": "get_profile", "body": "" },
- { "action": "get_profile", "body": "" },
- { "action": "handshake", "body": "{\"js\":{\"token\":\"token-legacy-b\"}}" },
{ "action": "get_profile", "body": "{\"js\":{\"id\":\"88\",\"name\":\"Legacy\",\"status\":\"1\",\"auth_access\":true}}" },
{ "action": "get_main_info", "body": "{\"js\":{\"id\":\"88\",\"name\":\"Legacy\",\"status\":\"1\",\"auth_access\":true}}" }
],
@@ -21,6 +19,6 @@
"bootstrapRecipe": "LEGACY_MAG",
"recipeEvidence": ["recipe:LEGACY_MAG", "preset:MAG250_LEGACY", "fallback_recipe", "rediscovery_attempted"],
"bootstrapEvidence": ["handshake", "get_profile", "get_account_info"],
- "requestOrder": ["handshake", "get_profile", "get_profile", "handshake", "get_profile", "get_main_info"]
+ "requestOrder": ["handshake", "get_profile", "get_profile", "get_main_info"]
}
}