package dev.stave.upnp
import dev.stave.domain.model.DidlItem
import javax.inject.Inject
import javax.inject.Singleton
/**
* Recursively walks a UPnP ContentDirectory container and flattens every descendant [DidlItem.Track]
* into a single list. Needed because "Queue this artist" or "Play all Jazz" can't map to a single
* Browse() call — the tracks live two or three levels down (Artist → Albums → Tracks, Genre →
* Artists → Albums → Tracks).
*
* Intentionally sequential: parallel browsing would saturate a single-threaded MinimServer install
* on an older NAS and interleave output in ways that corrupt track order within an album. Order
* matters — users expect an album's tracks to arrive in disc/track order, not in whatever order
* HTTP responses race back.
*/
@Singleton
class MediaCollector @Inject constructor(
private val cd: ContentDirectoryClient,
) {
/**
* Gather every playable track under [containerId], walking up to [maxDepth] levels deep.
* Depth is bounded because some pathological server configurations (or self-referential
* playlists) can loop, and a user triggering "Play genre" should never hang the app.
*
* Returns an empty list on any Browse failure — partial results would be confusing ("why
* did it play 40 of 60 tracks?") so we prefer all-or-nothing per top-level call.
*/
suspend fun collectTracks(
udn: String,
containerId: String,
maxDepth: Int = 8,
): List<DidlItem.Track> {
val out = mutableListOf<DidlItem.Track>()
val ok = collect(udn, containerId, depth = 0, maxDepth, out)
return if (ok) out else emptyList()
}
private suspend fun collect(
udn: String,
containerId: String,
depth: Int,
maxDepth: Int,
out: MutableList<DidlItem.Track>,
): Boolean {
if (depth > maxDepth) return true // treat depth cap as a soft stop, not a failure
return when (val result = cd.browse(udn, containerId)) {
is BrowseResult.Success -> {
for (item in result.items) {
when (item) {
is DidlItem.Track -> out += item
is DidlItem.Container -> {
// MinimServer's synthetic entries (">> Show All", "[folder view]",
// "[untagged]") expose the same tracks that are already reachable
// through the tagged hierarchy. Following them would double- or
// triple-count tracks in the collected list.
if (item.isSynthetic) continue
val childOk = collect(udn, item.id, depth + 1, maxDepth, out)
if (!childOk) return false
}
}
}
true
}
is BrowseResult.Failure -> false
}
}
}