diff --git a/musikr/src/main/java/org/oxycblt/musikr/model/SongImpl.kt b/musikr/src/main/java/org/oxycblt/musikr/model/SongImpl.kt
index c06e5d0e1..bd4e92635 100644
--- a/musikr/src/main/java/org/oxycblt/musikr/model/SongImpl.kt
+++ b/musikr/src/main/java/org/oxycblt/musikr/model/SongImpl.kt
@@ -40,7 +40,7 @@ internal interface SongCore {
* @author Alexander Capehart (OxygenCobalt)
*/
internal class SongImpl(private val handle: SongCore) : Song {
- private val preSong = handle.preSong
+ internal val preSong = handle.preSong
override val uid = preSong.v363Uid
diff --git a/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshot.kt b/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshot.kt
new file mode 100644
index 000000000..a28f1e9ad
--- /dev/null
+++ b/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshot.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2026 Auxio Project
+ * LibrarySnapshot.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.snapshot
+
+import android.content.Context
+import java.io.File
+import java.io.InputStream
+import org.oxycblt.musikr.Config
+import org.oxycblt.musikr.Library
+import org.oxycblt.musikr.MutableLibrary
+import org.oxycblt.musikr.model.SongImpl
+import org.oxycblt.musikr.playlist.db.StoredPlaylists
+import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
+import org.oxycblt.musikr.tag.interpret.PreSong
+
+class LibrarySnapshot(private val context: Context, config: Config) {
+ private val storedCoverDirectory = File(context.filesDir, "covers")
+ private val storedPlaylists: StoredPlaylists = config.storage.storedPlaylists
+ private val playlistInterpreter = PlaylistInterpreter.new(config.interpretation)
+
+ suspend fun capture(
+ library: Library,
+ store: LibrarySnapshotStore,
+ fingerprint: LibrarySnapshotFingerprint,
+ ) {
+ val songs =
+ library.songs.map { song ->
+ (song as? SongImpl)?.preSong
+ ?: throw IllegalArgumentException("Snapshot capture requires Musikr songs")
+ }
+ store.replace(
+ write = { LibrarySnapshotDocument.write(it, songs, fingerprint) },
+ verify = { read(it, fingerprint) },
+ )
+ }
+
+ suspend fun restore(
+ store: LibrarySnapshotStore,
+ fingerprint: LibrarySnapshotFingerprint,
+ ): MutableLibrary? = store.load { read(it, fingerprint) }
+
+ private suspend fun read(
+ input: InputStream,
+ fingerprint: LibrarySnapshotFingerprint,
+ ): MutableLibrary =
+ LibrarySnapshotDocument.read(
+ input,
+ fingerprint,
+ storedCoverDirectory,
+ context,
+ storedPlaylists,
+ playlistInterpreter,
+ )
+}
diff --git a/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStore.kt b/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStore.kt
index e52d8c25f..b7a41b6b9 100644
--- a/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStore.kt
+++ b/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStore.kt
@@ -26,6 +26,8 @@ import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import kotlin.coroutines.cancellation.CancellationException
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.ensureActive
class LibrarySnapshotStore
internal constructor(
@@ -48,12 +50,12 @@ internal constructor(
private val snapshot = File(directory, "library.snapshot")
- fun load(read: (InputStream) -> T): T? {
+ suspend fun load(read: suspend (InputStream) -> T): T? {
if (!snapshot.isFile) {
return null
}
return try {
- snapshot.inputStream().use(read)
+ snapshot.inputStream().use { read(it) }
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
@@ -61,14 +63,18 @@ internal constructor(
}
}
- fun replace(write: (OutputStream) -> Unit, verify: (InputStream) -> Unit) {
+ suspend fun replace(
+ write: suspend (OutputStream) -> Unit,
+ verify: suspend (InputStream) -> Unit,
+ ) {
if (!directory.isDirectory && !directory.mkdirs() && !directory.isDirectory) {
throw IOException("Unable to create library snapshot directory")
}
val tempFile = File.createTempFile("${snapshot.name}.", ".tmp", directory)
try {
- tempFile.outputStream().use(write)
- tempFile.inputStream().use(verify)
+ tempFile.outputStream().use { write(it) }
+ tempFile.inputStream().use { verify(it) }
+ currentCoroutineContext().ensureActive()
atomicMove(tempFile.toPath(), snapshot.toPath())
} finally {
tempFile.delete()
diff --git a/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotCaptureTest.kt b/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotCaptureTest.kt
new file mode 100644
index 000000000..cd1943a1e
--- /dev/null
+++ b/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotCaptureTest.kt
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2026 Auxio Project
+ * LibrarySnapshotCaptureTest.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.snapshot
+
+import android.net.Uri
+import io.mockk.coEvery
+import io.mockk.every
+import io.mockk.mockk
+import java.io.File
+import java.io.IOException
+import java.nio.file.AtomicMoveNotSupportedException
+import java.nio.file.Files
+import kotlin.coroutines.cancellation.CancellationException
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertThrows
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.oxycblt.musikr.Config
+import org.oxycblt.musikr.Interpretation
+import org.oxycblt.musikr.Library
+import org.oxycblt.musikr.Music
+import org.oxycblt.musikr.Song
+import org.oxycblt.musikr.Storage
+import org.oxycblt.musikr.fs.Components
+import org.oxycblt.musikr.fs.Format
+import org.oxycblt.musikr.fs.Path
+import org.oxycblt.musikr.fs.path.InternalVolumeValue
+import org.oxycblt.musikr.playlist.PlaylistFile
+import org.oxycblt.musikr.playlist.PlaylistHandle
+import org.oxycblt.musikr.playlist.SongPointer
+import org.oxycblt.musikr.playlist.db.StoredPlaylists
+import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
+import org.oxycblt.musikr.tag.ReleaseType
+import org.oxycblt.musikr.tag.ReplayGainAdjustment
+import org.oxycblt.musikr.tag.interpret.Naming
+import org.oxycblt.musikr.tag.interpret.PreAlbum
+import org.oxycblt.musikr.tag.interpret.PreArtist
+import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
+import org.oxycblt.musikr.tag.interpret.PreGenre
+import org.oxycblt.musikr.tag.interpret.PreSong
+import org.oxycblt.musikr.tag.interpret.Separators
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.annotation.Config as RobolectricConfig
+
+@RunWith(RobolectricTestRunner::class)
+@RobolectricConfig(sdk = [30])
+class LibrarySnapshotCaptureTest {
+ @Test
+ fun capture_completeLibrary_restoresEquivalentGraph() = runBlocking {
+ val storedPlaylists = mockk()
+ val interpretation = Interpretation(Naming.simple(), Separators.from(""))
+ val config = Config(mockk(), Storage(mockk(), mockk(), storedPlaylists), interpretation)
+ val playlistInterpreter = PlaylistInterpreter.new(interpretation)
+ val input = preSong(91, "Captured")
+ val handle = TestPlaylistHandle(playlistUid(91))
+ coEvery { storedPlaylists.read() } returns
+ listOf(PlaylistFile("Bangers", listOf(SongPointer.UID(input.v363Uid)), handle))
+ val original =
+ runBlocking {
+ LibrarySnapshotGraph.restore(
+ listOf(input),
+ storedPlaylists,
+ playlistInterpreter,
+ )
+ }
+ val directory = Files.createTempDirectory("auxio-capture").toFile().apply { deleteOnExit() }
+ val store = LibrarySnapshotStore(directory)
+ val snapshot = LibrarySnapshot(RuntimeEnvironment.getApplication(), config)
+ val fingerprint = fingerprint()
+
+ snapshot.capture(original, store, fingerprint)
+ val restored = requireNotNull(snapshot.restore(store, fingerprint))
+
+ assertEquals(original.songs, restored.songs)
+ assertEquals(original.albums, restored.albums)
+ assertEquals(original.artists, restored.artists)
+ assertEquals(original.genres, restored.genres)
+ assertEquals(original.playlists, restored.playlists)
+ assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
+ }
+
+ @Test
+ fun capture_partialFailureCancellationOrMoveFailure_preservesPreviousValidGraph() =
+ runBlocking {
+ val storedPlaylists = mockk()
+ val interpretation = Interpretation(Naming.simple(), Separators.from(""))
+ val config = Config(mockk(), Storage(mockk(), mockk(), storedPlaylists), interpretation)
+ val playlistInterpreter = PlaylistInterpreter.new(interpretation)
+ val originalInput = preSong(91, "Captured")
+ val updatedInput = preSong(91, "Replacement")
+ val handle = TestPlaylistHandle(playlistUid(91))
+ val liveFile =
+ PlaylistFile(
+ "Bangers",
+ listOf(SongPointer.UID(originalInput.v363Uid)),
+ handle,
+ )
+ coEvery { storedPlaylists.read() } returns listOf(liveFile)
+ val original =
+ LibrarySnapshotGraph.restore(
+ listOf(originalInput),
+ storedPlaylists,
+ playlistInterpreter,
+ )
+ val updated =
+ LibrarySnapshotGraph.restore(
+ listOf(updatedInput),
+ storedPlaylists,
+ playlistInterpreter,
+ )
+ val directory =
+ Files.createTempDirectory("auxio-capture-failure").toFile().apply { deleteOnExit() }
+ val store = LibrarySnapshotStore(directory)
+ val snapshot = LibrarySnapshot(RuntimeEnvironment.getApplication(), config)
+ val fingerprint = fingerprint()
+ snapshot.capture(original, store, fingerprint)
+
+ val partialLibrary = mockk()
+ every { partialLibrary.songs } returns listOf(mockk())
+ assertSuspendThrows {
+ snapshot.capture(partialLibrary, store, fingerprint)
+ }
+ assertPreserved(snapshot, store, fingerprint, original, directory)
+
+ coEvery { storedPlaylists.read() } throws IOException("Forced verification failure")
+ assertSuspendThrows {
+ snapshot.capture(updated, store, fingerprint)
+ }
+ coEvery { storedPlaylists.read() } returns listOf(liveFile)
+ assertPreserved(snapshot, store, fingerprint, original, directory)
+
+ val failedMoveStore =
+ LibrarySnapshotStore(directory) { source, target ->
+ throw AtomicMoveNotSupportedException(
+ source.toString(),
+ target.toString(),
+ "Forced capture move failure",
+ )
+ }
+ assertSuspendThrows {
+ snapshot.capture(updated, failedMoveStore, fingerprint)
+ }
+ assertPreserved(snapshot, store, fingerprint, original, directory)
+
+ val cancelled = Job().apply { cancel() }
+ assertSuspendThrows {
+ withContext(cancelled) { snapshot.capture(updated, store, fingerprint) }
+ }
+ assertPreserved(snapshot, store, fingerprint, original, directory)
+ }
+
+ private inline fun assertSuspendThrows(
+ noinline block: suspend () -> Unit
+ ) {
+ assertThrows(T::class.java) { runBlocking { block() } }
+ }
+
+ private suspend fun assertPreserved(
+ snapshot: LibrarySnapshot,
+ store: LibrarySnapshotStore,
+ fingerprint: LibrarySnapshotFingerprint,
+ original: Library,
+ directory: File,
+ ) {
+ val restored = requireNotNull(snapshot.restore(store, fingerprint))
+ assertEquals(original.songs, restored.songs)
+ assertEquals(original.playlists, restored.playlists)
+ assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
+ }
+
+ private fun fingerprint() =
+ LibrarySnapshotFingerprint(
+ sourceMode = "SAF",
+ sourceRoots = listOf("content://tree/Development/Music"),
+ excludedRoots = emptyList(),
+ withHidden = false,
+ excludeNonMusic = false,
+ intelligentSorting = true,
+ separators = ",;",
+ coverMode = "BALANCED",
+ )
+
+ private fun preSong(suffix: Int, name: String): PreSong {
+ val artist = PreArtist(null, Naming.simple().name("Artist", null), "Artist")
+ return PreSong(
+ v363Uid = songUid(suffix),
+ v400Uid = songUid(suffix + 1_000),
+ v401Uid = songUid(suffix + 2_000),
+ musicBrainzId = null,
+ name = Naming.simple().name(name, null),
+ rawName = name,
+ track = 1,
+ disc = null,
+ date = null,
+ uri = Uri.parse("content://snapshot/${songUid(suffix)}"),
+ path =
+ Path(
+ InternalVolumeValue(
+ null,
+ Components.parseUnix("/storage/emulated/0"),
+ "Internal shared storage",
+ ),
+ Components.parseUnix("Download/$name.mp3"),
+ ),
+ format = Format.MPEG3,
+ size = 1_024L,
+ durationMs = 60_000L,
+ bitrateKbps = 128,
+ sampleRateHz = 44_100,
+ replayGainAdjustment = ReplayGainAdjustment(null, null),
+ modifiedMs = 100L,
+ addedMs = 200L,
+ cover = null,
+ preAlbum =
+ PreAlbum(
+ null,
+ Naming.simple().name("Album", null),
+ "Album",
+ ReleaseType.Album(null),
+ PreArtistsFrom.Album(listOf(artist)),
+ ),
+ preArtists = listOf(artist),
+ preGenres = listOf(PreGenre(Naming.simple().name("Genre", null), "Genre")),
+ )
+ }
+
+ private fun songUid(suffix: Int) =
+ requireNotNull(
+ Music.UID.fromString("uas00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
+ )
+
+ private fun playlistUid(suffix: Int) =
+ requireNotNull(
+ Music.UID.fromString("uap00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
+ )
+
+ private class TestPlaylistHandle(override val uid: Music.UID) : PlaylistHandle {
+ override suspend fun rename(name: String) {}
+
+ override suspend fun add(songs: List) {}
+
+ override suspend fun rewrite(songs: List) {}
+
+ override suspend fun delete() {}
+ }
+}
diff --git a/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotFingerprintTest.kt b/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotFingerprintTest.kt
index 913ca72f0..39617f774 100644
--- a/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotFingerprintTest.kt
+++ b/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotFingerprintTest.kt
@@ -118,7 +118,7 @@ class LibrarySnapshotFingerprintTest {
}
@Test
- fun mismatchedFingerprint_storeFallsBackAndPreservesUnrelatedCache() {
+ fun mismatchedFingerprint_storeFallsBackAndPreservesUnrelatedCache() = runBlocking {
val root = Files.createTempDirectory("auxio-fingerprint-store").toFile().apply { deleteOnExit() }
val directory = File(root, "snapshots")
val cache = File(root, "tag-cache.db").apply { writeText("preserve-tags") }
diff --git a/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStoreTest.kt b/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStoreTest.kt
index 2f19c7969..eda0d59b0 100644
--- a/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStoreTest.kt
+++ b/musikr/src/test/java/org/oxycblt/musikr/snapshot/LibrarySnapshotStoreTest.kt
@@ -27,6 +27,7 @@ import java.io.OutputStream
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import kotlin.coroutines.cancellation.CancellationException
+import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@@ -35,7 +36,7 @@ import org.junit.Test
class LibrarySnapshotStoreTest {
@Test
- fun load_missingSnapshot_returnsNullWithoutCreatingDirectory() {
+ fun load_missingSnapshot_returnsNullWithoutCreatingDirectory() = runBlocking {
val root = Files.createTempDirectory("auxio-store-missing").toFile().apply { deleteOnExit() }
val directory = File(root, "snapshots")
val store = LibrarySnapshotStore(directory)
@@ -47,7 +48,7 @@ class LibrarySnapshotStoreTest {
}
@Test
- fun replace_validSnapshot_verifiesContentsAndCleansTemporaryFiles() {
+ fun replace_validSnapshot_verifiesContentsAndCleansTemporaryFiles() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-valid").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
@@ -67,7 +68,7 @@ class LibrarySnapshotStoreTest {
}
@Test
- fun load_corruptOrTruncatedSnapshot_fallsBackWithoutTouchingOtherFiles() {
+ fun load_corruptOrTruncatedSnapshot_fallsBackWithoutTouchingOtherFiles() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-invalid").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
val snapshot = File(directory, "library.snapshot")
@@ -89,7 +90,7 @@ class LibrarySnapshotStoreTest {
}
@Test
- fun replace_failedWriteVerificationCancellationOrMove_preservesPreviousAndCleansTemps() {
+ fun replace_failedWriteVerificationCancellationOrMove_preservesPreviousAndCleansTemps() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-failed").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
store.replace(
@@ -97,7 +98,7 @@ class LibrarySnapshotStoreTest {
verify = { assertEquals("stable", readSnapshot(it)) },
)
- assertThrows(IllegalStateException::class.java) {
+ assertSuspendThrows {
store.replace(
write = {
writeSnapshot(it, "write-failed")
@@ -108,7 +109,7 @@ class LibrarySnapshotStoreTest {
}
assertEquals("stable", store.load(::readSnapshot))
- assertThrows(CancellationException::class.java) {
+ assertSuspendThrows {
store.replace(
write = {
writeSnapshot(it, "cancelled")
@@ -123,7 +124,7 @@ class LibrarySnapshotStoreTest {
LibrarySnapshotCodec.writeHeader(truncated)
LibrarySnapshotCodec.writeInt(truncated, 10)
truncated.write('v'.code)
- assertThrows(EOFException::class.java) {
+ assertSuspendThrows {
store.replace(
write = { it.write(truncated.toByteArray()) },
verify = { readSnapshot(it) },
@@ -139,7 +140,7 @@ class LibrarySnapshotStoreTest {
"Forced move failure",
)
}
- assertThrows(AtomicMoveNotSupportedException::class.java) {
+ assertSuspendThrows {
failedMoveStore.replace(
write = { writeSnapshot(it, "move-failed") },
verify = { assertEquals("move-failed", readSnapshot(it)) },
@@ -149,6 +150,12 @@ class LibrarySnapshotStoreTest {
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
+ private inline fun assertSuspendThrows(
+ noinline block: suspend () -> Unit
+ ) {
+ org.junit.Assert.assertThrows(T::class.java) { runBlocking { block() } }
+ }
+
private fun writeSnapshot(output: OutputStream, value: String) {
LibrarySnapshotCodec.writeHeader(output)
LibrarySnapshotCodec.writeString(output, value)