diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt index 713c2b085..d3991b22a 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt @@ -53,6 +53,7 @@ class MusicViewModel constructor( @ApplicationContext context: Context, private val listSettings: ListSettings, + private val musicSettings: MusicSettings, private val musicRepository: MusicRepository, ) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener { private val externalPlaylistManager = ExternalPlaylistManager.from(context) @@ -160,24 +161,19 @@ constructor( fun importPlaylist(uri: Uri? = null, target: Playlist? = null) { if (uri != null) { 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) { L.e("Could not import playlist") playlistMessage.put(PlaylistMessage.ImportFailed) return@launch } - - 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 - } + val songs = importedPlaylist.songs if (target !== null) { if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) { diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt index 6520b8e28..8fc21da3b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt @@ -20,7 +20,9 @@ package org.oxycblt.musikr.playlist import android.content.Context import android.net.Uri +import org.oxycblt.musikr.Library import org.oxycblt.musikr.Playlist +import org.oxycblt.musikr.Song import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Volume @@ -37,13 +39,16 @@ import org.oxycblt.musikr.playlist.m3u.M3U */ 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. - * @return An [ImportedPlaylist] containing the paths to the files listed in the playlist file, - * or null if the playlist could not be imported. + * @param roots Candidate roots to resolve entries against after the playlist file's own + * 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, library: Library): ImportedPlaylist? /** * Export the given [playlist] to the given [uri]. @@ -60,7 +65,7 @@ interface ExternalPlaylistManager { ExternalPlaylistManagerImpl( 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. * * @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 M3U */ -data class ImportedPlaylist(val name: String?, val paths: List) - -typealias PossiblePaths = List +data class ImportedPlaylist(val name: String?, val songs: List) private class ExternalPlaylistManagerImpl( private val context: Context, private val documentPathFactory: DocumentPathFactory, private val m3u: M3U, ) : ExternalPlaylistManager { - override suspend fun import(uri: Uri): ImportedPlaylist? { + private val resolver = PlaylistPathResolver() + override suspend fun import(uri: Uri, roots: List, library: Library): ImportedPlaylist? { val filePath = documentPathFactory.unpackDocumentUri(uri) ?: Path(Volume.ThirdParty(uri), Components.root()) return try { context.contentResolverSafe.openInputStream(uri)?.use { - val imported = m3u.read(it, filePath.directory) ?: return null - val name = imported.name + val parsed = m3u.read(it) ?: return null + 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) { - return imported + return ImportedPlaylist(name, songs) } // Strip extension - val fileName = filePath.name ?: return imported + val fileName = filePath.name ?: return ImportedPlaylist(null, songs) val split = fileName.split(".") var newName = split[0] // Replace delimiters with space newName = newName.replace(Regex("[_-]"), " ") // Replace long stretches of whitespace with one space newName = newName.replace(Regex("\\s+"), " ") - return ImportedPlaylist(newName, imported.paths) + return ImportedPlaylist(newName, songs) } } catch (e: Exception) { null diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt index 193c5666b..36215ccb6 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt @@ -18,7 +18,6 @@ package org.oxycblt.musikr.playlist.m3u -import android.content.Context import java.io.BufferedReader import java.io.BufferedWriter import java.io.InputStream @@ -27,11 +26,8 @@ import java.io.OutputStream import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.fs.Components 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.ImportedPlaylist -import org.oxycblt.musikr.playlist.PossiblePaths +import org.oxycblt.musikr.playlist.PlaylistPathResolver import org.oxycblt.musikr.tag.Name import org.oxycblt.musikr.util.correctWhitespace import org.oxycblt.musikr.util.unlikelyToBeNull @@ -43,15 +39,13 @@ import org.oxycblt.musikr.util.unlikelyToBeNull */ abstract class M3U { /** - * Reads an M3U file from the given [stream] and returns a [ImportedPlaylist] containing the - * paths to the files listed in the M3U file. + * Reads an M3U file from the given [stream] and returns the parsed [ParsedM3U]. Entries are + * interpreted but not resolved against the library — see [PlaylistPathResolver]. * * @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 - * resolve relative paths. - * @return An [ImportedPlaylist] containing the paths to the files listed in the M3U file, + * @return The [ParsedM3U], or null if the file contained no entries. */ - 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,. @@ -73,15 +67,22 @@ abstract class M3U { /** The mime type used for M3U files by the android system. */ 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? { - val volumes = volumeManager.getVolumes() +/** + * The raw result of parsing an M3U file. + * + * @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) + +private class M3UImpl : M3U() { + override fun read(stream: InputStream): ParsedM3U? { val reader = BufferedReader(InputStreamReader(stream)) - val paths = mutableListOf() + val entries = mutableListOf() var name: String? = null 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 - // based on the programs that generated it. I more or less have to consider any possible - // interpretation as valid. - val interpretations = interpretPath(unlikelyToBeNull(path)) - val possibilities = interpretations.flatMap { - expandInterpretation(it, workingDirectory, volumes) - } - - paths.add(possibilities) + // One interpretation per line: resolution against the library happens later, in + // PlaylistPathResolver. + entries.add(interpretLine(unlikelyToBeNull(path))) } - return if (paths.isNotEmpty()) { - ImportedPlaylist(name, paths) + return if (entries.isNotEmpty()) { + ParsedM3U(name, entries) } else { // Couldn't get anything useful out of this file. null } } - private data class InterpretedPath(val components: Components, val likelyAbsolute: Boolean) - - private fun interpretPath(path: String): List = + /** + * Interpret a line as an entry. There is no formal specification of M3U paths, so the form + * 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 { - path.startsWith('/') -> listOf(InterpretedPath(Components.parseUnix(path), true)) - path.startsWith("./") -> listOf(InterpretedPath(Components.parseUnix(path), false)) + path.startsWith('/') -> + PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = true) + path.startsWith("./") -> + PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false) path.matches(WINDOWS_VOLUME_PREFIX_REGEX) -> - listOf(InterpretedPath(Components.parseWindows(path.substring(2)), true)) - path.startsWith("\\") -> listOf(InterpretedPath(Components.parseWindows(path), true)) - path.startsWith(".\\") -> listOf(InterpretedPath(Components.parseWindows(path), false)) - else -> - listOf( - InterpretedPath(Components.parseUnix(path), false), - InterpretedPath(Components.parseWindows(path), true), + PlaylistPathResolver.Entry( + Components.parseWindows(path.substring(2)), absolute = 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, - ): List { - 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( playlist: Playlist, outputStream: OutputStream, @@ -232,22 +213,6 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() { 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 { // 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 diff --git a/musikr/src/test/java/org/oxycblt/musikr/playlist/m3u/M3UTest.kt b/musikr/src/test/java/org/oxycblt/musikr/playlist/m3u/M3UTest.kt new file mode 100644 index 000000000..02833f5e0 --- /dev/null +++ b/musikr/src/test/java/org/oxycblt/musikr/playlist/m3u/M3UTest.kt @@ -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 . + */ + +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, + ) + } +}