Files
AudioManager/src/main/kotlin/win/taptap/musicmanager/download/YtDlpDownloader.kt
T
TapTap c75f2971b4
CI / chart (push) Successful in 3s
CI / chart-push (push) Successful in 5s
CI / test (push) Successful in 1m50s
CI / image (push) Successful in 3m16s
feat: mix mood radio by seed percentage and embed download artwork
Moods now store a seedPercent (0-100, default 50). RadioService rolls that
share independently for every queued slot: heads picks from the seed songs,
tails from the generated recommendation pool. When one pool is empty the other
fills the batch, so a mood never stalls. The DTO exposes both seedPercent and
the derived recommendationPercent, and create/patch accept seedPercent.

Automatic YT downloads now embed the video thumbnail as MP3 cover art so the
scanner publishes a cover for newly imported tracks.

V7 adds moods.seed_percent.
2026-11-15 17:07:04 +00:00

71 lines
2.3 KiB
Kotlin

package win.taptap.musicmanager.download
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
/**
* Downloads a single YouTube video as an MP3 with embedded metadata, so the
* scanner can derive artist and title from the file itself.
*/
class YtDlpDownloader(
private val executable: String,
private val timeoutSeconds: Long = 600,
) : AudioDownloader {
override fun download(videoId: String, title: String, artist: String, targetDir: Path): Path {
Files.createDirectories(targetDir)
val process = ProcessBuilder(
executable,
"-x",
"--audio-format",
"mp3",
"--audio-quality",
"0",
"--embed-metadata",
"--embed-thumbnail",
"--convert-thumbnails",
"jpg",
"--no-playlist",
"--no-cache-dir",
"--no-progress",
"--print",
"after_move:filepath",
"-o",
targetDir.resolve("%(id)s.%(ext)s").toString(),
"https://www.youtube.com/watch?v=$videoId",
)
.redirectErrorStream(true)
.start()
val output = StringBuilder()
val reader = thread(isDaemon = true, name = "yt-dlp-download") {
process.inputStream.bufferedReader().useLines { lines ->
lines.forEach { output.appendLine(it) }
}
}
if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) {
process.destroyForcibly()
reader.join(2_000)
throw IllegalStateException("yt-dlp download timed out after ${timeoutSeconds}s")
}
reader.join(2_000)
if (process.exitValue() != 0) {
throw IllegalStateException(
"yt-dlp exited with ${process.exitValue()}: ${output.toString().take(400).trim()}",
)
}
val printed = output.lines()
.map { it.trim() }
.lastOrNull { it.endsWith(".mp3", ignoreCase = true) }
val file = printed?.let { Path.of(it) } ?: targetDir.resolve("$videoId.mp3")
if (!Files.isRegularFile(file)) {
throw IllegalStateException("yt-dlp did not produce an MP3 file")
}
return file
}
}