JsPacker.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/JsPacker.kt
1package eu.friedcutlet.yokan.services.media.extractors23/**4 * Kotlin port of Dean Edwards' `p,a,c,k,e,d` JavaScript unpacker — the same5 * algorithm Filemoon and StreamWish payloads ship through.6 *7 * The packer wraps the original script in a self-executing function whose tail8 * looks like `}('payload', radix, count, 'sym1|sym2|…'.split('|'), 0, {}))`.9 * We slice those four arguments out, then substitute each `\b\w+\b` token in10 * the payload with `symbolTable[unbase(token, radix)]`.11 *12 * Returns the unpacked source on success, or null when the input is not in13 * the packed shape we recognise.14 */15internal object JsPacker {1617 private val HEAD_REGEX = Regex(18 """\}\s*\(\s*'([\s\S]+?)'\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*'([\s\S]+?)'\.split\('\|'\)\s*,\s*0\s*,\s*\{\}\s*\)\s*\)""",19 )2021 private val TOKEN_REGEX = Regex("""\b\w+\b""")2223 fun unpack(source: String): String? {24 val match = HEAD_REGEX.find(source) ?: return null25 val payload = match.groupValues[1].unescape()26 val radix = match.groupValues[2].toIntOrNull() ?: return null27 // Group 3 is the symbol count; it may disagree with `symbols.size` (some28 // payloads still unpack correctly) and `getOrNull` below keeps indexing in bounds.29 match.groupValues[3].toIntOrNull() ?: return null30 val symbols = match.groupValues[4].split('|')31 return TOKEN_REGEX.replace(payload) { mr ->32 val token = mr.value33 val index = unbase(token, radix) ?: return@replace token34 val sym = symbols.getOrNull(index)35 // Empty string in the table means "leave the original token in".36 if (sym.isNullOrEmpty()) token else sym37 }38 }3940 /** Inverse of Dean Edwards' radix-N alphabet used by the packer. */41 private fun unbase(token: String, radix: Int): Int? {42 var result = 043 for (ch in token) {44 val digit = when {45 ch in '0'..'9' -> ch - '0'46 ch in 'a'..'z' -> ch - 'a' + 1047 ch in 'A'..'Z' -> ch - 'A' + 3648 else -> return null49 }50 if (digit >= radix) return null51 result = result * radix + digit52 }53 return result54 }5556 /**57 * Undo the standard escape characters the packer uses inside its first58 * argument: `\'` `\\` `\n` `\t` `\r`. We don't try to be a full JS string59 * literal parser — the packer only ever emits these escapes.60 */61 private fun String.unescape(): String {62 val sb = StringBuilder(length)63 var i = 064 while (i < length) {65 val ch = this[i]66 if (ch == '\\' && i + 1 < length) {67 when (val next = this[i + 1]) {68 '\\' -> sb.append('\\')69 '\'' -> sb.append('\'')70 '"' -> sb.append('"')71 'n' -> sb.append('\n')72 't' -> sb.append('\t')73 'r' -> sb.append('\r')74 '/' -> sb.append('/')75 else -> {76 sb.append('\\')77 sb.append(next)78 }79 }80 i += 281 } else {82 sb.append(ch)83 i++84 }85 }86 return sb.toString()87 }88}89