Yokan / rebuild
Course 1 8624561

TorrentUtils.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/TorrentUtils.kt

implementation205 lines
1package eu.friedcutlet.yokan.services.library23import io.ktor.http.Url4import io.ktor.http.decodeURLQueryComponent56object TorrentUtils {7    private const val BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567"8    private val BTIH_REGEX = Regex("""urn:btih:([a-zA-Z0-9]+)""", RegexOption.IGNORE_CASE)9    private val BTMH_REGEX = Regex("""urn:btmh:(?:1220)?([a-zA-Z0-9]+)""", RegexOption.IGNORE_CASE)1011    /** A magnet URI or a `.torrent` file path/URL (Animetail's torrent-video test). */12    fun isTorrentLink(url: String): Boolean =13        url.startsWith("magnet:", ignoreCase = true) ||14            url.substringBefore('#').substringBefore('?').endsWith(".torrent", ignoreCase = true)1516    /** Animetail's `index=` file selector inside a magnet/torrent link (TorrServer file ids start at 1). */17    fun fileIndex(link: String): Int? =18        link.substringAfter('?', "").split('&').firstOrNull { it.startsWith("index=") }?.substringAfter('=')?.toIntOrNull()1920    /**21     * Normalizes a torrent infohash:22     * - 40 hex characters: lowercased hex.23     * - 32 base32 characters (RFC 4648 / BitTorrent standard): decoded into 20 bytes and returned24     *   as 40 lowercase hex characters.25     * - 64 hex characters (BitTorrent v2 multihash/SHA256): lowercased hex.26     * - Other strings: trimmed and left untouched.27     */28    fun normalizeInfoHash(hash: String): String {29        val clean = hash.trim()30        if (clean.length == 40) {31            return clean.lowercase()32        }33        if (clean.length == 32) {34            val lower = clean.lowercase()35            var buffer = 036            var bitsLeft = 037            val bytes = ByteArray(20)38            var byteCount = 039            for (i in lower.indices) {40                val value = BASE32_ALPHABET.indexOf(lower[i])41                if (value < 0) return clean42                buffer = (buffer shl 5) or value43                bitsLeft += 544                if (bitsLeft >= 8) {45                    bitsLeft -= 846                    if (byteCount < 20) {47                        bytes[byteCount++] = ((buffer ushr bitsLeft) and 0xFF).toByte()48                    }49                }50            }51            if (byteCount == 20) {52                return bytes.toHexString()53            }54        }55        if (clean.length == 64 && clean.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }) {56            return clean.lowercase()57        }58        return clean59    }6061    /**62     * Extracts and normalizes the infohash from a magnet URI:63     * First checks for BitTorrent v1 (urn:btih:...), then BitTorrent v2 (urn:btmh:...).64     */65    fun extractInfoHashFromMagnet(magnetUrl: String): String? {66        val btihMatch = BTIH_REGEX.find(magnetUrl)67        if (btihMatch != null) {68            return normalizeInfoHash(btihMatch.groupValues[1])69        }70        val btmhMatch = BTMH_REGEX.find(magnetUrl)71        if (btmhMatch != null) {72            return normalizeInfoHash(btmhMatch.groupValues[1])73        }74        return null75    }7677    /**78     * Extracts and normalizes an infohash from a stream/playlist URL or magnet link:79     * Checks `infohash` and `ih` query parameters, falling back to magnet URI extraction.80     */81    fun extractInfoHashFromUrl(url: String): String? {82        if (url.isBlank()) return null83        val query = url.substringAfter('?', "")84        if (query.isNotEmpty()) {85            for (param in query.split('&')) {86                val key = param.substringBefore('=')87                if (key.equals("infohash", ignoreCase = true) || key.equals("ih", ignoreCase = true)) {88                    val raw = param.substringAfter('=', "")89                    val decoded = runCatching {90                        raw.decodeURLQueryComponent(plusIsSpace = true)91                    }.getOrDefault(raw)92                    val normalized = normalizeInfoHash(decoded)93                    if (normalized.isNotBlank()) return normalized94                }95            }96        }97        return extractInfoHashFromMagnet(url)98    }99100    /**101     * Extracts the display name (`dn`) parameter from a magnet URI, decoding percent escapes102     * and plus spaces.103     */104    fun extractMagnetDisplayName(magnetUrl: String): String? {105        if (!magnetUrl.startsWith("magnet:", ignoreCase = true)) return null106        val query = magnetUrl.substringAfter('?', "")107        if (query.isEmpty()) return null108        for (param in query.split('&')) {109            if (param.startsWith("dn=", ignoreCase = true)) {110                val raw = param.substring(3)111                return runCatching {112                    raw.decodeURLQueryComponent(plusIsSpace = true)113                }.getOrDefault(raw.replace('+', ' '))114            }115        }116        return null117    }118119    /**120     * Normalizes a collection of HTTP/HTTPS URLs:121     * Trims, removes empty/invalid items, ensures HTTP or HTTPS scheme, and deduplicates while122     * preserving order.123     */124    fun normalizeHttpUrls(values: Iterable<String>): List<String> {125        val normalized = mutableListOf<String>()126        val seen = mutableSetOf<String>()127        for (value in values) {128            val trimmed = value.trim()129            if (trimmed.isEmpty()) continue130            if (!trimmed.startsWith("http://", ignoreCase = true) && !trimmed.startsWith("https://", ignoreCase = true)) {131                continue132            }133            val parsed = runCatching { Url(trimmed).toString() }.getOrNull() ?: trimmed134            if (seen.add(parsed)) {135                normalized.add(parsed)136            }137        }138        return normalized139    }140141    /**142     * Extracts fallback download sources (`xs`, `as`) and webseeds (`ws`) from a magnet URI.143     */144    fun extractMagnetFallbacks(magnetUrl: String): Pair<List<String>, List<String>> {145        if (!magnetUrl.startsWith("magnet:", ignoreCase = true)) {146            return Pair(emptyList(), emptyList())147        }148        val query = magnetUrl.substringAfter('?', "")149        if (query.isEmpty()) return Pair(emptyList(), emptyList())150        val sources = mutableListOf<String>()151        val webseeds = mutableListOf<String>()152        for (param in query.split('&')) {153            val key = param.substringBefore('=').lowercase()154            val raw = param.substringAfter('=', "")155            val decoded = runCatching { raw.decodeURLQueryComponent(plusIsSpace = true) }.getOrDefault(raw)156            when (key) {157                "xs", "as" -> sources.add(decoded)158                "ws" -> webseeds.add(decoded)159            }160        }161        return Pair(normalizeHttpUrls(sources), normalizeHttpUrls(webseeds))162    }163164    /**165     * Merges base and discovered fallback URLs.166     */167    fun mergeTorrentFallbacks(base: Iterable<String>, discovered: Iterable<String>): List<String> {168        return normalizeHttpUrls(base + discovered)169    }170171    /**172     * Complete parsed magnet metadata.173     */174    data class MagnetInfo(175        val infoHash: String?,176        val displayName: String?,177        val sources: List<String>,178        val webseeds: List<String>,179        val trackers: List<String>,180    )181182    fun parseMagnet(magnetUrl: String): MagnetInfo {183        val infoHash = extractInfoHashFromMagnet(magnetUrl)184        val displayName = extractMagnetDisplayName(magnetUrl)185        val (sources, webseeds) = extractMagnetFallbacks(magnetUrl)186        val trackers = mutableListOf<String>()187        val query = magnetUrl.substringAfter('?', "")188        if (query.isNotEmpty()) {189            for (param in query.split('&')) {190                if (param.startsWith("tr=", ignoreCase = true)) {191                    val raw = param.substring(3)192                    val decoded = runCatching { raw.decodeURLQueryComponent(plusIsSpace = true) }.getOrDefault(raw)193                    if (decoded.isNotBlank()) trackers.add(decoded)194                }195            }196        }197        return MagnetInfo(198            infoHash = infoHash,199            displayName = displayName,200            sources = sources,201            webseeds = webseeds,202            trackers = trackers.distinct(),203        )204    }205}206

Search chapters, reference and source filenames.