Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ data class ExtVideoSource(
/** Separate audio renditions that belong with this video (CloudStream `audioTracks`). */
val audioTracks: List<ExtAudioTrack> = 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(
Expand Down Expand Up @@ -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 ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ data class VodMovieResponse(
val useLocalProxy: Boolean = false,
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<AudioTrackRef> = emptyList(),
val drm: String? = null,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String>()
// From an #EXTINF up to its uri, which decides whether they stay.
val pending = mutableListOf<String>()
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")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -81,13 +82,15 @@ class LocalHlsProxy(private val client: OkHttpClient) {
headers: Map<String, String>,
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)}"
}

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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<String, String>, val transform: RequestTransform?)
private class Session(val headers: Map<String, String>, val transform: RequestTransform?, val dropSegments: Regex?)

private class TransformedRequest(val url: String, val headers: Map<String, String>)

Expand Down
107 changes: 107 additions & 0 deletions app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
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<String, String> = 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<String, String>, 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<String, Pair<String, Long>>()

private val defaultClient: OkHttpClient by lazy {
OkHttpClient.Builder()
.dns(ExtensionDns.dns)
.callTimeout(8, TimeUnit.SECONDS)
.build()
}

/** [file] signed by the source's [signerJson], or [file] itself. Blocking. */
fun signedOrSelf(signerJson: String?, file: String, playerHeaders: Map<String, String>): 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
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<String>().firstOrNull()
is JSONArray -> (0 until v.length()).map { v.opt(it) }.filterIsInstance<String>().firstOrNull()
is String -> v
else -> null
}
return signed?.takeIf { it.startsWith("http") }
}

internal fun clearCache() = synchronized(cache) { cache.clear() }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.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
// or inherited from the media level.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,15 @@ 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
}
if (source.useLocalProxy || StreamRequestRules.needsManifestProxy(url)) {
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -1827,16 +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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -331,11 +331,19 @@ class PlayAnimeViewModel(
torrentSource = true
}
var headers = option.headers
// 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,
Expand Down Expand Up @@ -368,6 +376,8 @@ class PlayAnimeViewModel(
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,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand Down
Loading
Loading