feat: add Deezer as the default download source
- V9 adds source/external_id to songs, moods, recommendations and jobs - Deezer public catalog for search, related album covers and metadata - streamrip downloader configured with DEEZER_ARL, 128/320 MP3 - per-mood source selector; switching clears and refills recommendations - keep YouTube Music as a full second catalog and downloader - media layout <source>-<externalId>, legacy YouTube folders still read - Docker/streamrip install, chart ARL secret, docs and dual-source smoke test
This commit is contained in:
1 parent
81a47f4cd2
commit
141698282d
43 files changed
+2072
-605
No files matched your search
@@ -0,0 +1,194 @@
|
||||
package win.taptap.musicmanager.discovery
|
||||
|
||||
import java.net.URI
|
||||
import java.net.URLEncoder
|
||||
import java.net.http.HttpClient
|
||||
import java.net.http.HttpRequest
|
||||
import java.net.http.HttpResponse
|
||||
import java.time.Duration
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import win.taptap.musicmanager.source.MusicSource
|
||||
|
||||
/**
|
||||
* Deezer's public catalog API. No user token is needed for search or track
|
||||
* metadata; the ARL is only used by the downloader.
|
||||
*
|
||||
* Deezer returns canonical tracks with a square album cover, which is also what
|
||||
* the indexer embeds into the downloaded MP3.
|
||||
*/
|
||||
class DeezerSearch(
|
||||
private val apiBase: String = "https://api.deezer.com",
|
||||
private val timeoutSeconds: Long = 20,
|
||||
) : MusicCatalog {
|
||||
|
||||
override val source: String = MusicSource.DEEZER
|
||||
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
private val http = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build()
|
||||
|
||||
override fun search(query: String, limit: Int): List<TrackCandidate> {
|
||||
val count = limit.coerceIn(1, MAX_RESULTS)
|
||||
val url = "$apiBase/search/track?q=${encode(query)}&limit=$count&output=json"
|
||||
return parseDeezerSearch(get(url))
|
||||
}
|
||||
|
||||
override fun resolve(url: String): TrackCandidate? {
|
||||
val trimmed = url.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
|
||||
val trackId = trackIdFrom(trimmed) ?: followShortLink(trimmed)?.let(::trackIdFrom)
|
||||
?: return null
|
||||
return parseDeezerTrack(get("$apiBase/track/$trackId"))
|
||||
}
|
||||
|
||||
private fun get(url: String): String {
|
||||
throttle()
|
||||
val request = HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(timeoutSeconds))
|
||||
.header("Accept", "application/json")
|
||||
.header("User-Agent", "AudioManager/0.1")
|
||||
.GET()
|
||||
.build()
|
||||
val response = try {
|
||||
http.send(request, HttpResponse.BodyHandlers.ofString())
|
||||
} catch (e: Exception) {
|
||||
throw IllegalStateException("Deezer request failed: ${e.message ?: e::class.simpleName}", e)
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw IllegalStateException("Deezer API returned HTTP ${response.statusCode()}")
|
||||
}
|
||||
val body = response.body()
|
||||
if (body.isBlank()) throw IllegalStateException("Deezer API returned an empty response")
|
||||
throwIfError(body)
|
||||
return body
|
||||
}
|
||||
|
||||
/** `deezer.page.link` redirects to a normal deezer.com URL. */
|
||||
private fun followShortLink(url: String): String? {
|
||||
if (!url.contains("deezer.page.link", ignoreCase = true)) return null
|
||||
return runCatching {
|
||||
throttle()
|
||||
val request = HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(timeoutSeconds))
|
||||
.header("User-Agent", "AudioManager/0.1")
|
||||
.GET()
|
||||
.build()
|
||||
http.send(request, HttpResponse.BodyHandlers.discarding()).uri().toString()
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private fun throwIfError(body: String) {
|
||||
val root = runCatching { json.parseToJsonElement(body).jsonObject }.getOrNull() ?: return
|
||||
val error = root["error"] as? JsonObject ?: return
|
||||
val message = error["message"]?.jsonPrimitive?.contentOrNull
|
||||
?: error["type"]?.jsonPrimitive?.contentOrNull
|
||||
?: "Deezer request failed"
|
||||
throw IllegalStateException(message)
|
||||
}
|
||||
|
||||
/** Keeps us well below Deezer's 50 requests per 5 seconds limit. */
|
||||
private fun throttle() {
|
||||
synchronized(throttleLock) {
|
||||
val now = System.nanoTime()
|
||||
val wait = MIN_REQUEST_INTERVAL_NANOS - (now - lastRequestNanos)
|
||||
if (wait > 0) {
|
||||
Thread.sleep(wait / 1_000_000, (wait % 1_000_000).toInt())
|
||||
}
|
||||
lastRequestNanos = System.nanoTime()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_RESULTS = 25
|
||||
const val MIN_REQUEST_INTERVAL_NANOS = 120_000_000L
|
||||
val THROTTLE_LOCK = Any()
|
||||
|
||||
fun encode(value: String): String =
|
||||
URLEncoder.encode(value, Charsets.UTF_8).replace("+", "%20")
|
||||
|
||||
fun trackIdFrom(url: String): String? {
|
||||
val match = TRACK_URL.find(url) ?: return null
|
||||
return match.groupValues[1].takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
val TRACK_URL = Regex("deezer\\.com/(?:[a-z]{2}/)?track/(\\d+)", RegexOption.IGNORE_CASE)
|
||||
}
|
||||
|
||||
private val throttleLock = THROTTLE_LOCK
|
||||
@Volatile
|
||||
private var lastRequestNanos = 0L
|
||||
}
|
||||
|
||||
internal fun parseDeezerSearch(json: String): List<TrackCandidate> {
|
||||
val parsed = runCatching {
|
||||
Json { ignoreUnknownKeys = true; explicitNulls = false }
|
||||
.decodeFromString<DeezerSearchResponse>(json)
|
||||
}.getOrNull() ?: return emptyList()
|
||||
|
||||
return parsed.data.mapNotNull { it.toCandidate() }
|
||||
}
|
||||
|
||||
internal fun parseDeezerTrack(json: String): TrackCandidate? {
|
||||
val parsed = runCatching {
|
||||
Json { ignoreUnknownKeys = true; explicitNulls = false }
|
||||
.decodeFromString<DeezerTrackDto>(json)
|
||||
}.getOrNull() ?: return null
|
||||
return parsed.toCandidate(applyLengthFilter = false)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class DeezerSearchResponse(val data: List<DeezerTrackDto> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class DeezerTrackDto(
|
||||
val id: Long = 0,
|
||||
val title: String = "",
|
||||
val duration: Int = 0,
|
||||
val readable: Boolean = true,
|
||||
val artist: DeezerArtistDto? = null,
|
||||
val album: DeezerAlbumDto? = null,
|
||||
) {
|
||||
fun toCandidate(applyLengthFilter: Boolean = true): TrackCandidate? {
|
||||
if (id <= 0 || !readable) return null
|
||||
if (title.isBlank()) return null
|
||||
val artistName = artist?.name?.takeIf { it.isNotBlank() } ?: return null
|
||||
if (applyLengthFilter && duration > 0 &&
|
||||
duration !in MIN_TRACK_SECONDS..MAX_TRACK_SECONDS
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return TrackCandidate(
|
||||
source = MusicSource.DEEZER,
|
||||
externalId = id.toString(),
|
||||
title = title.trim(),
|
||||
artist = artistName.trim(),
|
||||
album = album?.title?.takeIf { it.isNotBlank() },
|
||||
duration = duration.takeIf { it > 0 },
|
||||
thumbnail = album?.coverBig ?: album?.coverXl ?: album?.coverMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class DeezerArtistDto(val name: String = "")
|
||||
|
||||
@Serializable
|
||||
private data class DeezerAlbumDto(
|
||||
val title: String? = null,
|
||||
@SerialName("cover_big") val coverBig: String? = null,
|
||||
@SerialName("cover_xl") val coverXl: String? = null,
|
||||
@SerialName("cover_medium") val coverMedium: String? = null,
|
||||
)
|
||||
Reference in new issue
Block a user