musikr: resolve playlist imports by probe-and-lock

This commit is contained in:
jay
2026-11-12 18:17:03 -05:00
parent a9f6c82041
commit e4cca068db
4 changed files with 131 additions and 104 deletions
@@ -53,6 +53,7 @@ class MusicViewModel
constructor( constructor(
@ApplicationContext context: Context, @ApplicationContext context: Context,
private val listSettings: ListSettings, private val listSettings: ListSettings,
private val musicSettings: MusicSettings,
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener { ) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener {
private val externalPlaylistManager = ExternalPlaylistManager.from(context) private val externalPlaylistManager = ExternalPlaylistManager.from(context)
@@ -160,24 +161,19 @@ constructor(
fun importPlaylist(uri: Uri? = null, target: Playlist? = null) { fun importPlaylist(uri: Uri? = null, target: Playlist? = null) {
if (uri != null) { if (uri != null) {
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
val importedPlaylist = externalPlaylistManager.import(uri) val library = musicRepository.library ?: return@launch
val importedPlaylist =
externalPlaylistManager.import(
uri,
musicSettings.safQuery.source.map { it.path },
library,
)
if (importedPlaylist == null) { if (importedPlaylist == null) {
L.e("Could not import playlist") L.e("Could not import playlist")
playlistMessage.put(PlaylistMessage.ImportFailed) playlistMessage.put(PlaylistMessage.ImportFailed)
return@launch return@launch
} }
val songs = importedPlaylist.songs
val library = musicRepository.library ?: return@launch
val songs =
importedPlaylist.paths.mapNotNull {
it.firstNotNullOfOrNull(library::findSongByPath)
}
if (songs.isEmpty()) {
L.e("No songs found")
playlistMessage.put(PlaylistMessage.ImportFailed)
return@launch
}
if (target !== null) { if (target !== null) {
if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) { if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) {
@@ -20,7 +20,9 @@ package org.oxycblt.musikr.playlist
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume import org.oxycblt.musikr.fs.Volume
@@ -37,13 +39,16 @@ import org.oxycblt.musikr.playlist.m3u.M3U
*/ */
interface ExternalPlaylistManager { interface ExternalPlaylistManager {
/** /**
* Import the playli L.d("Unable to extract bit rate field") st file at the given [uri]. * Import the playlist file at the given [uri].
* *
* @param uri The [Uri] of the playlist file to import. * @param uri The [Uri] of the playlist file to import.
* @return An [ImportedPlaylist] containing the paths to the files listed in the playlist file, * @param roots Candidate roots to resolve entries against after the playlist file's own
* or null if the playlist could not be imported. * directory, in precedence order. Usually the configured music locations.
* @param library The [Library] to resolve entries against.
* @return An [ImportedPlaylist] containing the resolved songs, or null if the playlist could
* not be imported or no entry resolved.
*/ */
suspend fun import(uri: Uri): ImportedPlaylist? suspend fun import(uri: Uri, roots: List<Path>, library: Library): ImportedPlaylist?
/** /**
* Export the given [playlist] to the given [uri]. * Export the given [playlist] to the given [uri].
@@ -60,7 +65,7 @@ interface ExternalPlaylistManager {
ExternalPlaylistManagerImpl( ExternalPlaylistManagerImpl(
context, context,
DocumentPathFactory.from(context), DocumentPathFactory.from(context),
M3U.from(context), M3U.new(),
) )
} }
} }
@@ -80,40 +85,46 @@ data class ExportConfig(val absolute: Boolean, val windowsPaths: Boolean)
* A playlist that has been imported. * A playlist that has been imported.
* *
* @property name The name of the playlist. May be null if not provided. * @property name The name of the playlist. May be null if not provided.
* @property paths The paths of the files in the playlist. * @property songs The resolved songs of the playlist, in file order. Entries that did not
* resolve are dropped.
* @see ExternalPlaylistManager * @see ExternalPlaylistManager
* @see M3U * @see M3U
*/ */
data class ImportedPlaylist(val name: String?, val paths: List<PossiblePaths>) data class ImportedPlaylist(val name: String?, val songs: List<Song>)
typealias PossiblePaths = List<Path>
private class ExternalPlaylistManagerImpl( private class ExternalPlaylistManagerImpl(
private val context: Context, private val context: Context,
private val documentPathFactory: DocumentPathFactory, private val documentPathFactory: DocumentPathFactory,
private val m3u: M3U, private val m3u: M3U,
) : ExternalPlaylistManager { ) : ExternalPlaylistManager {
override suspend fun import(uri: Uri): ImportedPlaylist? { private val resolver = PlaylistPathResolver()
override suspend fun import(uri: Uri, roots: List<Path>, library: Library): ImportedPlaylist? {
val filePath = val filePath =
documentPathFactory.unpackDocumentUri(uri) documentPathFactory.unpackDocumentUri(uri)
?: Path(Volume.ThirdParty(uri), Components.root()) ?: Path(Volume.ThirdParty(uri), Components.root())
return try { return try {
context.contentResolverSafe.openInputStream(uri)?.use { context.contentResolverSafe.openInputStream(uri)?.use {
val imported = m3u.read(it, filePath.directory) ?: return null val parsed = m3u.read(it) ?: return null
val name = imported.name val paths =
resolver.resolve(parsed.entries, listOf(filePath.directory) + roots) { path ->
library.findSongByPath(path) != null
}
?: return null
val songs = paths.mapNotNull(library::findSongByPath)
val name = parsed.name
if (name != null) { if (name != null) {
return imported return ImportedPlaylist(name, songs)
} }
// Strip extension // Strip extension
val fileName = filePath.name ?: return imported val fileName = filePath.name ?: return ImportedPlaylist(null, songs)
val split = fileName.split(".") val split = fileName.split(".")
var newName = split[0] var newName = split[0]
// Replace delimiters with space // Replace delimiters with space
newName = newName.replace(Regex("[_-]"), " ") newName = newName.replace(Regex("[_-]"), " ")
// Replace long stretches of whitespace with one space // Replace long stretches of whitespace with one space
newName = newName.replace(Regex("\\s+"), " ") newName = newName.replace(Regex("\\s+"), " ")
return ImportedPlaylist(newName, imported.paths) return ImportedPlaylist(newName, songs)
} }
} catch (e: Exception) { } catch (e: Exception) {
null null
@@ -18,7 +18,6 @@
package org.oxycblt.musikr.playlist.m3u package org.oxycblt.musikr.playlist.m3u
import android.content.Context
import java.io.BufferedReader import java.io.BufferedReader
import java.io.BufferedWriter import java.io.BufferedWriter
import java.io.InputStream import java.io.InputStream
@@ -27,11 +26,8 @@ import java.io.OutputStream
import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
import org.oxycblt.musikr.fs.path.VolumeManager
import org.oxycblt.musikr.playlist.ExportConfig import org.oxycblt.musikr.playlist.ExportConfig
import org.oxycblt.musikr.playlist.ImportedPlaylist import org.oxycblt.musikr.playlist.PlaylistPathResolver
import org.oxycblt.musikr.playlist.PossiblePaths
import org.oxycblt.musikr.tag.Name import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.util.correctWhitespace import org.oxycblt.musikr.util.correctWhitespace
import org.oxycblt.musikr.util.unlikelyToBeNull import org.oxycblt.musikr.util.unlikelyToBeNull
@@ -43,15 +39,13 @@ import org.oxycblt.musikr.util.unlikelyToBeNull
*/ */
abstract class M3U { abstract class M3U {
/** /**
* Reads an M3U file from the given [stream] and returns a [ImportedPlaylist] containing the * Reads an M3U file from the given [stream] and returns the parsed [ParsedM3U]. Entries are
* paths to the files listed in the M3U file. * interpreted but not resolved against the library — see [PlaylistPathResolver].
* *
* @param stream The stream to read the M3U file from. * @param stream The stream to read the M3U file from.
* @param workingDirectory The directory that the M3U file is contained in. This is used to * @return The [ParsedM3U], or null if the file contained no entries.
* resolve relative paths.
* @return An [ImportedPlaylist] containing the paths to the files listed in the M3U file,
*/ */
internal abstract fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist? internal abstract fun read(stream: InputStream): ParsedM3U?
/** /**
* Writes the given [playlist] to the given [outputStream] in the M3U format,. * Writes the given [playlist] to the given [outputStream] in the M3U format,.
@@ -73,15 +67,22 @@ abstract class M3U {
/** The mime type used for M3U files by the android system. */ /** The mime type used for M3U files by the android system. */
const val MIME_TYPE = "audio/x-mpegurl" const val MIME_TYPE = "audio/x-mpegurl"
internal fun from(context: Context): M3U = M3UImpl(VolumeManager.from(context)) internal fun new(): M3U = M3UImpl()
} }
} }
private class M3UImpl(private val volumeManager: VolumeManager) : M3U() { /**
override fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist? { * The raw result of parsing an M3U file.
val volumes = volumeManager.getVolumes() *
* @property name The playlist name, if a #PLAYLIST entry was present.
* @property entries The parsed entries in file order.
*/
internal data class ParsedM3U(val name: String?, val entries: List<PlaylistPathResolver.Entry>)
private class M3UImpl : M3U() {
override fun read(stream: InputStream): ParsedM3U? {
val reader = BufferedReader(InputStreamReader(stream)) val reader = BufferedReader(InputStreamReader(stream))
val paths = mutableListOf<PossiblePaths>() val entries = mutableListOf<PlaylistPathResolver.Entry>()
var name: String? = null var name: String? = null
consumeFile@ while (true) { consumeFile@ while (true) {
@@ -112,63 +113,43 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
} }
} }
// There is basically no formal specification of file paths in M3U, and it differs // One interpretation per line: resolution against the library happens later, in
// based on the programs that generated it. I more or less have to consider any possible // PlaylistPathResolver.
// interpretation as valid. entries.add(interpretLine(unlikelyToBeNull(path)))
val interpretations = interpretPath(unlikelyToBeNull(path))
val possibilities = interpretations.flatMap {
expandInterpretation(it, workingDirectory, volumes)
}
paths.add(possibilities)
} }
return if (paths.isNotEmpty()) { return if (entries.isNotEmpty()) {
ImportedPlaylist(name, paths) ParsedM3U(name, entries)
} else { } else {
// Couldn't get anything useful out of this file. // Couldn't get anything useful out of this file.
null null
} }
} }
private data class InterpretedPath(val components: Components, val likelyAbsolute: Boolean) /**
* Interpret a line as an entry. There is no formal specification of M3U paths, so the form
private fun interpretPath(path: String): List<InterpretedPath> = * detection is heuristic: unix or windows, absolute or relative. Bare lines parse by
* whichever separator they contain.
*/
private fun interpretLine(path: String): PlaylistPathResolver.Entry =
when { when {
path.startsWith('/') -> listOf(InterpretedPath(Components.parseUnix(path), true)) path.startsWith('/') ->
path.startsWith("./") -> listOf(InterpretedPath(Components.parseUnix(path), false)) PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = true)
path.startsWith("./") ->
PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
path.matches(WINDOWS_VOLUME_PREFIX_REGEX) -> path.matches(WINDOWS_VOLUME_PREFIX_REGEX) ->
listOf(InterpretedPath(Components.parseWindows(path.substring(2)), true)) PlaylistPathResolver.Entry(
path.startsWith("\\") -> listOf(InterpretedPath(Components.parseWindows(path), true)) Components.parseWindows(path.substring(2)), absolute = true
path.startsWith(".\\") -> listOf(InterpretedPath(Components.parseWindows(path), false))
else ->
listOf(
InterpretedPath(Components.parseUnix(path), false),
InterpretedPath(Components.parseWindows(path), true),
) )
path.startsWith("\\") ->
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = true)
path.startsWith(".\\") ->
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
'\\' in path ->
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
else -> PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
} }
private fun expandInterpretation(
path: InterpretedPath,
workingDirectory: Path,
volumes: List<Volume>,
): List<Path> {
val absoluteInterpretation = Path(workingDirectory.volume, path.components)
val relativeInterpretation =
Path(workingDirectory.volume, path.components.absoluteTo(workingDirectory.components))
val volumeExactMatch = volumes.find { it.components?.contains(path.components) == true }
val volumeInterpretation = volumeExactMatch?.let {
val components =
unlikelyToBeNull(volumeExactMatch.components).containing(path.components)
Path(volumeExactMatch, components)
}
return if (path.likelyAbsolute) {
listOfNotNull(volumeInterpretation, absoluteInterpretation, relativeInterpretation)
} else {
listOfNotNull(relativeInterpretation, volumeInterpretation, absoluteInterpretation)
}
}
override fun write( override fun write(
playlist: Playlist, playlist: Playlist,
outputStream: OutputStream, outputStream: OutputStream,
@@ -232,22 +213,6 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
newLine() newLine()
} }
private fun Components.absoluteTo(workingDirectory: Components): Components {
var absoluteComponents = workingDirectory
for (component in components) {
when (component) {
// Parent specifier, go "back" one directory (in practice cleave off the last
// component)
".." -> absoluteComponents = absoluteComponents.parent()
// Current directory, the components are already there.
"." -> {}
// New directory, add it
else -> absoluteComponents = absoluteComponents.child(component)
}
}
return absoluteComponents
}
private fun Components.relativeTo(workingDirectory: Components): Components { private fun Components.relativeTo(workingDirectory: Components): Components {
// We want to find the common prefix of the working directory and path, and then // We want to find the common prefix of the working directory and path, and then
// and them combine them with the correct relative elements to make sure they // and them combine them with the correct relative elements to make sure they
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2026 Auxio Project
* M3UTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.playlist.m3u
import org.junit.Assert.assertEquals
import org.junit.Test
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.playlist.PlaylistPathResolver
class M3UTest {
@Test
fun read_relativeAndForeignAbsoluteLines_produceEntries() {
val text =
"""
#EXTM3U
Library/Artist/a.mp3
./Library/Artist/b.mp3
C:\Users\me\Music\Library\Artist\c.mp3
"""
.trimIndent()
val imported = M3U.new().read(text.byteInputStream())
assertEquals(
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("./Library/Artist/b.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Users/me/Music/Library/Artist/c.mp3"), absolute = true
),
),
imported?.entries,
)
}
}