From fc75b2c5409c2a48d7cd6c49d50eba4b93d9b05f Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:55:59 +0500 Subject: [PATCH 1/2] Android TV: take kkphim's ads out and sign asilmedia's fayllar1 files The backend sends a dropSegments rule for kkphim and a signer for asilmedia's fayllar1 files, and the TV dropped both on the way to the player: kkphim played its spliced ads, and fayllar1 was asked for the bare file, which it refuses. Both now reach the player as they do on the phone. A source with a rule goes through the local proxy, which strips the matching segments from each media playlist; a signed file is signed on the device, with the player's own User-Agent, before it plays. Ported from hls_segment_filter.dart and url_signer.dart. --- .../sozo_tv/data/extensions/ExtModels.kt | 5 + .../sozo_tv/data/model/VodMovieResponse.kt | 1 + .../sozo_tv/engine/player/HlsSegmentFilter.kt | 51 +++++++++ .../sozo_tv/engine/player/LocalHlsProxy.kt | 11 +- .../saikou/sozo_tv/engine/player/UrlSigner.kt | 103 ++++++++++++++++++ .../sozo_tv/engine/server/ServerHost.kt | 2 + .../sozo_tv/parser/models/ShowResponse.kt | 2 + .../sozo_tv/parser/sources/ExtensionParser.kt | 2 + .../activities/WatchPartyActivity.kt | 8 +- .../screens/play/SeriesPlayerScreen.kt | 1 + .../viewmodel/PlayAnimeViewModel.kt | 9 +- .../sozo_tv/player/HlsSegmentFilterTest.kt | 48 ++++++++ .../saikou/sozo_tv/player/UrlSignerTest.kt | 68 ++++++++++++ 13 files changed, 304 insertions(+), 7 deletions(-) create mode 100644 app/src/main/java/com/saikou/sozo_tv/engine/player/HlsSegmentFilter.kt create mode 100644 app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt create mode 100644 app/src/test/java/com/saikou/sozo_tv/player/HlsSegmentFilterTest.kt create mode 100644 app/src/test/java/com/saikou/sozo_tv/player/UrlSignerTest.kt diff --git a/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtModels.kt b/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtModels.kt index 663318ab..33deaced 100644 --- a/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtModels.kt +++ b/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtModels.kt @@ -136,6 +136,9 @@ data class ExtVideoSource( /** Separate audio renditions that belong with this video (CloudStream `audioTracks`). */ val audioTracks: List = emptyList(), val drm: String? = null, + /** Regex for ad segments the local proxy takes out of the playlist. */ + val dropSegments: String? = null, + val signer: String? = null, // raw JSON, see UrlSigner ) data class ExtAudioTrack( @@ -369,6 +372,8 @@ internal object ExtParser { sniff = (s.optJSONObject("sniff") ?: o.optJSONObject("sniff"))?.toString(), localProxy = s.optJSONObject("localProxy")?.toString(), requestTransform = s.optJSONObject("requestTransform")?.toString(), + dropSegments = s.strOrNull("dropSegments"), + signer = s.optJSONObject("signer")?.toString(), // PluginHost emits these for dual-audio releases; dropping them here left the // player with one track and nothing to switch to. audioTracks = s.optJSONArray("audioTracks")?.let { arr -> diff --git a/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt b/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt index 9f73f8bc..6a5f6deb 100644 --- a/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt +++ b/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt @@ -15,6 +15,7 @@ data class VodMovieResponse( val useLocalProxy: Boolean = false, val localProxyJson: String? = null, val requestTransformJson: String? = null, + val dropSegments: String? = null, /** Separate audio renditions the player merges in alongside [urlobj]. */ val audioTracks: List = emptyList(), val drm: String? = null, diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/HlsSegmentFilter.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/HlsSegmentFilter.kt new file mode 100644 index 00000000..5dcd3a67 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/HlsSegmentFilter.kt @@ -0,0 +1,51 @@ +package com.saikou.sozo_tv.engine.player + +/** + * Takes the segments a source's `dropSegments` rule matches out of a media playlist, with their + * timing. Port of the phone app's hls_segment_filter.dart. + * + * Some catalogues (kkphim) splice an ad into every stream as ordinary segments between two + * discontinuities; only the path gives it away. The two discontinuities around it become one, + * since the film's timestamps still jump there. A master playlist, or one the rule would empty, + * comes back as it is. + */ +object HlsSegmentFilter { + + /** The server's rule, or null when there is none or it does not compile. */ + fun ruleFrom(pattern: String?): Regex? { + if (pattern.isNullOrEmpty()) return null + return runCatching { Regex(pattern) }.getOrNull() + } + + fun drop(playlist: String, drop: Regex): String { + if (playlist.contains("#EXT-X-STREAM-INF")) return playlist + val out = mutableListOf() + // From an #EXTINF up to its uri, which decides whether they stay. + val pending = mutableListOf() + var discontinuity = false + var kept = 0 + var dropped = 0 + for (line in playlist.split('\n')) { + val s = line.trim() + when { + s == "#EXT-X-DISCONTINUITY" -> discontinuity = true + s.startsWith("#EXTINF") || pending.isNotEmpty() && s.startsWith("#") -> pending.add(line) + s.isEmpty() || s.startsWith("#") -> out.add(line) + drop.containsMatchIn(s) -> { + pending.clear() + dropped++ + } + else -> { + if (discontinuity) out.add("#EXT-X-DISCONTINUITY") + discontinuity = false + out.addAll(pending) + out.add(line) + pending.clear() + kept++ + } + } + } + if (dropped == 0 || kept == 0) return playlist + return out.joinToString("\n") + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/LocalHlsProxy.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/LocalHlsProxy.kt index 3c08f881..657afd6f 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/player/LocalHlsProxy.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/LocalHlsProxy.kt @@ -19,7 +19,8 @@ import java.util.concurrent.ConcurrentHashMap * variant playlists, segments, keys โ€” through the same OkHttp client (which shares the WebView * cookie jar), so IP + cookies + signed headers match end to end. * - * Activates only when a source arrives with `useLocalProxy: true`. For uzmovi it also applies the + * Activates when a source arrives with `useLocalProxy: true`, or with a `dropSegments` rule whose + * ad segments it takes out of each media playlist. For uzmovi it also applies the * `uzmovi-rc4-v1` request transform (RC4-signed X-ATT-DeviceId / X-Match / X-Path + randomized URL). */ class LocalHlsProxy(private val client: OkHttpClient) { @@ -81,13 +82,15 @@ class LocalHlsProxy(private val client: OkHttpClient) { headers: Map, localProxy: JSONObject, requestTransform: JSONObject, + dropSegments: String? = null, ): String { ensureStarted() val id = randomId() val parsed = URI(upstreamUrl) require(parsed.scheme in setOf("http", "https") && parsed.host != null) sessions[id] = Session(headers = HashMap(headers), - transform = RequestTransform.fromMaps(localProxy, requestTransform)) + transform = RequestTransform.fromMaps(localProxy, requestTransform), + dropSegments = HlsSegmentFilter.ruleFrom(dropSegments)) return "http://127.0.0.1:$port/hls/$id/${b64UrlEncode(upstreamUrl)}" } @@ -150,7 +153,7 @@ class LocalHlsProxy(private val client: OkHttpClient) { } } else { if (!text.trimStart().startsWith("#EXTM3U")) return error(502) - rewriteM3u8(text, "/hls/$sid", effectiveUrl) + rewriteM3u8(sess.dropSegments?.let { HlsSegmentFilter.drop(text, it) } ?: text, "/hls/$sid", effectiveUrl) } return NanoHTTPD.newFixedLengthResponse(statusOf(200), if (isDash) "application/dash+xml" else "application/vnd.apple.mpegurl", rewritten) @@ -205,7 +208,7 @@ class LocalHlsProxy(private val client: OkHttpClient) { private fun b64UrlDecode(s: String): String = String(Base64.decode(s, Base64.URL_SAFE), Charsets.UTF_8) - private class Session(val headers: Map, val transform: RequestTransform?) + private class Session(val headers: Map, val transform: RequestTransform?, val dropSegments: Regex?) private class TransformedRequest(val url: String, val headers: Map) diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt new file mode 100644 index 00000000..92980633 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt @@ -0,0 +1,103 @@ +package com.saikou.sozo_tv.engine.player + +import com.saikou.sozo_tv.engine.network.ExtensionDns +import com.saikou.sozo_tv.utils.SOZO_USER_AGENT +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import org.json.JSONArray +import org.json.JSONObject +import org.json.JSONTokener +import java.net.URLDecoder +import java.util.concurrent.TimeUnit + +/** + * A source's file that the device has to sign for itself before playing. Port of the phone app's + * url_signer.dart. + * + * asilmedia's fayllar1 hands out a file only through a signed URL whose token is bound to the + * User-Agent and IP that asked for it, so the server cannot sign on the TV's behalf. It sends + * where to ask, under which query parameter the file goes, and with what headers; the answer is + * a JSON map from the file as sent to its signed URL. + */ +class UrlSigner( + val url: String, + val param: String, + val headers: Map = emptyMap(), +) { + + /** + * The signed URL for [file], asked with [playerHeaders]' User-Agent, which the token is bound + * to. Null when the host would not sign it; the caller then plays the file as it was. + */ + fun sign(file: String, playerHeaders: Map, client: OkHttpClient = defaultClient): String? { + val ua = playerHeaders.entries.firstOrNull { it.key.equals("User-Agent", true) }?.value + ?: SOZO_USER_AGENT + val key = "$file\u0000$ua" + val now = System.currentTimeMillis() + synchronized(cache) { + cache[key]?.takeIf { now - it.second < KEEP_MS }?.let { return it.first } + } + return runCatching { + val request = Request.Builder().url(requestUrl(file)).apply { + headers.forEach { (k, v) -> header(k, v) } + header("User-Agent", ua) + }.build() + client.newCall(request).execute().use { res -> + if (res.code != 200) return null + signedUrlFrom(res.body?.string().orEmpty()) + } + }.getOrNull()?.also { signed -> + synchronized(cache) { + if (cache.size > 64) cache.clear() + cache[key] = signed to now + } + } + } + + /** Sent decoded, as the page itself sends it: the host keys its answer by the file as asked. */ + internal fun requestUrl(file: String): String = + url.toHttpUrl().newBuilder() + .setQueryParameter(param, URLDecoder.decode(file.replace("+", "%2B"), "UTF-8")) + .build().toString() + + companion object { + private const val KEEP_MS = 20 * 60 * 1000L + + // Tokens expire, so a retry after that must ask again. + private val cache = HashMap>() + + private val defaultClient: OkHttpClient by lazy { + OkHttpClient.Builder() + .dns(ExtensionDns.dns) + .callTimeout(8, TimeUnit.SECONDS) + .build() + } + + fun fromJson(json: String?): UrlSigner? { + if (json.isNullOrBlank()) return null + val o = runCatching { JSONObject(json) }.getOrNull() ?: return null + val url = o.opt("url") as? String + val param = o.opt("param") as? String + if (url.isNullOrEmpty() || param.isNullOrEmpty()) return null + val raw = o.optJSONObject("headers") + val headers = raw?.keys()?.asSequence() + ?.filter { !raw.isNull(it) } + ?.associateWith { raw.get(it).toString() } + .orEmpty() + return UrlSigner(url, param, headers) + } + + internal fun signedUrlFrom(body: String): String? { + val signed = when (val v = runCatching { JSONTokener(body).nextValue() }.getOrNull()) { + is JSONObject -> v.keys().asSequence().map { v.opt(it) }.filterIsInstance().firstOrNull() + is JSONArray -> (0 until v.length()).map { v.opt(it) }.filterIsInstance().firstOrNull() + is String -> v + else -> null + } + return signed?.takeIf { it.startsWith("http") } + } + + internal fun clearCache() = synchronized(cache) { cache.clear() } + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt b/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt index 1516596f..01c33a5f 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt @@ -431,6 +431,8 @@ class ServerHost( if (s.optBoolean("useLocalProxy", false)) put("useLocalProxy", true) s.optJSONObject("localProxy")?.let { put("localProxy", it) } s.optJSONObject("requestTransform")?.let { put("requestTransform", it) } + s.optString("dropSegments").takeIf { it.isNotEmpty() }?.let { put("dropSegments", it) } + s.optJSONObject("signer")?.let { put("signer", it) } // Headless-WebView sniff directive (embed pages whose manifest is // only produced by the page's own JS) โ€” forward raw, per source // or inherited from the media level. diff --git a/app/src/main/java/com/saikou/sozo_tv/parser/models/ShowResponse.kt b/app/src/main/java/com/saikou/sozo_tv/parser/models/ShowResponse.kt index 38cf6e1b..6ae80eb3 100644 --- a/app/src/main/java/com/saikou/sozo_tv/parser/models/ShowResponse.kt +++ b/app/src/main/java/com/saikou/sozo_tv/parser/models/ShowResponse.kt @@ -30,6 +30,8 @@ data class VideoOption( var useLocalProxy: Boolean = false, var localProxy: String? = null, var requestTransform: String? = null, + var dropSegments: String? = null, + var signer: String? = null, var useWebViewSniff: Boolean = false, var sniff: String? = null, /** Separate audio renditions merged into playback alongside [videoUrl]. */ diff --git a/app/src/main/java/com/saikou/sozo_tv/parser/sources/ExtensionParser.kt b/app/src/main/java/com/saikou/sozo_tv/parser/sources/ExtensionParser.kt index 6f61d118..90628737 100644 --- a/app/src/main/java/com/saikou/sozo_tv/parser/sources/ExtensionParser.kt +++ b/app/src/main/java/com/saikou/sozo_tv/parser/sources/ExtensionParser.kt @@ -136,6 +136,8 @@ class ExtensionParser : BaseParser() { useLocalProxy = s.useLocalProxy, localProxy = s.localProxy, requestTransform = s.requestTransform, + dropSegments = s.dropSegments, + signer = s.signer, useWebViewSniff = s.useWebViewSniff, sniff = s.sniff, audioTracks = s.audioTracks.map { AudioTrackRef(it.url, media.headers + it.headers) }, diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt index 06cc2195..be6e7ee0 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt @@ -216,9 +216,13 @@ class WatchPartyActivity : AppCompatActivity() { val sniffed = WebViewStreamExtractor.extract(this@WatchPartyActivity, url, headers) ?: error("Could not open the embedded player") url = sniffed.url; headers = sniffed.headers; type = sniffed.playType } - if (source.useLocalProxy || StreamRequestRules.needsManifestProxy(url)) { + UrlSigner.fromJson(source.signer)?.let { signer -> + withContext(Dispatchers.IO) { signer.sign(url, headers) }?.let { url = it } + } + if (source.useLocalProxy || source.dropSegments != null || StreamRequestRules.needsManifestProxy(url)) { url = withContext(Dispatchers.IO) { proxy.register(url, headers, - source.localProxy?.let(::JSONObject) ?: JSONObject(), source.requestTransform?.let(::JSONObject) ?: JSONObject()) } + source.localProxy?.let(::JSONObject) ?: JSONObject(), source.requestTransform?.let(::JSONObject) ?: JSONObject(), + source.dropSegments) } headers = emptyMap() } ensureActive(); if (stamp != generation) return@launch diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/screens/play/SeriesPlayerScreen.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/screens/play/SeriesPlayerScreen.kt index 06502ea6..7fec9651 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/screens/play/SeriesPlayerScreen.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/screens/play/SeriesPlayerScreen.kt @@ -1835,6 +1835,7 @@ class SeriesPlayerScreen : Fragment() { headers = vod.header, localProxy = vod.localProxyJson?.let { JSONObject(it) } ?: JSONObject(), requestTransform = vod.requestTransformJson?.let { JSONObject(it) } ?: JSONObject(), + dropSegments = vod.dropSegments, ) }.getOrDefault(vod.urlobj) } diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/viewmodel/PlayAnimeViewModel.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/viewmodel/PlayAnimeViewModel.kt index be8f754d..1682842c 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/viewmodel/PlayAnimeViewModel.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/viewmodel/PlayAnimeViewModel.kt @@ -331,6 +331,11 @@ class PlayAnimeViewModel( torrentSource = true } var headers = option.headers + com.saikou.sozo_tv.engine.player.UrlSigner.fromJson(option.signer)?.let { signer -> + val signed = withContext(Dispatchers.IO) { signer.sign(url, headers) } + if (signed != null) url = signed + else Log.w(TAG, "signing refused, playing the file as given") + } var mime = if (torrentSource) MimeTypes.VIDEO_MP4 else option.mimeTypes.ifEmpty { MimeTypes.APPLICATION_M3U8 } if (option.useWebViewSniff || @@ -365,9 +370,11 @@ class PlayAnimeViewModel( header = headers, type = mime, thumbnail = option.thumbnail ?: "", - useLocalProxy = option.useLocalProxy || com.saikou.sozo_tv.engine.player.StreamRequestRules.needsManifestProxy(url), + useLocalProxy = option.useLocalProxy || option.dropSegments != null || + com.saikou.sozo_tv.engine.player.StreamRequestRules.needsManifestProxy(url), localProxyJson = option.localProxy, requestTransformJson = option.requestTransform, + dropSegments = option.dropSegments, audioTracks = option.audioTracks, drm = option.drm, ) diff --git a/app/src/test/java/com/saikou/sozo_tv/player/HlsSegmentFilterTest.kt b/app/src/test/java/com/saikou/sozo_tv/player/HlsSegmentFilterTest.kt new file mode 100644 index 00000000..1e09672c --- /dev/null +++ b/app/src/test/java/com/saikou/sozo_tv/player/HlsSegmentFilterTest.kt @@ -0,0 +1,48 @@ +package com.saikou.sozo_tv.player + +import com.saikou.sozo_tv.engine.player.HlsSegmentFilter +import org.junit.Assert.* +import org.junit.Test + +class HlsSegmentFilterTest { + // The shape of a live KKPhim playlist, 2026-10-31. + private val playlist = + "#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-PLAYLIST-TYPE:vod\n" + + "#EXT-X-TARGETDURATION:8\n#EXT-X-MEDIA-SEQUENCE:0\n" + + "#EXTINF:4.0,\nHcTaGA8B.ts\n#EXT-X-DISCONTINUITY\n" + + "#EXTINF:4.0,\nconvertv8/R9SjR8xq.ts\n#EXT-X-DISCONTINUITY\n" + + "#EXTINF:4.0,\n8T4q13t8.ts\n#EXT-X-DISCONTINUITY\n" + + "#EXTINF:3.0,\n/v8/d61a03b1dabe537cc05ffe5c9c280f56/segment_0000.ts\n" + + "#EXTINF:2.0,\n/v8/d61a03b1dabe537cc05ffe5c9c280f56/segment_0001.ts\n" + + "#EXT-X-DISCONTINUITY\n#EXTINF:4.0,\nZFE6Zblx.ts\n#EXT-X-ENDLIST\n" + private val ad = HlsSegmentFilter.ruleFrom("^/v\\d+/[0-9a-f]{32}/")!! + + @Test fun takesTheAdAndItsTimingOutAndLeavesTheFilmWhole() { + val out = HlsSegmentFilter.drop(playlist, ad) + assertFalse(out.contains("segment_")) + assertTrue(out.contains("convertv8/R9SjR8xq.ts")) + assertEquals(4, Regex("#EXTINF").findAll(out).count()) + assertTrue(out.endsWith("ZFE6Zblx.ts\n#EXT-X-ENDLIST\n")) + } + + @Test fun theTwoDiscontinuitiesAroundTheAdBecomeOne() { + val out = HlsSegmentFilter.drop(playlist, ad) + assertEquals(3, Regex("#EXT-X-DISCONTINUITY").findAll(out).count()) + assertTrue(out.contains("8T4q13t8.ts\n#EXT-X-DISCONTINUITY\n#EXTINF:4.0,\nZFE6Zblx.ts")) + } + + @Test fun aMasterPlaylistIsNotAListOfSegments() { + val master = "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\n/v8/abc/index.m3u8\n" + assertEquals(master, HlsSegmentFilter.drop(master, Regex("."))) + } + + @Test fun aRuleThatWouldEmptyThePlaylistIsWrongNotTheFilm() { + assertEquals(playlist, HlsSegmentFilter.drop(playlist, Regex("."))) + } + + @Test fun aMissingOrBrokenRuleIsNoRule() { + assertNull(HlsSegmentFilter.ruleFrom(null)) + assertNull(HlsSegmentFilter.ruleFrom("")) + assertNull(HlsSegmentFilter.ruleFrom("(unclosed")) + } +} diff --git a/app/src/test/java/com/saikou/sozo_tv/player/UrlSignerTest.kt b/app/src/test/java/com/saikou/sozo_tv/player/UrlSignerTest.kt new file mode 100644 index 00000000..1ca7b16c --- /dev/null +++ b/app/src/test/java/com/saikou/sozo_tv/player/UrlSignerTest.kt @@ -0,0 +1,68 @@ +package com.saikou.sozo_tv.player + +import com.saikou.sozo_tv.engine.player.UrlSigner +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.Response +import okhttp3.ResponseBody.Companion.toResponseBody +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +// A file the device signs itself: asked with the player's own User-Agent, read out of the host's +// JSON map, and not asked twice. +class UrlSignerTest { + private val asked = mutableListOf() + + // Answers like fayllar-sign.php, without a network. + private val client = OkHttpClient.Builder().addInterceptor { chain -> + val req = chain.request() + asked.add(req) + val file = req.url.queryParameter("u[]").orEmpty() + val body = if (file.isEmpty()) "{}" + else JSONObject().put(file, "$file?token=abc&ua=${req.header("User-Agent")}").toString() + Response.Builder().request(req).protocol(Protocol.HTTP_1_1).code(200).message("OK") + .body(body.toResponseBody("application/json".toMediaType())).build() + }.build() + + private fun signer() = UrlSigner.fromJson( + """{"url":"https://asilmedia.org/fayllar-sign.php","param":"u[]","headers":{"Referer":"https://asilmedia.org/"}}""" + )!! + + @Before fun reset() = UrlSigner.clearCache() + + @Test fun signsWithThePlayersOwnUserAgentAndTheHostsHeaders() { + val signed = signer().sign("https://fayllar1.ru/9/Film%20720p%20O'zbek.mp4", + mapOf("user-agent" to "PlayerUA/1"), client) + assertEquals("https://fayllar1.ru/9/Film 720p O'zbek.mp4?token=abc&ua=PlayerUA/1", signed) + // Sent decoded, as the page itself sends it. + assertEquals("https://fayllar1.ru/9/Film 720p O'zbek.mp4", asked.single().url.queryParameter("u[]")) + assertEquals("https://asilmedia.org/", asked.single().header("Referer")) + } + + @Test fun asksOncePerFileAndUserAgent() { + val s = signer() + s.sign("https://fayllar1.ru/9/a.mp4", mapOf("User-Agent" to "X"), client) + s.sign("https://fayllar1.ru/9/a.mp4", mapOf("User-Agent" to "X"), client) + assertEquals(1, asked.size) + s.sign("https://fayllar1.ru/9/a.mp4", mapOf("User-Agent" to "Y"), client) + assertEquals(2, asked.size) + } + + @Test fun noSignerWithoutAUrlAndAParameter() { + assertNull(UrlSigner.fromJson("{}")) + assertNull(UrlSigner.fromJson("""{"url":"https://x"}""")) + assertNull(UrlSigner.fromJson(null)) + } + + @Test fun refusesAnAnswerThatIsNotAUrl() { + val refusing = OkHttpClient.Builder().addInterceptor { chain -> + Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(200).message("OK") + .body("""{"x":"denied"}""".toResponseBody(null)).build() + }.build() + assertNull(signer().sign("https://fayllar1.ru/9/b.mp4", emptyMap(), refusing)) + } +} From 9c13658318f093abf9ae6c76fef4750a372074a0 Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:02:32 +0500 Subject: [PATCH 2/2] Android TV: sign fayllar1 files each time they start, and let kkphim open externally again The file was signed once, when the source was built, and the signed URL was kept. A retry after the token expired sent the same dead token, so a long film that failed after a pause could not be resumed without picking the source again. The source now keeps the unsigned file and the player signs it on every start, as the phone does; the external player and downloads sign it when they are opened. History no longer stores a token bound to this device's IP and User-Agent. The ad rule no longer marks kkphim as needing the proxy, which had stopped those streams from opening in an external player. The player still routes them through the proxy to strip the ads. --- .../sozo_tv/data/model/VodMovieResponse.kt | 2 ++ .../saikou/sozo_tv/engine/player/UrlSigner.kt | 4 +++ .../sozo_tv/engine/server/ServerHost.kt | 2 +- .../activities/WatchPartyActivity.kt | 4 +-- .../screens/play/SeriesPlayerScreen.kt | 27 ++++++++++++++----- .../viewmodel/PlayAnimeViewModel.kt | 17 +++++++----- .../extensions/CloudStreamMediaTest.kt | 8 ++++++ .../saikou/sozo_tv/player/UrlSignerTest.kt | 4 +++ 8 files changed, 50 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt b/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt index 6a5f6deb..3786601a 100644 --- a/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt +++ b/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt @@ -16,6 +16,8 @@ data class VodMovieResponse( val localProxyJson: String? = null, val requestTransformJson: String? = null, val dropSegments: String? = null, + /** [urlobj] is the unsigned file; this signs it each time it is opened. See UrlSigner. */ + val signerJson: String? = null, /** Separate audio renditions the player merges in alongside [urlobj]. */ val audioTracks: List = emptyList(), val drm: String? = null, diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt index 92980633..d9f2df88 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt @@ -74,6 +74,10 @@ class UrlSigner( .build() } + /** [file] signed by the source's [signerJson], or [file] itself. Blocking. */ + fun signedOrSelf(signerJson: String?, file: String, playerHeaders: Map): String = + fromJson(signerJson)?.sign(file, playerHeaders) ?: file + fun fromJson(json: String?): UrlSigner? { if (json.isNullOrBlank()) return null val o = runCatching { JSONObject(json) }.getOrNull() ?: return null diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt b/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt index 01c33a5f..c3a86d6b 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt @@ -431,7 +431,7 @@ class ServerHost( if (s.optBoolean("useLocalProxy", false)) put("useLocalProxy", true) s.optJSONObject("localProxy")?.let { put("localProxy", it) } s.optJSONObject("requestTransform")?.let { put("requestTransform", it) } - s.optString("dropSegments").takeIf { it.isNotEmpty() }?.let { put("dropSegments", it) } + (s.opt("dropSegments") as? String)?.takeIf { it.isNotEmpty() }?.let { put("dropSegments", it) } s.optJSONObject("signer")?.let { put("signer", it) } // Headless-WebView sniff directive (embed pages whose manifest is // only produced by the page's own JS) โ€” forward raw, per source diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt index be6e7ee0..c549dfb7 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt @@ -212,13 +212,11 @@ class WatchPartyActivity : AppCompatActivity() { val stream = torrent.resolve(url, room.optJSONObject("content")?.optInt("episode", -1)?.takeIf { it > 0 }) torrentHash = stream.hash; url = stream.url; type = "http" } + if (source.signer != null) url = withContext(Dispatchers.IO) { UrlSigner.signedOrSelf(source.signer, url, headers) } if (source.useWebViewSniff || WebViewStreamExtractor.needsExtraction(url)) { val sniffed = WebViewStreamExtractor.extract(this@WatchPartyActivity, url, headers) ?: error("Could not open the embedded player") url = sniffed.url; headers = sniffed.headers; type = sniffed.playType } - UrlSigner.fromJson(source.signer)?.let { signer -> - withContext(Dispatchers.IO) { signer.sign(url, headers) }?.let { url = it } - } if (source.useLocalProxy || source.dropSegments != null || StreamRequestRules.needsManifestProxy(url)) { url = withContext(Dispatchers.IO) { proxy.register(url, headers, source.localProxy?.let(::JSONObject) ?: JSONObject(), source.requestTransform?.let(::JSONObject) ?: JSONObject(), diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/screens/play/SeriesPlayerScreen.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/screens/play/SeriesPlayerScreen.kt index 7fec9651..7df63a02 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/screens/play/SeriesPlayerScreen.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/screens/play/SeriesPlayerScreen.kt @@ -746,11 +746,11 @@ class SeriesPlayerScreen : Fragment() { autoPlay: Boolean, then: () -> Unit = {}, ) { - val url = effectiveStreamUrl(vod) loadJob?.cancel() loadJob = viewLifecycleOwner.lifecycleScope.launch { val source = try { withContext(Dispatchers.IO) { + val url = effectiveStreamUrl(vod, signedUrl(vod)) withSeparateAudio(buildPlaybackSource(url, vod.type), vod) } } catch (cancelled: kotlinx.coroutines.CancellationException) { @@ -1352,7 +1352,9 @@ class SeriesPlayerScreen : Fragment() { val title = if (model.contentIsSeries == true) "${args.name} ยท ${currentEpisodeNumber()}" else args.name viewLifecycleOwner.lifecycleScope.launch { try { - com.saikou.sozo_tv.engine.download.TvDownloads.enqueue(requireContext(), title, vod) + val signed = if (vod.signerJson == null) vod + else vod.copy(urlobj = withContext(Dispatchers.IO) { signedUrl(vod) }) + com.saikou.sozo_tv.engine.download.TvDownloads.enqueue(requireContext(), title, signed) showToast(getString(R.string.player_download_started)) } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled @@ -1386,12 +1388,19 @@ class SeriesPlayerScreen : Fragment() { val excluded = candidates.filterNot { it in realPlayers }.map { android.content.ComponentName(it.activityInfo.packageName, it.activityInfo.name) }.toTypedArray() - return runCatching { + fun start(): Boolean = runCatching { player?.pause() startActivity(Intent.createChooser(intent, getString(R.string.player_external)) .putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS, excluded)) true }.getOrElse { showToast(getString(R.string.player_external_unavailable)); false } + if (vod.signerJson == null) return start() + player?.pause() + viewLifecycleOwner.lifecycleScope.launch { + intent.setDataAndType(android.net.Uri.parse(withContext(Dispatchers.IO) { signedUrl(vod) }), "video/*") + start() + } + return true } private fun openWatchParty() { @@ -1827,17 +1836,21 @@ class SeriesPlayerScreen : Fragment() { } } - private fun effectiveStreamUrl(vod: VodMovieResponse): String { - if (!vod.useLocalProxy) return vod.urlobj + /** Blocking: a signed source asks its host for a fresh token. */ + private fun signedUrl(vod: VodMovieResponse): String = + com.saikou.sozo_tv.engine.player.UrlSigner.signedOrSelf(vod.signerJson, vod.urlobj, vod.header) + + private fun effectiveStreamUrl(vod: VodMovieResponse, url: String): String { + if (!vod.useLocalProxy && vod.dropSegments == null) return url return runCatching { hlsProxy.register( - upstreamUrl = vod.urlobj, + upstreamUrl = url, headers = vod.header, localProxy = vod.localProxyJson?.let { JSONObject(it) } ?: JSONObject(), requestTransform = vod.requestTransformJson?.let { JSONObject(it) } ?: JSONObject(), dropSegments = vod.dropSegments, ) - }.getOrDefault(vod.urlobj) + }.getOrDefault(url) } private fun applySubtitleStyle() { diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/viewmodel/PlayAnimeViewModel.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/viewmodel/PlayAnimeViewModel.kt index 1682842c..df110ab8 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/viewmodel/PlayAnimeViewModel.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/viewmodel/PlayAnimeViewModel.kt @@ -331,16 +331,19 @@ class PlayAnimeViewModel( torrentSource = true } var headers = option.headers - com.saikou.sozo_tv.engine.player.UrlSigner.fromJson(option.signer)?.let { signer -> - val signed = withContext(Dispatchers.IO) { signer.sign(url, headers) } - if (signed != null) url = signed - else Log.w(TAG, "signing refused, playing the file as given") - } + // Signed by the player on every start, so a retry after the token expires gets a new one. + var signer = option.signer var mime = if (torrentSource) MimeTypes.VIDEO_MP4 else option.mimeTypes.ifEmpty { MimeTypes.APPLICATION_M3U8 } if (option.useWebViewSniff || com.saikou.sozo_tv.engine.player.WebViewStreamExtractor.needsExtraction(url) ) { + if (signer != null) { + url = withContext(Dispatchers.IO) { + com.saikou.sozo_tv.engine.player.UrlSigner.signedOrSelf(signer, url, headers) + } + signer = null + } val directive = parseSniff(option.sniff) val sniffed = com.saikou.sozo_tv.engine.player.WebViewStreamExtractor.extract( context = com.saikou.sozo_tv.app.MyApp.context, @@ -370,11 +373,11 @@ class PlayAnimeViewModel( header = headers, type = mime, thumbnail = option.thumbnail ?: "", - useLocalProxy = option.useLocalProxy || option.dropSegments != null || - com.saikou.sozo_tv.engine.player.StreamRequestRules.needsManifestProxy(url), + useLocalProxy = option.useLocalProxy || com.saikou.sozo_tv.engine.player.StreamRequestRules.needsManifestProxy(url), localProxyJson = option.localProxy, requestTransformJson = option.requestTransform, dropSegments = option.dropSegments, + signerJson = signer, audioTracks = option.audioTracks, drm = option.drm, ) diff --git a/app/src/test/java/com/saikou/sozo_tv/extensions/CloudStreamMediaTest.kt b/app/src/test/java/com/saikou/sozo_tv/extensions/CloudStreamMediaTest.kt index d43469be..19ad28d4 100644 --- a/app/src/test/java/com/saikou/sozo_tv/extensions/CloudStreamMediaTest.kt +++ b/app/src/test/java/com/saikou/sozo_tv/extensions/CloudStreamMediaTest.kt @@ -21,6 +21,14 @@ class CloudStreamMediaTest { assertEquals("https://site", media.sources.single().audioTracks.single().headers["Origin"]) assertEquals("https://page", media.subtitles.single().headers["Referer"]) } + @Test fun `a source's ad rule and signer survive media parsing`() { + val media = ExtParser.media("""{"videoSources":[{"videoUrl":"https://a/f.mp4","dropSegments":"^/v\\d+/","signer":{"url":"https://s/","param":"u[]"}},{"videoUrl":"https://b/v.m3u8","dropSegments":null}]}""") + val (signed, plain) = media.sources + assertEquals("^/v\\d+/", signed.dropSegments) + assertEquals("u[]", JSONObject(signed.signer!!).getString("param")) + assertNull(plain.dropSegments) + assertNull(plain.signer) + } @Test fun `empty failed provider remains an error rather than successful empty media`() { try { ExtParser.media("""{"videoSources":[],"error":"Provider: timed out"}"""); fail("expected failure") } catch (e: IllegalStateException) { assertEquals("Provider: timed out", e.message) } diff --git a/app/src/test/java/com/saikou/sozo_tv/player/UrlSignerTest.kt b/app/src/test/java/com/saikou/sozo_tv/player/UrlSignerTest.kt index 1ca7b16c..8d4f5ec5 100644 --- a/app/src/test/java/com/saikou/sozo_tv/player/UrlSignerTest.kt +++ b/app/src/test/java/com/saikou/sozo_tv/player/UrlSignerTest.kt @@ -58,6 +58,10 @@ class UrlSignerTest { assertNull(UrlSigner.fromJson(null)) } + @Test fun aSourceWithoutASignerPlaysAsGiven() { + assertEquals("https://cdn/a.mp4", UrlSigner.signedOrSelf(null, "https://cdn/a.mp4", emptyMap())) + } + @Test fun refusesAnAnswerThatIsNotAUrl() { val refusing = OkHttpClient.Builder().addInterceptor { chain -> Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(200).message("OK")