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 @@ -135,7 +135,7 @@ fun ExtMedia.toVod(thumbnail: String = "", language: String = ""): VodMovieRespo
return VodMovieResponse(
authInfo = "",
header = chosen?.headers ?: headers,
subtitleList = subtitles.map { SubTitle(file = it.file, label = it.label, headers = it.headers) },
subtitleList = subtitles.map { SubTitle(file = it.file, label = it.label, headers = it.headers, cipher = it.cipher) },
urlobj = url,
type = mime,
thumbnail = thumbnail,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.saikou.sozo_tv.data.extensions

import android.util.Log
import com.saikou.sozo_tv.domain.player.SubtitleCipher
import org.json.JSONArray
import org.json.JSONObject

Expand Down Expand Up @@ -157,6 +158,7 @@ data class ExtSubtitle(
val file: String,
val default: Boolean,
val headers: Map<String, String> = emptyMap(),
val cipher: SubtitleCipher? = null,
)

data class ExtMedia(
Expand Down Expand Up @@ -394,6 +396,7 @@ internal object ExtParser {
file,
s.optBoolean("default", false),
s.headersMap("headers"),
SubtitleCipher.from(s.optJSONObject("cipher")),
)
}
// Seek-preview thumbnails: soplay emits a bare VTT url String or a {url,type,template,...}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.saikou.sozo_tv.data.model

import androidx.media3.common.MimeTypes
import com.saikou.sozo_tv.domain.player.SubtitleCipher
import java.io.Serializable

data class VodMovieResponse(
Expand Down Expand Up @@ -35,4 +36,5 @@ data class SubTitle(
val flag: String = "",
/** Headers for the subtitle request itself; empty for sources that need none. */
val headers: Map<String, String> = emptyMap(),
val cipher: SubtitleCipher? = null,
)
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ data class MegaTrack(
val kind: String,
/** Headers for fetching this track — see [com.saikou.sozo_tv.data.extensions.ExtSubtitle]. */
val headers: Map<String, String> = emptyMap(),
val cipher: com.saikou.sozo_tv.domain.player.SubtitleCipher? = null,
)
data class MegaResponse(
val sources: List<MegaSource>,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.saikou.sozo_tv.domain.player

import okio.ByteString.Companion.decodeBase64
import org.json.JSONObject
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.charset.CodingErrorAction
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

/**
* Some sources (KissKH's `.txt1` files) ship an ordinary SRT whose cue text lines are
* each AES-encrypted; the backend tags such a subtitle with the key to open them.
*/
data class SubtitleCipher(
val alg: String,
val key: String,
val iv: String,
val scope: String = SCOPE,
val encoding: String = ENCODING,
) {

/** Decrypts every cue text line; indices, timing lines and blanks pass through. */
fun decrypt(body: String): String {
if (!alg.equals(ALG, true) || !scope.equals(SCOPE, true) || !encoding.equals(ENCODING, true)) {
throw IOException("unsupported subtitle cipher $alg/$scope/$encoding")
}
val keyBytes = key.toByteArray(Charsets.UTF_8)
val ivBytes = iv.toByteArray(Charsets.UTF_8)
if (keyBytes.size != 16 || ivBytes.size != 16) throw IOException("bad subtitle cipher key")
val aes = Cipher.getInstance("AES/CBC/PKCS5Padding")
val secret = SecretKeySpec(keyBytes, "AES")

var encrypted = 0
var opened = 0
val out = body.split('\n').map { line ->
val text = line.trim()
if (!isCueText(text)) return@map line
encrypted++
val plain = runCatching {
aes.init(Cipher.DECRYPT_MODE, secret, IvParameterSpec(ivBytes))
val bytes = text.decodeBase64() ?: return@runCatching null
strictUtf8(aes.doFinal(bytes.toByteArray()))
}.getOrNull() ?: return@map line
opened++
if (line.endsWith('\r')) "$plain\r" else plain
}
// A wrong key still yields valid padding now and then, so a few opened lines prove nothing.
if (encrypted > 0 && opened * 2 < encrypted) throw IOException("subtitle cipher opened $opened of $encrypted cues")
return out.joinToString("\n")
}

private fun strictUtf8(bytes: ByteArray): String =
Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes)).toString()

private fun isCueText(line: String): Boolean =
line.isNotEmpty() && !line.contains("-->") && !line.all { it.isDigit() } && line != "WEBVTT"

companion object {
private const val ALG = "aes-128-cbc"
private const val SCOPE = "cue-text"
private const val ENCODING = "base64"

fun from(o: JSONObject?): SubtitleCipher? {
o ?: return null
val alg = o.optString("alg").ifEmpty { return null }
val key = o.optString("key").ifEmpty { return null }
val iv = o.optString("iv").ifEmpty { return null }
return SubtitleCipher(
alg, key, iv,
o.optString("scope").ifEmpty { SCOPE },
o.optString("encoding").ifEmpty { ENCODING },
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ class SubtitleSideloader(
?: retryReferer?.let { fetch(chosen, referer = it) }
?: throw IOException("subtitle host refused the request")

val body = SubtitleBody.decode(bytes, chosen.label)
val decoded = SubtitleBody.decode(bytes, chosen.label)
val body = chosen.cipher?.decrypt(decoded) ?: decoded
cached = chosen.file to body
return body
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ class ServerHost(
}.toString()
}

private fun translateMedia(soplay: String?): String {
internal fun translateMedia(soplay: String?): String {
val o = parseObject(soplay ?: return "{}")
val srcIn = o.optJSONArray("videoSources") ?: JSONArray()
val srcOut = JSONArray()
Expand Down Expand Up @@ -450,6 +450,7 @@ class ServerHost(
put("file", file)
put("default", s.optBoolean("default", s.optBoolean("isDefault", false)))
s.optJSONObject("headers")?.let { put("headers", it) }
s.optJSONObject("cipher")?.let { put("cipher", it) }
})
}
return JSONObject().apply {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ class ExtensionParser : BaseParser() {
val (encoded, mediaRef) = untag(epId)
val p = encoded ?: activeProvider() ?: return emptyList()
val media = engine.loadLinks(p, mediaRef)
val tracks = media.subtitles.map { MegaTrack(it.file, it.label, "captions", it.headers) }
val tracks = media.subtitles.map { MegaTrack(it.file, it.label, "captions", it.headers, it.cipher) }
return media.sources.map { s ->
VideoOption(
videoUrl = s.videoUrl,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ class PlayAnimeViewModel(

return VodMovieResponse(
authInfo = "",
subtitleList = option.tracks.map { SubTitle(it.file, it.label ?: "", headers = it.headers) },
subtitleList = option.tracks.map { SubTitle(it.file, it.label ?: "", headers = it.headers, cipher = it.cipher) },
urlobj = url,
header = headers,
type = mime,
Expand Down
76 changes: 76 additions & 0 deletions app/src/test/java/com/saikou/sozo_tv/player/SubtitleCipherTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.saikou.sozo_tv.player

import com.saikou.sozo_tv.data.extensions.ExtParser
import android.content.ContextWrapper
import com.saikou.sozo_tv.domain.player.SubtitleCipher
import com.saikou.sozo_tv.engine.server.ServerHost
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.fail
import org.junit.Test
import java.io.IOException

class SubtitleCipherTest {
private val cipher = SubtitleCipher("aes-128-cbc", "AmSmZVcH93UQUezi", "ReBKWW8cqdjPEnF6", "cue-text", "base64")

@Test
fun `kisskh cue text is decrypted and timing is kept`() {
val body = "1\r\n00:00:01,000 --> 00:00:02,500\r\nSq/yslS8glo0CoTCWZBT0GepZqSNY4KqATqtSAO1798=\r\n\r\n"

val out = cipher.decrypt(body)

assertEquals("1\r\n00:00:01,000 --> 00:00:02,500\r\n<i>♫ Set off ♫</i>\r\n\r\n", out)
}

@Test
fun `a wrong key fails instead of showing ciphertext`() {
val body = "1\n00:00:01,000 --> 00:00:02,500\nSq/yslS8glo0CoTCWZBT0GepZqSNY4KqATqtSAO1798=\n"
try {
cipher.copy(key = "8056483646328763").decrypt(body)
fail("expected failure")
} catch (_: IOException) {
}
}

@Test
fun `a key that opens only a minority of cues fails`() {
val body = "1\n00:00:01,000 --> 00:00:02,500\nSq/yslS8glo0CoTCWZBT0GepZqSNY4KqATqtSAO1798=\n\n" +
"2\n00:00:03,000 --> 00:00:04,000\nnot a cue\n\n3\n00:00:05,000 --> 00:00:06,000\nnor this\n"
try {
cipher.decrypt(body)
fail("expected failure")
} catch (_: IOException) {
}
}

@Test
fun `an extractor payload keeps the cipher through the server host`() {
val extractor = """{"videoSources":[{"videoUrl":"https://cdn/v.m3u8"}],"subtitles":[""" +
"""{"src":"https://sub/a.srt.txt1","label":"English","cipher":{"alg":"aes-128-cbc","key":"AmSmZVcH93UQUezi","iv":"ReBKWW8cqdjPEnF6","scope":"cue-text","encoding":"base64"}}]}"""

val media = ExtParser.media(ServerHost(ContextWrapper(null)).translateMedia(extractor))

assertEquals(cipher, media.subtitles[0].cipher)
}

@Test
fun `an unknown algorithm is refused`() {
try {
cipher.copy(alg = "aes-256-gcm").decrypt("1\n00:00:01,000 --> 00:00:02,000\nx\n")
fail("expected failure")
} catch (_: IOException) {
}
}

@Test
fun `the media payload carries the cipher to the subtitle`() {
val media = ExtParser.media(
"""{"videoSources":[{"videoUrl":"https://cdn/v.m3u8"}],"subtitles":[""" +
"""{"file":"https://sub/a.srt.txt1","label":"English","cipher":{"alg":"aes-128-cbc","key":"AmSmZVcH93UQUezi","iv":"ReBKWW8cqdjPEnF6","scope":"cue-text","encoding":"base64"}},""" +
"""{"file":"https://sub/b.srt","label":"Korean"}]}"""
)

assertEquals(cipher, media.subtitles[0].cipher)
assertNull(media.subtitles[1].cipher)
}
}
20 changes: 20 additions & 0 deletions apple-tv/SozoTV/Models.swift
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,26 @@ struct SubtitleTrack: Decodable, Identifiable, Hashable {
var id: String { file }
let label: String?
let file: String
var cipher: SubtitleCipher? = nil
}

extension SubtitleTrack {
private enum CodingKeys: String, CodingKey { case label, file, cipher }
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
label = try c.decodeIfPresent(String.self, forKey: .label)
file = try c.decode(String.self, forKey: .file)
cipher = try? c.decodeIfPresent(SubtitleCipher.self, forKey: .cipher)
}
}

/// Key for subtitles whose cue text lines are each encrypted (KissKH `.txt1`).
struct SubtitleCipher: Decodable, Hashable, Sendable {
let alg: String
let key: String
let iv: String
let scope: String?
let encoding: String?
}

struct MediaEnvelope: Decodable {
Expand Down
69 changes: 61 additions & 8 deletions apple-tv/SozoTV/SidecarSubtitles.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import CommonCrypto
import Foundation

/// Plain-text sidecar captions. Times are seconds on the media timeline.
Expand All @@ -13,14 +14,15 @@ enum SidecarSubtitles {
private static let maximumDuration: Double = 3600

enum ParseError: Error, LocalizedError {
case tooLarge, invalidEncoding, invalidTiming, tooManyCues, invalidFormat
case tooLarge, invalidEncoding, invalidTiming, tooManyCues, invalidFormat, undecryptable
var errorDescription: String? {
switch self {
case .tooLarge: "Subtitle file is too large."
case .invalidEncoding: "Subtitle text encoding is unsupported."
case .invalidTiming: "Subtitle file contains invalid timing."
case .tooManyCues: "Subtitle file contains too many captions."
case .invalidFormat: "The source did not return a supported subtitle file."
case .undecryptable: "Subtitle file could not be decrypted."
}
}
}
Expand All @@ -32,6 +34,60 @@ enum SidecarSubtitles {

/// Parses WebVTT or SubRip without evaluating markup or accepting HTML responses.
static func parse(_ data: Data) throws -> [SubtitleCue] {
let normalized = try decodeText(data)
// Providers occasionally return an HTML error document with subtitle-like text.
// Only detect document markup before cue parsing; angle brackets in real captions are valid.
let beginning = normalized.trimmingCharacters(in: .whitespacesAndNewlines).prefix(512)
guard beginning.range(of: #"(?is)^(?:<!--.*?-->\s*)*(?:<!doctype\s+html\b|<html\b|<head\b|<body\b)"#,
options: .regularExpression) == nil else { throw ParseError.invalidFormat }
let lines = normalized.components(separatedBy: "\n")
return try cues(lines)
}

/// Opens subtitles whose cue text lines are each AES-128-CBC encrypted and base64 encoded.
/// Indices and timing lines are left alone; a key that opens no line is an error.
static func decryptCueText(_ data: Data, alg: String, key: String, iv: String,
scope: String? = nil, encoding: String? = nil) throws -> Data {
guard alg.lowercased() == "aes-128-cbc", (scope ?? "cue-text").lowercased() == "cue-text",
(encoding ?? "base64").lowercased() == "base64" else { throw ParseError.undecryptable }
let keyBytes = Data(key.utf8), ivBytes = Data(iv.utf8)
guard keyBytes.count == kCCKeySizeAES128, ivBytes.count == kCCBlockSizeAES128 else { throw ParseError.undecryptable }
var encrypted = 0, opened = 0
let lines = try decodeText(data).components(separatedBy: "\n").map { line -> String in
let text = line.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty, !text.contains("-->"), text != "WEBVTT",
!text.allSatisfy({ $0.isASCII && $0.isNumber }) else { return line }
encrypted += 1
guard let cipherText = Data(base64Encoded: text),
let plain = aes128CBCDecrypt(cipherText, key: keyBytes, iv: ivBytes) else { return line }
opened += 1
return plain
}
if encrypted > 0 && opened * 2 < encrypted { throw ParseError.undecryptable }
return Data(lines.joined(separator: "\n").utf8)
}

private static func aes128CBCDecrypt(_ data: Data, key: Data, iv: Data) -> String? {
guard !data.isEmpty, data.count % kCCBlockSizeAES128 == 0 else { return nil }
var output = Data(count: data.count + kCCBlockSizeAES128)
let capacity = output.count
var written = 0
let status = output.withUnsafeMutableBytes { out in
data.withUnsafeBytes { input in
key.withUnsafeBytes { k in
iv.withUnsafeBytes { v in
CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding),
k.baseAddress, key.count, v.baseAddress, input.baseAddress, data.count,
out.baseAddress, capacity, &written)
}
}
}
}
guard status == kCCSuccess else { return nil }
return String(data: output.prefix(written), encoding: .utf8)
}

private static func decodeText(_ data: Data) throws -> String {
guard data.count <= maximumBytes else { throw ParseError.tooLarge }
let decoded: String?
if data.starts(with: [0xFF, 0xFE]) {
Expand All @@ -42,14 +98,11 @@ enum SidecarSubtitles {
decoded = String(data: data, encoding: .utf8)
}
guard let decoded, !decoded.contains("\0") else { throw ParseError.invalidEncoding }
let normalized = decoded.replacingOccurrences(of: "\u{FEFF}", with: "")
return decoded.replacingOccurrences(of: "\u{FEFF}", with: "")
.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
// Providers occasionally return an HTML error document with subtitle-like text.
// Only detect document markup before cue parsing; angle brackets in real captions are valid.
let beginning = normalized.trimmingCharacters(in: .whitespacesAndNewlines).prefix(512)
guard beginning.range(of: #"(?is)^(?:<!--.*?-->\s*)*(?:<!doctype\s+html\b|<html\b|<head\b|<body\b)"#,
options: .regularExpression) == nil else { throw ParseError.invalidFormat }
let lines = normalized.components(separatedBy: "\n")
}

private static func cues(_ lines: [String]) throws -> [SubtitleCue] {
var cues: [SubtitleCue] = []
var index = 0
while index < lines.count {
Expand Down
Loading
Loading