Yokan / rebuild
Course 1 8624561

TorrentStreams.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrentStreams.kt

implementation139 lines
1package eu.friedcutlet.yokan.services.torrent23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.database.DbTorrentPreferences5import eu.friedcutlet.yokan.database.DbVideo6import eu.friedcutlet.yokan.database.TorrServerMode7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.services.files.LocalFileService9import eu.friedcutlet.yokan.services.http.HttpService10import eu.friedcutlet.yokan.services.library.TorrentUtils11import kotlinx.coroutines.delay12import kotlinx.coroutines.flow.StateFlow13import kotlinx.coroutines.sync.Mutex14import kotlinx.coroutines.sync.withLock15import kotlinx.coroutines.withTimeoutOrNull16import kotlinx.serialization.json.JsonObject17import kotlinx.serialization.json.JsonPrimitive1819/** Launch options of a TorrServer process Yokan supervises. */20data class TorrServerLaunch(val port: Int, val executablePath: String, val proxyMode: String?, val proxyUrl: String)2122/** A TorrServer process owned by this profile; only platforms that can spawn one provide it. */23interface TorrServerHost {24    val status: StateFlow<String>25    /** Installed or user-provided executable, or null when neither exists yet. */26    fun executable(userPath: String): String?27    /** Downloads the pinned official release after SHA-256 verification; returns its path. */28    suspend fun install(onProgress: (downloaded: Long, total: Long) -> Unit): String29    /** Starts, or restarts after a crash or option change, and returns the server's base URL once healthy. */30    suspend fun ensureRunning(launch: TorrServerLaunch): String31    suspend fun stop()32}3334/** Desktop supervises a subprocess; Android, iOS and the browser have no host and use a remote server. */35expect fun createPlatformTorrServerHost(profileId: ProfileId): TorrServerHost?3637/** Turns magnet/`.torrent` references into TorrServer stream URLs for playback, casting and downloads. */38class TorrentStreams(39    private val database: YokanDatabase,40    private val http: HttpService,41    private val files: LocalFileService,42    val host: TorrServerHost?,43    private val pollMillis: Long = 1_000,44    private val metadataTimeoutMillis: Long = 90_000,45) {46    private val lock = Mutex()47    /** Server URL and tracker list last pushed; the server persists its settings itself. */48    private var pushed: Pair<String, String>? = null4950    private fun prefs(): DbTorrentPreferences = database.settings().features.torrent5152    /** Client for the configured server, starting or recovering the managed process first. Hostless platforms are remote-only. */53    suspend fun client(): TorrServerClient = lock.withLock {54        val prefs = prefs()55        check(prefs.enabled) { "Torrent streaming is off. Enable TorrServer in Settings → Player → Torrent streaming." }56        val host = host57        val client = if (prefs.mode == TorrServerMode.Managed && host != null) {58            TorrServerClient(http, host.ensureRunning(prefs.launch()))59        } else {60            host?.stop()61            check(prefs.remoteUrl.startsWith("http://", true) || prefs.remoteUrl.startsWith("https://", true)) { "Set the remote TorrServer URL (http://host:8090) in Settings → Player → Torrent streaming." }62            TorrServerClient(http, prefs.remoteUrl, prefs.username, prefs.password)63        }64        if (pushed != client.baseUrl to prefs.trackers) {65            pushTrackers(client, prefs.trackers)66            pushed = client.baseUrl to prefs.trackers67        }68        client69    }7071    /** Re-pushes the tracker list, e.g. after a reset, and returns the server version. */72    suspend fun applySettings(): String {73        lock.withLock { pushed = null }74        return client().echo()75    }7677    suspend fun stop() = lock.withLock {78        pushed = null79        host?.stop()80    }8182    /** Playable files of [link]; multi-file torrents list each video file (Animetail's `index=` picks one). */83    suspend fun videos(link: String, title: String): List<DbVideo> {84        val client = client()85        val added = if (isRemoteLink(link)) client.add(link, title) else {86            files.prepare()87            client.upload(files.readBytesAsync(link, MaxTorrentFileBytes), link.substringAfterLast('/'), title)88        }89        val torrent = if (added.files.isNotEmpty()) added else awaitFiles(client, added.hash)90        val wanted = TorrentUtils.fileIndex(link)91        val playable = torrent.files.filter { it.id == wanted }92            .ifEmpty { torrent.files.filter { it.name.substringAfterLast('.', "").lowercase() in VideoExtensions } }93            .ifEmpty { torrent.files }94        return playable.map { DbVideo(url = client.streamUrl(torrent.hash, it), quality = it.name, originalUrl = link) }95    }9697    /** Replaces torrent entries of an extension's video list; without the engine they are dropped. */98    suspend fun expand(videos: List<DbVideo>, title: String): List<DbVideo> {99        if (videos.none { TorrentUtils.isTorrentLink(it.url) }) return videos100        if (!prefs().enabled) {101            return videos.filterNot { TorrentUtils.isTorrentLink(it.url) }102                .ifEmpty { error("This source only offers torrents. Enable TorrServer in Settings → Player → Torrent streaming.") }103        }104        return videos.flatMap { video ->105            if (!TorrentUtils.isTorrentLink(video.url)) listOf(video)106            else videos(video.url, title).map { file ->107                file.copy(quality = if (video.quality.isBlank()) file.quality else "${video.quality} · ${file.quality}", subtitles = video.subtitles, audios = video.audios)108            }109        }110    }111112    private suspend fun awaitFiles(client: TorrServerClient, hash: String): TorrServerTorrent =113        withTimeoutOrNull(metadataTimeoutMillis) {114            var torrent = client.get(hash)115            while (torrent.files.isEmpty()) {116                delay(pollMillis)117                torrent = client.get(hash)118            }119            torrent120        } ?: error("TorrServer found no metadata for this torrent in ${metadataTimeoutMillis / 1000} s (no peers?).")121122    private suspend fun pushTrackers(client: TorrServerClient, trackers: String) {123        val sets = client.settings()124        check("DefaultTrackers" in sets) { "This TorrServer does not support tracker lists; update it to a current MatriX release." }125        val list = trackers.lines().map(String::trim).filter(String::isNotEmpty).joinToString("\n")126        // RetrackersMode 1 adds the list to every torrent's own trackers.127        client.setSettings(JsonObject(sets + mapOf("DefaultTrackers" to JsonPrimitive(list), "RetrackersMode" to JsonPrimitive(1))))128    }129130    private fun isRemoteLink(link: String) =131        link.startsWith("magnet:", true) || link.startsWith("http://", true) || link.startsWith("https://", true)132133    private companion object {134        const val MaxTorrentFileBytes = 16L * 1024 * 1024135        val VideoExtensions = setOf("mkv", "mp4", "m4v", "avi", "webm", "mov", "ts", "m2ts", "wmv", "flv", "ogv", "mpg", "mpeg")136    }137}138139fun DbTorrentPreferences.launch() = TorrServerLaunch(port, executablePath, proxyMode.flag?.takeIf { proxyUrl.isNotBlank() }, proxyUrl)140

Search chapters, reference and source filenames.