musikr: import and track discovered playlists during indexing

This commit is contained in:
jay
2026-11-12 18:54:33 -05:00
parent f492410484
commit 65bfdf6b7d
9 changed files with 150 additions and 21 deletions
@@ -24,6 +24,9 @@ import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface FS { interface FS {
/** The roots playlist entries resolve against, in precedence order. May be empty. */
val locationRoots: List<Path>
suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> suspend fun explore(files: Channel<File>): Deferred<Result<Unit>>
fun track(): Flow<FSUpdate> fun track(): Flow<FSUpdate>
@@ -35,6 +35,7 @@ import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.FSUpdate import org.oxycblt.musikr.fs.FSUpdate
import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.MediaStorePathInterpreter import org.oxycblt.musikr.fs.path.MediaStorePathInterpreter
import org.oxycblt.musikr.fs.path.VolumeManager import org.oxycblt.musikr.fs.path.VolumeManager
import org.oxycblt.musikr.fs.saf.contentResolverSafe import org.oxycblt.musikr.fs.saf.contentResolverSafe
@@ -54,6 +55,15 @@ private constructor(
) : FS { ) : FS {
private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager) private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager)
// Include-mode filters are the closest thing MediaStore has to configured locations.
override val locationRoots: List<Path>
get() =
if (query.mode == FilterMode.INCLUDE) {
query.filtered.map { it.path }
} else {
emptyList()
}
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope { override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.IO) { channel -> tryAsyncWith(files, Dispatchers.IO) { channel ->
@@ -54,6 +54,9 @@ private constructor(
private val contentResolver: ContentResolver, private val contentResolver: ContentResolver,
private val query: Query, private val query: Query,
) : FS { ) : FS {
override val locationRoots: List<Path>
get() = query.source.map { it.path }
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope { override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.Main) { tryAsyncWith(files, Dispatchers.Main) {
query.source query.source
@@ -19,16 +19,26 @@
package org.oxycblt.musikr.pipeline package org.oxycblt.musikr.pipeline
import android.content.Context import android.content.Context
import java.util.zip.CRC32
import java.util.zip.CheckedInputStream
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.BuildConfig import org.oxycblt.musikr.BuildConfig
import org.oxycblt.musikr.Config import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.MutableLibrary import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.fs.saf.contentResolverSafe
import org.oxycblt.musikr.graph.MusicGraph import org.oxycblt.musikr.graph.MusicGraph
import org.oxycblt.musikr.model.LibraryFactory import org.oxycblt.musikr.model.LibraryFactory
import org.oxycblt.musikr.playlist.PlaylistPathResolver
import org.oxycblt.musikr.playlist.PlaylistReconciler
import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.playlist.m3u.ParsedM3U
import org.oxycblt.musikr.playlist.playlistNameFromFileName
import org.oxycblt.musikr.tag.interpret.PreSong
import org.oxycblt.musikr.tag.interpret.TagInterpreter import org.oxycblt.musikr.tag.interpret.TagInterpreter
internal interface EvaluateStep { internal interface EvaluateStep {
@@ -41,6 +51,7 @@ internal interface EvaluateStep {
fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep = fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep =
EvaluateStepImpl( EvaluateStepImpl(
context, context,
config.fs,
TagInterpreter.new(interpretation), TagInterpreter.new(interpretation),
PlaylistInterpreter.new(interpretation), PlaylistInterpreter.new(interpretation),
config.storage.storedPlaylists, config.storage.storedPlaylists,
@@ -51,6 +62,7 @@ internal interface EvaluateStep {
private class EvaluateStepImpl( private class EvaluateStepImpl(
private val context: Context, private val context: Context,
private val fs: FS,
private val tagInterpreter: TagInterpreter, private val tagInterpreter: TagInterpreter,
private val playlistInterpreter: PlaylistInterpreter, private val playlistInterpreter: PlaylistInterpreter,
private val storedPlaylists: StoredPlaylists, private val storedPlaylists: StoredPlaylists,
@@ -61,15 +73,23 @@ private class EvaluateStepImpl(
playlistFiles: List<File>, playlistFiles: List<File>,
): MutableLibrary { ): MutableLibrary {
val builder = MusicGraph.builder() val builder = MusicGraph.builder()
val preSongs = mutableListOf<PreSong>()
for (extracted in extractedMusic) { for (extracted in extractedMusic) {
when (extracted) { when (extracted) {
is RawSong -> builder.add(tagInterpreter.interpret(extracted)) is RawSong -> {
val preSong = tagInterpreter.interpret(extracted)
preSongs.add(preSong)
builder.add(preSong)
}
is NotAudio -> {} is NotAudio -> {}
is InvalidSong -> {} is InvalidSong -> {}
} }
} }
// Stored playlists enter the graph here, after the songs, so that a reconcile pass can if (playlistFiles.isNotEmpty()) {
// update them first (added in a later change; playlistFiles is threaded for it). reconcilePlaylists(playlistFiles, preSongs)
}
// Stored playlists enter the graph after the reconcile pass, so the graph sees the
// settled state.
for (playlistFile in storedPlaylists.read()) { for (playlistFile in storedPlaylists.read()) {
builder.add(playlistInterpreter.interpret(playlistFile)) builder.add(playlistInterpreter.interpret(playlistFile))
} }
@@ -83,4 +103,77 @@ private class EvaluateStepImpl(
return libraryFactory.create(graph, storedPlaylists, playlistInterpreter) return libraryFactory.create(graph, storedPlaylists, playlistInterpreter)
} }
/**
* Reconcile the discovered playlist files against the tracked store. Each file is parsed,
* signed, and resolved in one pass; the reconciler decides keep/replace/create, and the
* actions are applied to the store before stored playlists feed the graph.
*/
private suspend fun reconcilePlaylists(playlistFiles: List<File>, preSongs: List<PreSong>) {
val resolver = PlaylistPathResolver()
val m3u = M3U.new()
val uidsByPath = preSongs.associate { it.path to it.v363Uid }
val roots = fs.locationRoots
val discoveredFiles = mutableListOf<DiscoveredFile>()
for (file in playlistFiles) {
val crc = CRC32()
val parsed =
context.contentResolverSafe.openInputStream(file.uri)?.use { stream ->
m3u.read(CheckedInputStream(stream, crc))
}
?: continue
val paths =
resolver.resolve(parsed.entries, listOf(file.path.directory) + roots) { path ->
path in uidsByPath
}
discoveredFiles.add(DiscoveredFile(file, parsed, crc.value, paths ?: emptyList()))
}
val actions =
PlaylistReconciler.reconcile(
storedPlaylists.readTracked(),
discoveredFiles.map {
PlaylistReconciler.Discovered(
it.file.uri.toString(),
it.signature,
it.songPaths.size,
)
},
)
for (action in actions) {
when (action) {
is PlaylistReconciler.Action.Keep -> {}
is PlaylistReconciler.Action.Replace -> {
val file =
discoveredFiles.first { it.file.uri.toString() == action.file.uri }
storedPlaylists.replaceTracked(
action.tracked.uid,
file.name(),
file.songPaths.mapNotNull { uidsByPath[it] },
action.file.signature,
)
}
is PlaylistReconciler.Action.Create -> {
val file =
discoveredFiles.first { it.file.uri.toString() == action.file.uri }
storedPlaylists.newTracked(
file.name(),
file.songPaths.mapNotNull { uidsByPath[it] },
file.file.uri.toString(),
action.file.signature,
)
}
}
}
}
private data class DiscoveredFile(
val file: File,
val parsed: ParsedM3U,
val signature: Long,
val songPaths: List<org.oxycblt.musikr.fs.Path>,
) {
/** The playlist's name: the file's #PLAYLIST entry, else derived from the file name. */
fun name() =
parsed.name ?: file.path.name?.let { playlistNameFromFileName(it) } ?: "Playlist"
}
} }
@@ -116,15 +116,8 @@ private class ExternalPlaylistManagerImpl(
if (name != null) { if (name != null) {
return ImportedPlaylist(name, songs) return ImportedPlaylist(name, songs)
} }
// Strip extension
val fileName = filePath.name ?: return ImportedPlaylist(null, songs) val fileName = filePath.name ?: return ImportedPlaylist(null, songs)
val split = fileName.split(".") return ImportedPlaylist(playlistNameFromFileName(fileName), songs)
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, songs)
} }
} catch (e: Exception) { } catch (e: Exception) {
null null
@@ -41,8 +41,15 @@ internal interface PlaylistHandle {
suspend fun rewrite(songs: List<Song>) suspend fun rewrite(songs: List<Song>)
/** Update the stored source-file signature after a re-import. */
suspend fun updateSignature(signature: Long)
suspend fun delete() suspend fun delete()
} }
/** Derive a playlist name from a file name: strip the extension, delimiters become spaces. */
internal fun playlistNameFromFileName(fileName: String): String {
// Strip extension
var name = fileName.split(".")[0]
// Replace delimiters with space
name = name.replace(Regex("[_-]"), " ")
// Replace long stretches of whitespace with one space
return name.replace(Regex("\\s+"), " ")
}
@@ -155,6 +155,12 @@ internal abstract class PlaylistDao {
@Query("SELECT * FROM PlaylistInfo WHERE sourceUri IS NOT NULL AND sourceSignature IS NOT NULL") @Query("SELECT * FROM PlaylistInfo WHERE sourceUri IS NOT NULL AND sourceSignature IS NOT NULL")
abstract suspend fun readTrackedInfos(): List<PlaylistInfo> abstract suspend fun readTrackedInfos(): List<PlaylistInfo>
/** Update the name and source signature of a tracked playlist after a re-import. */
@Query(
"UPDATE PlaylistInfo SET name = :name, sourceSignature = :signature WHERE playlistUid = :playlistUid"
)
abstract suspend fun updateTrackedInfo(playlistUid: Music.UID, name: String, signature: Long)
/** /**
* Create a new playlist. * Create a new playlist.
* *
@@ -35,10 +35,6 @@ internal class StoredPlaylistHandle(
playlistDao.replacePlaylistSongs(uid, songs.map { PlaylistSong(it.uid) }) playlistDao.replacePlaylistSongs(uid, songs.map { PlaylistSong(it.uid) })
} }
override suspend fun updateSignature(signature: Long) {
playlistDao.replacePlaylistInfo(playlistInfo.copy(sourceSignature = signature))
}
override suspend fun add(songs: List<Song>) { override suspend fun add(songs: List<Song>) {
playlistDao.insertPlaylistSongs(uid, songs.map { PlaylistSong(it.uid) }) playlistDao.insertPlaylistSongs(uid, songs.map { PlaylistSong(it.uid) })
} }
@@ -33,11 +33,19 @@ abstract class StoredPlaylists {
/** Create a playlist tracked against a source file. */ /** Create a playlist tracked against a source file. */
internal abstract suspend fun newTracked( internal abstract suspend fun newTracked(
name: String, name: String,
songs: List<Song>, songUids: List<Music.UID>,
sourceUri: String, sourceUri: String,
sourceSignature: Long, sourceSignature: Long,
): PlaylistHandle ): PlaylistHandle
/** Replace a tracked playlist with its re-imported file: new name, songs, and signature. */
internal abstract suspend fun replaceTracked(
playlistUid: Music.UID,
name: String,
songUids: List<Music.UID>,
sourceSignature: Long,
)
/** Read the tracking identities of playlists with a source file. */ /** Read the tracking identities of playlists with a source file. */
internal abstract suspend fun readTracked(): List<PlaylistReconciler.Tracked> internal abstract suspend fun readTracked(): List<PlaylistReconciler.Tracked>
@@ -58,7 +66,7 @@ private class StoredPlaylistsImpl(private val playlistDao: PlaylistDao) : Stored
override suspend fun newTracked( override suspend fun newTracked(
name: String, name: String,
songs: List<Song>, songUids: List<Music.UID>,
sourceUri: String, sourceUri: String,
sourceSignature: Long, sourceSignature: Long,
): PlaylistHandle { ): PlaylistHandle {
@@ -69,10 +77,20 @@ private class StoredPlaylistsImpl(private val playlistDao: PlaylistDao) : Stored
sourceUri = sourceUri, sourceUri = sourceUri,
sourceSignature = sourceSignature, sourceSignature = sourceSignature,
) )
playlistDao.insertPlaylist(RawPlaylist(info, songs.map { PlaylistSong(it.uid) })) playlistDao.insertPlaylist(RawPlaylist(info, songUids.map { PlaylistSong(it) }))
return StoredPlaylistHandle(info, playlistDao) return StoredPlaylistHandle(info, playlistDao)
} }
override suspend fun replaceTracked(
playlistUid: Music.UID,
name: String,
songUids: List<Music.UID>,
sourceSignature: Long,
) {
playlistDao.replacePlaylistSongs(playlistUid, songUids.map { PlaylistSong(it) })
playlistDao.updateTrackedInfo(playlistUid, name, sourceSignature)
}
override suspend fun readTracked() = override suspend fun readTracked() =
playlistDao.readTrackedInfos().map { playlistDao.readTrackedInfos().map {
PlaylistReconciler.Tracked( PlaylistReconciler.Tracked(