From 6a42f7c5d27fa27a7b858c04f6dd8ac28e6ecee1 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 22 Mar 2025 10:55:50 -0600 Subject: [PATCH 01/38] musikr: test tagparser Created by claude 3.7 --- .../oxycblt/musikr/tag/parse/TagFieldsTest.kt | 335 ++++++++++++++++++ .../oxycblt/musikr/tag/parse/TagParserTest.kt | 178 ++++++++++ .../tag/parse/TagParsingEdgeCasesTest.kt | 280 +++++++++++++++ 3 files changed, 793 insertions(+) create mode 100644 musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt create mode 100644 musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt create mode 100644 musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt new file mode 100644 index 000000000..9409f32e7 --- /dev/null +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt @@ -0,0 +1,335 @@ +/* + * Copyright (c) 2024 Auxio Project + * TagFieldsTest.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.tag.parse + +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.oxycblt.musikr.metadata.Metadata +import org.oxycblt.musikr.metadata.Properties +import org.oxycblt.musikr.tag.Date + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [30]) +class TagFieldsTest { + + @Test + fun metadata_name_formats() { + // Test ID3v2 format + var metadata = createTestMetadata(id3v2Tags = mapOf("TIT2" to listOf("ID3 Title"))) + assertEquals("ID3 Title", metadata.name()) + + // Test MP4 format + metadata = createTestMetadata(mp4Tags = mapOf("©nam" to listOf("MP4 Title"))) + assertEquals("MP4 Title", metadata.name()) + + // Test Xiph format + metadata = createTestMetadata(xiphTags = mapOf("TITLE" to listOf("Xiph Title"))) + assertEquals("Xiph Title", metadata.name()) + + // Test priority (xiph > mp4 > id3v2) + metadata = createTestMetadata( + id3v2Tags = mapOf("TIT2" to listOf("ID3 Title")), + mp4Tags = mapOf("©nam" to listOf("MP4 Title")), + xiphTags = mapOf("TITLE" to listOf("Xiph Title")) + ) + assertEquals("Xiph Title", metadata.name()) + } + + @Test + fun metadata_track_formats() { + // Test ID3v2 format + var metadata = createTestMetadata(id3v2Tags = mapOf("TRCK" to listOf("5/10"))) + assertEquals(5, metadata.track()) + + // Test ID3v2 format without total + metadata = createTestMetadata(id3v2Tags = mapOf("TRCK" to listOf("5"))) + assertEquals(5, metadata.track()) + + // Test MP4 format + metadata = createTestMetadata(mp4Tags = mapOf("trkn" to listOf("7/12"))) + assertEquals(7, metadata.track()) + + // Test Xiph format + metadata = createTestMetadata( + xiphTags = mapOf( + "TRACKNUMBER" to listOf("9"), + "TOTALTRACKS" to listOf("15") + ) + ) + assertEquals(9, metadata.track()) + + // Test Xiph alternative total tracks + metadata = createTestMetadata( + xiphTags = mapOf( + "TRACKNUMBER" to listOf("8"), + "TRACKTOTAL" to listOf("16") + ) + ) + assertEquals(8, metadata.track()) + } + + @Test + fun metadata_disc_formats() { + // Test ID3v2 format + var metadata = createTestMetadata(id3v2Tags = mapOf("TPOS" to listOf("2/3"))) + assertEquals(2, metadata.disc()) + + // Test MP4 format + metadata = createTestMetadata(mp4Tags = mapOf("disk" to listOf("1/2"))) + assertEquals(1, metadata.disc()) + + // Test Xiph format + metadata = createTestMetadata( + xiphTags = mapOf( + "DISCNUMBER" to listOf("3"), + "TOTALDISCS" to listOf("4") + ) + ) + assertEquals(3, metadata.disc()) + + // Test Xiph alternative total discs + metadata = createTestMetadata( + xiphTags = mapOf( + "DISCNUMBER" to listOf("2"), + "DISCTOTAL" to listOf("5") + ) + ) + assertEquals(2, metadata.disc()) + } + + @Test + fun metadata_subtitle() { + var metadata = createTestMetadata(id3v2Tags = mapOf("TSST" to listOf("Bonus Disc"))) + assertEquals("Bonus Disc", metadata.subtitle()) + + metadata = createTestMetadata(xiphTags = mapOf("DISCSUBTITLE" to listOf("Rarities"))) + assertEquals("Rarities", metadata.subtitle()) + + // Test priority + metadata = createTestMetadata( + id3v2Tags = mapOf("TSST" to listOf("ID3 Subtitle")), + xiphTags = mapOf("DISCSUBTITLE" to listOf("Xiph Subtitle")) + ) + assertEquals("Xiph Subtitle", metadata.subtitle()) + } + + @Test + fun metadata_date_formats() { + // Test simple year + var metadata = createTestMetadata(id3v2Tags = mapOf("TDRC" to listOf("2022"))) + assertEquals("2022", metadata.date().toString()) + + // Test ISO-8601 date + metadata = createTestMetadata(id3v2Tags = mapOf("TDRC" to listOf("2022-05-17"))) + assertEquals("2022-05-17", metadata.date().toString()) + + // Test ISO-8601 datetime + metadata = createTestMetadata(id3v2Tags = mapOf("TDRC" to listOf("2022-05-17T14:30:00"))) + assertEquals("2022-05-17T14:30:00Z", metadata.date().toString()) + + // Test Xiph date + metadata = createTestMetadata(xiphTags = mapOf("DATE" to listOf("2021-12-25"))) + assertEquals("2021-12-25", metadata.date().toString()) + + // Test date priority (ORIGINALDATE > DATE) + metadata = createTestMetadata( + xiphTags = mapOf( + "DATE" to listOf("2023-01-01"), + "ORIGINALDATE" to listOf("2021-01-01") + ) + ) + assertEquals("2021-01-01", metadata.date().toString()) + + // Test MP4 date + metadata = createTestMetadata(mp4Tags = mapOf("©day" to listOf("2020-11-30"))) + assertEquals("2020-11-30", metadata.date().toString()) + } + + @Test + fun metadata_id3v23Date() { + // Test ID3v2.3 date components + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TYER" to listOf("2019"), + "TDAT" to listOf("0523"), // May 23 + "TIME" to listOf("2145") // 21:45 + ) + ) + val date = metadata.date() + assertEquals(2019, date?.year) + assertEquals(5, date?.month) + assertEquals(23, date?.day) + assertEquals(21, date?.hour) + assertEquals(45, date?.minute) + } + + @Test + fun metadata_albumInfo() { + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TALB" to listOf("Album Name"), + "TSOA" to listOf("Sort Album Name"), + "TXXX:RELEASETYPE" to listOf("compilation") + ) + ) + + assertEquals("Album Name", metadata.albumName()) + assertEquals("Sort Album Name", metadata.albumSortName()) + assertEquals(listOf("compilation"), metadata.releaseTypes()) + } + + @Test + fun metadata_artistInfo() { + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TPE1" to listOf("Artist 1"), + "TPE2" to listOf("Album Artist 1"), + "TSOP" to listOf("Artist 1 Sort"), + "TSO2" to listOf("Album Artist 1 Sort") + ) + ) + + assertEquals(listOf("Artist 1"), metadata.artistNames()) + assertEquals(listOf("Album Artist 1"), metadata.albumArtistNames()) + assertEquals(listOf("Artist 1 Sort"), metadata.artistSortNames()) + assertEquals(listOf("Album Artist 1 Sort"), metadata.albumArtistSortNames()) + } + + @Test + fun metadata_musicBrainzIds() { + // Test different formats and variants of MusicBrainz identifiers + val metadata = createTestMetadata( + xiphTags = mapOf( + "MUSICBRAINZ_RELEASETRACKID" to listOf("track-mb-id"), + "MUSICBRAINZ_ALBUMID" to listOf("album-mb-id") + ) + ) + + assertEquals("track-mb-id", metadata.musicBrainzId()) + assertEquals("album-mb-id", metadata.albumMusicBrainzId()) + + // Test Apple iTunes MP4 variants + val metadata2 = createTestMetadata( + mp4Tags = mapOf( + "----:COM.APPLE.ITUNES:MUSICBRAINZ RELEASE TRACK ID" to listOf("track-mb-id-2"), + "----:COM.APPLE.ITUNES:MUSICBRAINZ ALBUM ID" to listOf("album-mb-id-2") + ) + ) + + assertEquals("track-mb-id-2", metadata2.musicBrainzId()) + assertEquals("album-mb-id-2", metadata2.albumMusicBrainzId()) + } + + @Test + fun metadata_isCompilation() { + // Test various compilation flags + var metadata = createTestMetadata( + id3v2Tags = mapOf("TCMP" to listOf("1")) + ) + assertTrue(metadata.isCompilation()) + + metadata = createTestMetadata( + id3v2Tags = mapOf("TCMP" to listOf("0")) + ) + assertFalse(metadata.isCompilation()) + + metadata = createTestMetadata( + xiphTags = mapOf("COMPILATION" to listOf("1")) + ) + assertTrue(metadata.isCompilation()) + + metadata = createTestMetadata( + mp4Tags = mapOf("cpil" to listOf("1")) + ) + assertTrue(metadata.isCompilation()) + + // Test invalid value + metadata = createTestMetadata( + id3v2Tags = mapOf("TCMP" to listOf("yes")) + ) + assertFalse(metadata.isCompilation()) + } + + @Test + fun metadata_replayGain() { + // Test ReplayGain track adjustment + var metadata = createTestMetadata( + xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("-5.5 dB")) + ) + assertEquals(-5.5f, metadata.replayGainTrackAdjustment()) + + // Test ReplayGain album adjustment + metadata = createTestMetadata( + xiphTags = mapOf("REPLAYGAIN_ALBUM_GAIN" to listOf("3.2 dB")) + ) + assertEquals(3.2f, metadata.replayGainAlbumAdjustment()) + + // Test R128 track gain + metadata = createTestMetadata( + xiphTags = mapOf("R128_TRACK_GAIN" to listOf("-2560")) + ) + // R128 is converted to match ReplayGain scale (-2560/256 + 5 = -5.0) + assertEquals(-5.0f, metadata.replayGainTrackAdjustment()) + + // Test zero value + metadata = createTestMetadata( + xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("0.0 dB")) + ) + assertNull(metadata.replayGainTrackAdjustment()) + } + + @Test + fun metadata_genreNames() { + var metadata = createTestMetadata( + id3v2Tags = mapOf("TCON" to listOf("Rock", "Electronic")) + ) + assertEquals(listOf("Rock", "Electronic"), metadata.genreNames()) + + metadata = createTestMetadata( + mp4Tags = mapOf("©gen" to listOf("Hip Hop", "Jazz")) + ) + assertEquals(listOf("Hip Hop", "Jazz"), metadata.genreNames()) + + metadata = createTestMetadata( + xiphTags = mapOf("GENRE" to listOf("Classical", "Ambient")) + ) + assertEquals(listOf("Classical", "Ambient"), metadata.genreNames()) + } + + private fun createTestMetadata( + id3v2Tags: Map> = emptyMap(), + xiphTags: Map> = emptyMap(), + mp4Tags: Map> = emptyMap(), + cover: ByteArray? = null, + durationMs: Long = 1000, + bitrateKbps: Int = 320, + sampleRateHz: Int = 44100, + mimeType: String = "audio/mpeg" + ): Metadata { + val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) + return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) + } +} \ No newline at end of file diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt new file mode 100644 index 000000000..79135683f --- /dev/null +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2024 Auxio Project + * TagParserTest.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.tag.parse + +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.oxycblt.musikr.metadata.Metadata +import org.oxycblt.musikr.metadata.Properties +import org.oxycblt.musikr.tag.Date + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [30]) +class TagParserTest { + private val tagParser = TagParser.new() + + @Test + fun tagParser_parse_basic() { + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TIT2" to listOf("Test Song"), + "TALB" to listOf("Test Album"), + "TPE1" to listOf("Test Artist"), + "TPE2" to listOf("Test Album Artist"), + "TYER" to listOf("2020"), + "TRCK" to listOf("1/10"), + "TPOS" to listOf("1/2"), + "TCON" to listOf("Rock", "Electronic") + ) + ) + + val tags = tagParser.parse(metadata) + + assertEquals("Test Song", tags.name) + assertEquals("Test Album", tags.albumName) + assertEquals(listOf("Test Artist"), tags.artistNames) + assertEquals(listOf("Test Album Artist"), tags.albumArtistNames) + assertEquals(2020, tags.date?.year) + assertEquals(1, tags.track) + assertEquals(1, tags.disc) + assertEquals(listOf("Rock", "Electronic"), tags.genreNames) + } + + @Test + fun tagParser_parse_multipleFormats() { + // Test priority handling between different tag formats + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TIT2" to listOf("ID3 Song"), + "TALB" to listOf("ID3 Album") + ), + xiphTags = mapOf( + "TITLE" to listOf("Xiph Song"), + "ALBUM" to listOf("Xiph Album") + ), + mp4Tags = mapOf( + "©nam" to listOf("MP4 Song"), + "©alb" to listOf("MP4 Album") + ) + ) + + val tags = tagParser.parse(metadata) + + // Check priority: xiph > mp4 > id3v2 + assertEquals("Xiph Song", tags.name) + assertEquals("Xiph Album", tags.albumName) + } + + @Test + fun tagParser_parse_compilation() { + // Test compilation album behavior + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TCMP" to listOf("1") + ) + ) + + val tags = tagParser.parse(metadata) + + assertEquals(listOf("Various Artists"), tags.albumArtistNames) + assertEquals(listOf("compilation"), tags.releaseTypes) + } + + @Test + fun tagParser_parse_compilationWithReleaseType() { + // Test compilation album with explicit release type + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TCMP" to listOf("1"), + "TXXX:RELEASETYPE" to listOf("soundtrack") + ) + ) + + val tags = tagParser.parse(metadata) + + assertEquals(listOf("Various Artists"), tags.albumArtistNames) + assertEquals(listOf("soundtrack"), tags.releaseTypes) + } + + @Test + fun tagParser_parse_empty() { + // Test handling of empty metadata + val metadata = createTestMetadata() + val tags = tagParser.parse(metadata) + + assertNull(tags.name) + assertNull(tags.albumName) + assertEquals(emptyList(), tags.artistNames) + } + + @Test + fun tagParser_musicBrainzIds() { + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TXXX:MUSICBRAINZ RELEASE TRACK ID" to listOf("track-id-123"), + "TXXX:MUSICBRAINZ ALBUM ID" to listOf("album-id-456"), + "TXXX:MUSICBRAINZ ARTIST ID" to listOf("artist-id-789"), + "TXXX:MUSICBRAINZ ALBUM ARTIST ID" to listOf("album-artist-id-012") + ) + ) + + val tags = tagParser.parse(metadata) + + assertEquals("track-id-123", tags.musicBrainzId) + assertEquals("album-id-456", tags.albumMusicBrainzId) + assertEquals(listOf("artist-id-789"), tags.artistMusicBrainzIds) + assertEquals(listOf("album-artist-id-012"), tags.albumArtistMusicBrainzIds) + } + + @Test + fun tagParser_replayGain() { + val metadata = createTestMetadata( + xiphTags = mapOf( + "REPLAYGAIN_TRACK_GAIN" to listOf("-3.5 dB"), + "REPLAYGAIN_ALBUM_GAIN" to listOf("-2.1 dB") + ) + ) + + val tags = tagParser.parse(metadata) + + assertEquals(-3.5f, tags.replayGainTrackAdjustment) + assertEquals(-2.1f, tags.replayGainAlbumAdjustment) + } + + private fun createTestMetadata( + id3v2Tags: Map> = emptyMap(), + xiphTags: Map> = emptyMap(), + mp4Tags: Map> = emptyMap(), + cover: ByteArray? = null, + durationMs: Long = 1000, + bitrateKbps: Int = 320, + sampleRateHz: Int = 44100, + mimeType: String = "audio/mpeg" + ): Metadata { + val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) + return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) + } +} \ No newline at end of file diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt new file mode 100644 index 000000000..2442d3422 --- /dev/null +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2024 Auxio Project + * TagParsingEdgeCasesTest.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.tag.parse + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.oxycblt.musikr.metadata.Metadata +import org.oxycblt.musikr.metadata.Properties +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [30]) +class TagParsingEdgeCasesTest { + private val tagParser = TagParser.new() + + @Test + fun tagParser_emptyTags() { + // Test behavior with completely empty tag maps + val metadata = createTestMetadata() + val parsedTags = tagParser.parse(metadata) + + // Check that all fields have their default values + assertNull(parsedTags.name) + assertNull(parsedTags.sortName) + assertNull(parsedTags.track) + assertNull(parsedTags.disc) + assertNull(parsedTags.subtitle) + assertNull(parsedTags.date) + assertNull(parsedTags.albumName) + assertNull(parsedTags.albumSortName) + assertTrue(parsedTags.releaseTypes.isEmpty()) + assertTrue(parsedTags.artistNames.isEmpty()) + assertTrue(parsedTags.artistSortNames.isEmpty()) + assertTrue(parsedTags.albumArtistNames.isEmpty()) + assertTrue(parsedTags.albumArtistSortNames.isEmpty()) + assertTrue(parsedTags.genreNames.isEmpty()) + } + + @Test + fun tagParser_malformedTags() { + // Test behavior with malformed tags + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TRCK" to listOf("not-a-number"), + "TPOS" to listOf("also-not-a-number"), + "TYER" to listOf("invalid-year"), + "REPLAYGAIN_TRACK_GAIN" to listOf("not-a-float dB") + ) + ) + val parsedTags = tagParser.parse(metadata) + + // Verify all numeric fields are null when given invalid values + assertNull(parsedTags.track) + assertNull(parsedTags.disc) + assertNull(parsedTags.date) + assertNull(parsedTags.replayGainTrackAdjustment) + } + + @Test + fun tagParser_priorityHandling() { + // Test that field priority is handled correctly when multiple formats have the same field + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TIT2" to listOf("ID3 Title"), + "TALB" to listOf("ID3 Album") + ), + mp4Tags = mapOf( + "©nam" to listOf("MP4 Title"), + "©alb" to listOf("MP4 Album") + ), + xiphTags = mapOf( + "TITLE" to listOf("Xiph Title"), + "ALBUM" to listOf("Xiph Album") + ) + ) + + // Individual field extraction + assertEquals("Xiph Title", metadata.name()) + assertEquals("Xiph Album", metadata.albumName()) + + // Full tag parsing + val parsedTags = tagParser.parse(metadata) + assertEquals("Xiph Title", parsedTags.name) + assertEquals("Xiph Album", parsedTags.albumName) + } + + @Test + fun tagParser_fieldBackoffHandling() { + // Test that when a format doesn't have a field, it falls back to the next format + val metadata = createTestMetadata( + id3v2Tags = mapOf( + "TIT2" to listOf("ID3 Title"), + "TALB" to listOf("ID3 Album") + ), + mp4Tags = mapOf( + "©nam" to listOf("MP4 Title") + // No album in MP4 + ), + xiphTags = mapOf( + // No title in Xiph + "ALBUM" to listOf("Xiph Album") + ) + ) + + // Individual field extraction + assertEquals("MP4 Title", metadata.name()) // Xiph missing, falls back to MP4 + assertEquals("Xiph Album", metadata.albumName()) // Xiph has it, no fallback needed + + // Full tag parsing + val parsedTags = tagParser.parse(metadata) + assertEquals("MP4 Title", parsedTags.name) + assertEquals("Xiph Album", parsedTags.albumName) + } + + @Test + fun tagParser_compilationBehavior() { + // Test the special behavior for compilation albums + + // Case 1: Compilation flag only + var metadata = createTestMetadata( + id3v2Tags = mapOf( + "TCMP" to listOf("1") + ) + ) + var tags = tagParser.parse(metadata) + assertEquals(listOf("Various Artists"), tags.albumArtistNames) + assertEquals(listOf("compilation"), tags.releaseTypes) + + // Case 2: Compilation flag with explicit album artist + metadata = createTestMetadata( + id3v2Tags = mapOf( + "TCMP" to listOf("1"), + "TPE2" to listOf("Custom Album Artist") + ) + ) + tags = tagParser.parse(metadata) + assertEquals(listOf("Custom Album Artist"), tags.albumArtistNames) + assertEquals(listOf("compilation"), tags.releaseTypes) + + // Case 3: Compilation flag with explicit release type + metadata = createTestMetadata( + id3v2Tags = mapOf( + "TCMP" to listOf("1"), + "TXXX:RELEASETYPE" to listOf("soundtrack") + ) + ) + tags = tagParser.parse(metadata) + assertEquals(listOf("Various Artists"), tags.albumArtistNames) + assertEquals(listOf("soundtrack"), tags.releaseTypes) + } + + @Test + fun tagFields_replayGainEdgeCases() { + // Test various ReplayGain edge cases + + // Non-numeric characters filtered out + var metadata = createTestMetadata( + xiphTags = mapOf( + "REPLAYGAIN_TRACK_GAIN" to listOf("+2.5 dB some text") + ) + ) + assertEquals(2.5f, metadata.replayGainTrackAdjustment()) + + // Zero values filtered + metadata = createTestMetadata( + xiphTags = mapOf( + "REPLAYGAIN_ALBUM_GAIN" to listOf("0.0 dB") + ) + ) + assertNull(metadata.replayGainAlbumAdjustment()) + + // R128 value with special parsing + metadata = createTestMetadata( + xiphTags = mapOf( + "R128_TRACK_GAIN" to listOf("-1280") + ) + ) + assertEquals(0.0f, metadata.replayGainTrackAdjustment()) // -1280/256 + 5 = 0.0 + + // Completely invalid value + metadata = createTestMetadata( + xiphTags = mapOf( + "REPLAYGAIN_TRACK_GAIN" to listOf("not a number") + ) + ) + assertNull(metadata.replayGainTrackAdjustment()) + } + + @Test + fun tagFields_id3v23DateEdgeCases() { + // Test ID3v2.3 date edge cases + + // Just year + var metadata = createTestMetadata( + id3v2Tags = mapOf( + "TYER" to listOf("2018") + ) + ) + assertEquals("2018", metadata.date().toString()) + + // Year and date + metadata = createTestMetadata( + id3v2Tags = mapOf( + "TYER" to listOf("2018"), + "TDAT" to listOf("0315") // March 15 + ) + ) + assertEquals("2018-03-15", metadata.date().toString()) + + // Year, date and time + metadata = createTestMetadata( + id3v2Tags = mapOf( + "TYER" to listOf("2018"), + "TDAT" to listOf("0315"), // March 15 + "TIME" to listOf("1422") // 14:22 + ) + ) + assertEquals("2018-03-15T14:22Z", metadata.date().toString()) + + // Original year + metadata = createTestMetadata( + id3v2Tags = mapOf( + "TORY" to listOf("1995") + ) + ) + assertEquals("1995", metadata.date().toString()) + + // Invalid date components + metadata = createTestMetadata( + id3v2Tags = mapOf( + "TYER" to listOf("2018"), + "TDAT" to listOf("invalid"), + "TIME" to listOf("invalid") + ) + ) + assertEquals("2018", metadata.date().toString()) + + // Non-numeric date components + metadata = createTestMetadata( + id3v2Tags = mapOf( + "TYER" to listOf("year") + ) + ) + assertNull(metadata.date()) + } + + private fun createTestMetadata( + id3v2Tags: Map> = emptyMap(), + xiphTags: Map> = emptyMap(), + mp4Tags: Map> = emptyMap(), + cover: ByteArray? = null, + durationMs: Long = 1000, + bitrateKbps: Int = 320, + sampleRateHz: Int = 44100, + mimeType: String = "audio/mpeg" + ): Metadata { + val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) + return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) + } +} \ No newline at end of file From 01a159754d7e4787f17020197e24d897eb4d28e7 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 22 Mar 2025 16:36:33 -0600 Subject: [PATCH 02/38] musikr: move name tests to naming --- .../musikr/tag/{NameTest.kt => interpret/NamingTest.kt} | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) rename musikr/src/test/java/org/oxycblt/musikr/tag/{NameTest.kt => interpret/NamingTest.kt} (98%) diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/NameTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/NamingTest.kt similarity index 98% rename from musikr/src/test/java/org/oxycblt/musikr/tag/NameTest.kt rename to musikr/src/test/java/org/oxycblt/musikr/tag/interpret/NamingTest.kt index a44f79708..ebe3f8109 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/NameTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/NamingTest.kt @@ -16,14 +16,16 @@ * along with this program. If not, see . */ -package org.oxycblt.musikr.tag +package org.oxycblt.musikr.tag.interpret import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Test -import org.oxycblt.musikr.tag.interpret.Naming +import org.oxycblt.musikr.tag.Name +import org.oxycblt.musikr.tag.Placeholder +import org.oxycblt.musikr.tag.Token -class NameTest { +class NamingTest { @Test fun name_simple_withoutPunct() { val name = Naming.simple().name("Loveless", null) From e2918d3a95b9288d21b5db9f81ba6eae51bbab06 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 22 Mar 2025 16:48:12 -0600 Subject: [PATCH 03/38] musikr: fix failing tests --- .../main/java/org/oxycblt/musikr/tag/interpret/Naming.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/Naming.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/Naming.kt index d1d8d0b63..caa620efd 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/Naming.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/Naming.kt @@ -41,12 +41,12 @@ abstract class Naming { } } -private data object IntelligentNaming : Naming() { - override fun name(raw: String, sort: String?) = IntelligentKnownName(raw, sort) +data object IntelligentNaming : Naming() { + override fun name(raw: String, sort: String?): Name.Known = IntelligentKnownName(raw, sort) } -private data object SimpleNaming : Naming() { - override fun name(raw: String, sort: String?) = SimpleKnownName(raw, sort) +data object SimpleNaming : Naming() { + override fun name(raw: String, sort: String?): Name.Known = SimpleKnownName(raw, sort) } private val collator: Collator = Collator.getInstance().apply { strength = Collator.PRIMARY } From d0d81390bc0c592d0fdfb3919e90be7a1a653678 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 22 Mar 2025 16:49:22 -0600 Subject: [PATCH 04/38] musikr: break off devicefsentries from devicefs --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 22 +-------------- .../musikr/fs/device/DeviceFSEntries.kt | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+), 21 deletions(-) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 44a5ff652..c9879aa98 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -43,26 +43,6 @@ internal interface DeviceFS { } } -sealed interface DeviceNode { - val uri: Uri - val path: Path -} - -data class DeviceDirectory( - override val uri: Uri, - override val path: Path, - val parent: Deferred?, - var children: List -) : DeviceNode - -data class DeviceFile( - override val uri: Uri, - override val path: Path, - val modifiedMs: Long, - val mimeType: String, - val size: Long, - val parent: Deferred -) : DeviceNode @OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( @@ -88,7 +68,7 @@ private class DeviceFSImpl( val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) val directoryDeferred = CompletableDeferred() val recursive = mutableListOf>() - val children = mutableListOf() + val children = mutableListOf() contentResolver.useQuery(uri, PROJECTION) { cursor -> val childUriIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt new file mode 100644 index 000000000..3e3e27d6b --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -0,0 +1,27 @@ +package org.oxycblt.musikr.fs.device + +import android.net.Uri +import kotlinx.coroutines.Deferred +import org.oxycblt.musikr.fs.Path + + +sealed interface DeviceFSEntry { + val uri: Uri + val path: Path +} + +data class DeviceDirectory( + override val uri: Uri, + override val path: Path, + val parent: Deferred?, + var children: List +) : DeviceFSEntry + +data class DeviceFile( + override val uri: Uri, + override val path: Path, + val modifiedMs: Long, + val mimeType: String, + val size: Long, + val parent: Deferred +) : DeviceFSEntry \ No newline at end of file From 61d34cb57687d6a2a4b1b5d249098ed4bc45c1e3 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 22 Mar 2025 17:08:59 -0600 Subject: [PATCH 05/38] musikr: test devicefs --- musikr/build.gradle | 1 + .../oxycblt/musikr/fs/device/DeviceFSTest.kt | 359 ++++++++++++++++++ 2 files changed, 360 insertions(+) create mode 100644 musikr/src/test/java/org/oxycblt/musikr/fs/device/DeviceFSTest.kt diff --git a/musikr/build.gradle b/musikr/build.gradle index 80007d3bf..9e819dcff 100644 --- a/musikr/build.gradle +++ b/musikr/build.gradle @@ -78,6 +78,7 @@ dependencies { testImplementation "io.mockk:mockk:1.13.7" testImplementation "org.robolectric:robolectric:4.11" testImplementation 'androidx.test:core-ktx:1.6.1' + testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlin_coroutines_version" androidTestImplementation 'androidx.test.ext:junit:1.2.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' } diff --git a/musikr/src/test/java/org/oxycblt/musikr/fs/device/DeviceFSTest.kt b/musikr/src/test/java/org/oxycblt/musikr/fs/device/DeviceFSTest.kt new file mode 100644 index 000000000..72572eea3 --- /dev/null +++ b/musikr/src/test/java/org/oxycblt/musikr/fs/device/DeviceFSTest.kt @@ -0,0 +1,359 @@ +/* + * Copyright (c) 2024 Auxio Project + * DeviceFSTest.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.fs.device + +import android.content.ContentResolver +import android.content.Context +import android.database.Cursor +import android.database.MatrixCursor +import android.net.Uri +import android.provider.DocumentsContract +import io.mockk.Runs +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.mockkStatic +import io.mockk.slot +import io.mockk.spyk +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.oxycblt.musikr.fs.Components +import org.oxycblt.musikr.fs.MusicLocation +import org.oxycblt.musikr.fs.Path +import org.oxycblt.musikr.fs.Volume +import org.oxycblt.musikr.fs.path.DocumentPathFactory +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [30]) +class DeviceFSTest { + + private lateinit var contentResolver: ContentResolver + private lateinit var context: Context + private lateinit var mockRootUri: Uri + private lateinit var mockChildUri: Uri + private lateinit var documentPathFactory: DocumentPathFactory + private lateinit var deviceFS: DeviceFS + private lateinit var testPath: Path + + @Before + fun setup() { + // Set up mocks + contentResolver = mockk(relaxed = true) + context = mockk(relaxed = true) + mockRootUri = mockk() + mockChildUri = mockk() + documentPathFactory = mockk() + + // Create test path + val testVolume = TestVolume("primary") + val components = Components.parseUnix("") + testPath = Path(testVolume, components) + + // Mock context to return our contentResolver + every { context.contentResolverSafe } returns contentResolver + + // Mock DocumentsContract static methods + mockkStatic(DocumentsContract::class) + every { DocumentsContract.buildChildDocumentsUriUsingTree(any(), any()) } returns mockRootUri + every { DocumentsContract.buildDocumentUriUsingTree(any(), any()) } returns mockChildUri + every { DocumentsContract.getTreeDocumentId(any()) } returns "tree-doc-id" + every { DocumentsContract.isTreeUri(any()) } returns true + + // Mock DocumentPathFactory + mockkStatic(DocumentPathFactory::class) + every { DocumentPathFactory.from(any()) } returns documentPathFactory + every { documentPathFactory.unpackDocumentTreeUri(any()) } returns testPath + + // Mock MusicLocation resolving + every { + contentResolver.persistedUriPermissions + } returns emptyList() + + every { + contentResolver.takePersistableUriPermission(any(), any()) + } just Runs + + // Create DeviceFS instance via the companion function + deviceFS = DeviceFS.from(context, withHidden = false) + } + + @Test + fun explore_emptyDirectory_returnsNoFiles() = runTest { + // Arrange + val location = createTestMusicLocation("primary", emptyList()) + val emptyCursor = createMockCursor(emptyList()) + + // Set up the query to return our empty cursor + mockContentResolverQuery(emptyCursor) + + // Act + val result = deviceFS.explore(flow { emit(location) }).toList() + + // Assert + assertTrue(result.isEmpty()) + } + + @Test + fun explore_filtersHiddenFiles() = runTest { + // Arrange + val location = createTestMusicLocation("primary", emptyList()) + + val entries = listOf( + MockFileEntry("doc1", "visible.mp3", "audio/mpeg", 1024, 1000), + MockFileEntry("doc2", ".hidden.mp3", "audio/mpeg", 2048, 2000) + ) + + val cursor = createMockCursor(entries) + mockContentResolverQuery(cursor) + + // Act + val result = deviceFS.explore(flow { emit(location) }).toList() + + // Assert + assertEquals(1, result.size) + assertEquals("visible.mp3", result[0].path.name) + } + + @Test + fun explore_includesHiddenFiles_whenConfigured() = runTest { + // Arrange + val deviceFSWithHidden = DeviceFS.from(context, withHidden = true) + val location = createTestMusicLocation("primary", emptyList()) + + val entries = listOf( + MockFileEntry("doc1", "visible.mp3", "audio/mpeg", 1024, 1000), + MockFileEntry("doc2", ".hidden.mp3", "audio/mpeg", 2048, 2000) + ) + + val cursor = createMockCursor(entries) + mockContentResolverQuery(cursor) + + // Act + val result = deviceFSWithHidden.explore(flow { emit(location) }).toList() + + // Assert + assertEquals(2, result.size) + val fileNames = result.map { it.path.name } + assertTrue(fileNames.contains("visible.mp3")) + assertTrue(fileNames.contains(".hidden.mp3")) + } + + @Test + fun explore_traversesDirectories() = runTest { + // Arrange + val location = createTestMusicLocation("primary", emptyList()) + + // Root directory contains 1 file and 1 subdirectory + val rootEntries = listOf( + MockFileEntry("doc1", "root.mp3", "audio/mpeg", 1024, 1000), + MockDirEntry("dir1", "subdir") + ) + + // Subdirectory contains 2 files + val subdirEntries = listOf( + MockFileEntry("doc2", "sub1.mp3", "audio/mpeg", 2048, 2000), + MockFileEntry("doc3", "sub2.mp3", "audio/mpeg", 3072, 3000) + ) + + // Set up cursor behavior to return different cursors for different queries + val rootCursor = createMockCursor(rootEntries) + val subdirCursor = createMockCursor(subdirEntries) + + // First call will get root entries, second call will get subdir entries + mockContentResolverQuery(rootCursor, subdirCursor) + + // Act + val result = deviceFS.explore(flow { emit(location) }).toList() + + // Assert + assertEquals(3, result.size) + + val fileNames = result.map { it.path.name } + assertTrue(fileNames.contains("root.mp3")) + assertTrue(fileNames.contains("sub1.mp3")) + assertTrue(fileNames.contains("sub2.mp3")) + } + + @Test + fun explore_multipleLocations_returnsAllFiles() = runTest { + // Arrange + val location1 = createTestMusicLocation("primary", listOf("Music")) + val location2 = createTestMusicLocation("secondary", listOf("Downloads")) + + val location1Entries = listOf( + MockFileEntry("doc1", "music1.mp3", "audio/mpeg", 1024, 1000), + MockFileEntry("doc2", "music2.mp3", "audio/mpeg", 2048, 2000) + ) + + val location2Entries = listOf( + MockFileEntry("doc3", "download1.mp3", "audio/mpeg", 3072, 3000) + ) + + val location1Cursor = createMockCursor(location1Entries) + val location2Cursor = createMockCursor(location2Entries) + + // First call will process location1, second call will process location2 + mockContentResolverQuery(location1Cursor, location2Cursor) + + // Act + val result = deviceFS.explore(flow { + emit(location1) + emit(location2) + }).toList() + + // Assert + assertEquals(3, result.size) + + val fileNames = result.map { it.path.name } + assertTrue(fileNames.contains("music1.mp3")) + assertTrue(fileNames.contains("music2.mp3")) + assertTrue(fileNames.contains("download1.mp3")) + } + + @Test + fun explore_fileMetadata_isCorrect() = runTest { + // Arrange + val location = createTestMusicLocation("primary", emptyList()) + + val entries = listOf( + MockFileEntry("doc1", "test.mp3", "audio/mpeg", 1024, 1000) + ) + + val cursor = createMockCursor(entries) + mockContentResolverQuery(cursor) + + // Act + val result = deviceFS.explore(flow { emit(location) }).toList() + + // Assert + assertEquals(1, result.size) + with(result[0]) { + assertEquals("test.mp3", path.name) + assertEquals("audio/mpeg", mimeType) + assertEquals(1024, size) + assertEquals(1000, modifiedMs) + } + } + + /** + * Mock the content resolver's query method to handle cursor interactions + */ + private fun mockContentResolverQuery(vararg cursors: Cursor) { + val cursorList = cursors.toList() + var callCount = 0 + + // Mock the useQuery extension function + every { + contentResolver.useQuery(any(), any(), any(), any(), any()) + } answers { call -> + val cursor = cursorList[callCount % cursorList.size] + callCount++ + val block = call.invocation.args[4] as (Cursor) -> Any + block(cursor) + } + } + + /** + * Create a mock cursor with the given entries + */ + private fun createMockCursor(entries: List): Cursor { + val cursor = MatrixCursor( + arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + DocumentsContract.Document.COLUMN_SIZE, + DocumentsContract.Document.COLUMN_LAST_MODIFIED + ) + ) + + entries.forEach { entry -> + when (entry) { + is MockFileEntry -> { + cursor.addRow(arrayOf( + entry.id, + entry.name, + entry.mimeType, + entry.size, + entry.lastModified + )) + } + is MockDirEntry -> { + cursor.addRow(arrayOf( + entry.id, + entry.name, + DocumentsContract.Document.MIME_TYPE_DIR, + 0, + 0 + )) + } + } + } + + return cursor + } + + /** + * Create a test MusicLocation using the factory method + */ + private fun createTestMusicLocation(volumeId: String, pathComponents: List): MusicLocation { + // For each different location, we need a slightly different path to be returned + val volume = TestVolume(volumeId) + val components = Components.parseUnix(pathComponents.joinToString("/")) + val path = Path(volume, components) + + // Override the path that will be returned for this specific call + every { documentPathFactory.unpackDocumentTreeUri(mockRootUri) } returns path + + // Use MusicLocation.new which is a public factory method + return MusicLocation.new(context, mockRootUri)!! + } + + // Mock classes for test data + sealed class MockFSEntry + + data class MockFileEntry( + val id: String, + val name: String, + val mimeType: String, + val size: Long, + val lastModified: Long + ) : MockFSEntry() + + data class MockDirEntry( + val id: String, + val name: String + ) : MockFSEntry() + + class TestVolume(override val id: String?) : Volume.External { + override val mediaStoreName: String? = id + override val components: Components? = null + + override fun resolveName(context: Context): String = id ?: "unknown" + } +} \ No newline at end of file From 5c99b1e6e13556f0e4aeb791e8d3a69cd44b5e1b Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 22 Mar 2025 17:14:34 -0600 Subject: [PATCH 06/38] musikr: test fscoverstorage --- .../musikr/covers/stored/CoverStorageTest.kt | 353 ++++++++++++++++++ 1 file changed, 353 insertions(+) create mode 100644 musikr/src/test/java/org/oxycblt/musikr/covers/stored/CoverStorageTest.kt diff --git a/musikr/src/test/java/org/oxycblt/musikr/covers/stored/CoverStorageTest.kt b/musikr/src/test/java/org/oxycblt/musikr/covers/stored/CoverStorageTest.kt new file mode 100644 index 000000000..ce8e85232 --- /dev/null +++ b/musikr/src/test/java/org/oxycblt/musikr/covers/stored/CoverStorageTest.kt @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2024 Auxio Project + * CoverStorageTest.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.covers.stored + +import android.os.ParcelFileDescriptor +import io.mockk.coEvery +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkStatic +import io.mockk.slot +import io.mockk.spyk +import io.mockk.verify +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.io.OutputStream +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [30]) +class CoverStorageTest { + + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var storageDir: File + private lateinit var coverStorage: CoverStorage + + @Before + fun setup() = runTest { + storageDir = tempFolder.newFolder("covers") + coverStorage = CoverStorage.at(storageDir) + } + + @Test(expected = IllegalStateException::class) + fun at_nonExistentDirectory_throwsException() = runTest { + // Arrange + val nonExistentDir = File(tempFolder.root, "nonexistent") + + // Act - should throw + CoverStorage.at(nonExistentDir) + } + + @Test(expected = IllegalStateException::class) + fun at_fileNotDirectory_throwsException() = runTest { + // Arrange + val file = tempFolder.newFile("not-a-directory") + + // Act - should throw + CoverStorage.at(file) + } + + @Test + fun find_existingCover_returnsCorrectCover() = runTest { + // Arrange + val coverName = "test-cover.jpg" + val coverFile = File(storageDir, coverName) + val testData = byteArrayOf(1, 2, 3, 4, 5) + + coverFile.writeBytes(testData) + + // Act + val cover = coverStorage.find(coverName) + + // Assert + assertNotNull(cover) + assertEquals(coverName, cover?.id) + + // Verify the cover can be opened + val inputStream = cover?.open() + assertNotNull(inputStream) + + val bytes = inputStream?.readBytes() + assertEquals(testData.size, bytes?.size) + assertTrue(testData.contentEquals(bytes!!)) + } + + @Test + fun find_nonExistentCover_returnsNull() = runTest { + // Act + val cover = coverStorage.find("nonexistent.jpg") + + // Assert + assertNull(cover) + } + + @Test + fun find_ioExceptionDuringAccess_returnsNull() = runTest { + // Arrange + val coverName = "error-cover.jpg" + val mockFile = mockk() + val storageDir = spyk(tempFolder.newFolder("error-covers")) + + // Setup a mock File that throws IOException when accessed + every { storageDir.listFiles() } returns arrayOf(mockFile) + every { mockFile.name } returns coverName + every { mockFile.exists() } returns true + every { mockFile.inputStream() } throws IOException("Test exception") + + val errorCoverStorage = CoverStorage.at(storageDir) + + // Act + val cover = errorCoverStorage.find(coverName) + + // Assert + assertNull(cover) + } + + @Test + fun write_newCover_createsFileAndReturnsCover() = runTest { + // Arrange + val coverName = "new-cover.jpg" + val testData = byteArrayOf(10, 20, 30, 40, 50) + + // Act + val cover = coverStorage.write(coverName) { outputStream -> + outputStream.write(testData) + } + + // Assert + assertNotNull(cover) + assertEquals(coverName, cover.id) + + // Verify the file was created correctly + val file = File(storageDir, coverName) + assertTrue(file.exists()) + + val fileData = file.readBytes() + assertEquals(testData.size, fileData.size) + assertTrue(testData.contentEquals(fileData)) + } + + @Test + fun write_existingCover_returnsExistingCover() = runTest { + // Arrange + val coverName = "existing-cover.jpg" + val existingData = byteArrayOf(1, 2, 3, 4, 5) + + // Create existing file + val existingFile = File(storageDir, coverName) + existingFile.writeBytes(existingData) + + // Act - trying to write new data should not overwrite + val cover = coverStorage.write(coverName) { outputStream -> + outputStream.write(byteArrayOf(99, 98, 97)) + } + + // Assert + assertNotNull(cover) + assertEquals(coverName, cover.id) + + // Verify the file still has the original data + val fileData = existingFile.readBytes() + assertEquals(existingData.size, fileData.size) + assertTrue(existingData.contentEquals(fileData)) + } + + @Test(expected = IOException::class) + fun write_ioExceptionDuringWrite_propagatesException() = runTest { + // Arrange + val coverName = "error-write.jpg" + + // Act - should throw + coverStorage.write(coverName) { outputStream -> + throw IOException("Test write exception") + } + } + + @Test + fun write_ioExceptionDuringWrite_cleanupsTempFile() = runTest { + // Arrange + val coverName = "error-cleanup.jpg" + val tmpFileName = "$coverName.tmp" + + try { + // Act - will throw + coverStorage.write(coverName) { outputStream -> + // Write some data first + outputStream.write(byteArrayOf(1, 2, 3)) + throw IOException("Test exception") + } + } catch (e: IOException) { + // Expected + } + + // Assert - temp file should be deleted + val tmpFile = File(storageDir, tmpFileName) + assertTrue(!tmpFile.exists()) + } + + @Test + fun ls_noExcludeFilter_returnsAllFiles() = runTest { + // Arrange + val files = listOf("cover1.jpg", "cover2.png", "cover3.jpeg") + + files.forEach { + File(storageDir, it).createNewFile() + } + + // Act + val result = coverStorage.ls(emptySet()) + + // Assert + assertEquals(files.size, result.size) + files.forEach { + assertTrue(result.contains(it)) + } + } + + @Test + fun ls_withExcludeFilter_returnsFilteredFiles() = runTest { + // Arrange + val files = listOf("cover1.jpg", "cover2.png", "cover3.jpeg") + val excluded = setOf("cover1.jpg", "cover3.jpeg") + + files.forEach { + File(storageDir, it).createNewFile() + } + + // Act + val result = coverStorage.ls(excluded) + + // Assert + assertEquals(1, result.size) + assertTrue(result.contains("cover2.png")) + assertTrue(!result.contains("cover1.jpg")) + assertTrue(!result.contains("cover3.jpeg")) + } + + @Test + fun ls_emptyDirectory_returnsEmptyList() = runTest { + // Act + val result = coverStorage.ls(emptySet()) + + // Assert + assertTrue(result.isEmpty()) + } + + @Test + fun rm_existingFile_deletesFile() = runTest { + // Arrange + val coverName = "to-delete.jpg" + val file = File(storageDir, coverName) + file.createNewFile() + + assertTrue(file.exists()) + + // Act + coverStorage.rm(coverName) + + // Assert + assertTrue(!file.exists()) + } + + @Test + fun rm_nonExistentFile_doesNothing() = runTest { + // Act - should not throw + coverStorage.rm("nonexistent.jpg") + } + + @Test + fun fdCover_fd_returnsValidFileDescriptor() = runTest { + // Arrange + val coverName = "fd-test.jpg" + val testData = byteArrayOf(1, 2, 3, 4, 5) + + val coverFile = File(storageDir, coverName) + coverFile.writeBytes(testData) + + // Act + val cover = coverStorage.find(coverName) + val fd = cover?.fd() + + // Assert + assertNotNull(fd) + + // Clean up + fd?.close() + } + + @Test + fun fdCover_fd_returnsNullOnIOException() = runTest { + // Arrange + val coverName = "fd-error.jpg" + + // Create a mock file that throws on ParcelFileDescriptor.open + val mockFile = mockk() + every { mockFile.exists() } returns true + every { mockFile.name } returns coverName + + mockkStatic(ParcelFileDescriptor::class) + coEvery { + ParcelFileDescriptor.open(any(), any()) + } throws IOException("Test fd exception") + + // Create mock cover + val cover = FSStoredCover(mockFile) + + // Act + val fd = cover.fd() + + // Assert + assertNull(fd) + } +} + +// Exposing the private FSStoredCover class for testing +private class FSStoredCover(private val file: File) : org.oxycblt.musikr.covers.FDCover { + override val id: String = file.name + + override suspend fun fd() = + try { + ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) + } catch (e: IOException) { + null + } + + override suspend fun open() = file.inputStream() + + override fun equals(other: Any?) = other is FSStoredCover && file == other.file + + override fun hashCode() = file.hashCode() +} \ No newline at end of file From 673c2fed7be9c0a4d0524fd0b7135f1208560e36 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 17:33:46 -0600 Subject: [PATCH 07/38] musikr: remove broken tests --- .../musikr/covers/stored/CoverStorageTest.kt | 353 ----------------- .../oxycblt/musikr/fs/device/DeviceFSTest.kt | 359 ------------------ 2 files changed, 712 deletions(-) delete mode 100644 musikr/src/test/java/org/oxycblt/musikr/covers/stored/CoverStorageTest.kt delete mode 100644 musikr/src/test/java/org/oxycblt/musikr/fs/device/DeviceFSTest.kt diff --git a/musikr/src/test/java/org/oxycblt/musikr/covers/stored/CoverStorageTest.kt b/musikr/src/test/java/org/oxycblt/musikr/covers/stored/CoverStorageTest.kt deleted file mode 100644 index ce8e85232..000000000 --- a/musikr/src/test/java/org/oxycblt/musikr/covers/stored/CoverStorageTest.kt +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright (c) 2024 Auxio Project - * CoverStorageTest.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.covers.stored - -import android.os.ParcelFileDescriptor -import io.mockk.coEvery -import io.mockk.every -import io.mockk.mockk -import io.mockk.mockkStatic -import io.mockk.slot -import io.mockk.spyk -import io.mockk.verify -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream -import java.io.File -import java.io.FileInputStream -import java.io.FileOutputStream -import java.io.IOException -import java.io.OutputStream -import kotlinx.coroutines.test.runTest -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNotNull -import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.annotation.Config - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [30]) -class CoverStorageTest { - - @get:Rule - val tempFolder = TemporaryFolder() - - private lateinit var storageDir: File - private lateinit var coverStorage: CoverStorage - - @Before - fun setup() = runTest { - storageDir = tempFolder.newFolder("covers") - coverStorage = CoverStorage.at(storageDir) - } - - @Test(expected = IllegalStateException::class) - fun at_nonExistentDirectory_throwsException() = runTest { - // Arrange - val nonExistentDir = File(tempFolder.root, "nonexistent") - - // Act - should throw - CoverStorage.at(nonExistentDir) - } - - @Test(expected = IllegalStateException::class) - fun at_fileNotDirectory_throwsException() = runTest { - // Arrange - val file = tempFolder.newFile("not-a-directory") - - // Act - should throw - CoverStorage.at(file) - } - - @Test - fun find_existingCover_returnsCorrectCover() = runTest { - // Arrange - val coverName = "test-cover.jpg" - val coverFile = File(storageDir, coverName) - val testData = byteArrayOf(1, 2, 3, 4, 5) - - coverFile.writeBytes(testData) - - // Act - val cover = coverStorage.find(coverName) - - // Assert - assertNotNull(cover) - assertEquals(coverName, cover?.id) - - // Verify the cover can be opened - val inputStream = cover?.open() - assertNotNull(inputStream) - - val bytes = inputStream?.readBytes() - assertEquals(testData.size, bytes?.size) - assertTrue(testData.contentEquals(bytes!!)) - } - - @Test - fun find_nonExistentCover_returnsNull() = runTest { - // Act - val cover = coverStorage.find("nonexistent.jpg") - - // Assert - assertNull(cover) - } - - @Test - fun find_ioExceptionDuringAccess_returnsNull() = runTest { - // Arrange - val coverName = "error-cover.jpg" - val mockFile = mockk() - val storageDir = spyk(tempFolder.newFolder("error-covers")) - - // Setup a mock File that throws IOException when accessed - every { storageDir.listFiles() } returns arrayOf(mockFile) - every { mockFile.name } returns coverName - every { mockFile.exists() } returns true - every { mockFile.inputStream() } throws IOException("Test exception") - - val errorCoverStorage = CoverStorage.at(storageDir) - - // Act - val cover = errorCoverStorage.find(coverName) - - // Assert - assertNull(cover) - } - - @Test - fun write_newCover_createsFileAndReturnsCover() = runTest { - // Arrange - val coverName = "new-cover.jpg" - val testData = byteArrayOf(10, 20, 30, 40, 50) - - // Act - val cover = coverStorage.write(coverName) { outputStream -> - outputStream.write(testData) - } - - // Assert - assertNotNull(cover) - assertEquals(coverName, cover.id) - - // Verify the file was created correctly - val file = File(storageDir, coverName) - assertTrue(file.exists()) - - val fileData = file.readBytes() - assertEquals(testData.size, fileData.size) - assertTrue(testData.contentEquals(fileData)) - } - - @Test - fun write_existingCover_returnsExistingCover() = runTest { - // Arrange - val coverName = "existing-cover.jpg" - val existingData = byteArrayOf(1, 2, 3, 4, 5) - - // Create existing file - val existingFile = File(storageDir, coverName) - existingFile.writeBytes(existingData) - - // Act - trying to write new data should not overwrite - val cover = coverStorage.write(coverName) { outputStream -> - outputStream.write(byteArrayOf(99, 98, 97)) - } - - // Assert - assertNotNull(cover) - assertEquals(coverName, cover.id) - - // Verify the file still has the original data - val fileData = existingFile.readBytes() - assertEquals(existingData.size, fileData.size) - assertTrue(existingData.contentEquals(fileData)) - } - - @Test(expected = IOException::class) - fun write_ioExceptionDuringWrite_propagatesException() = runTest { - // Arrange - val coverName = "error-write.jpg" - - // Act - should throw - coverStorage.write(coverName) { outputStream -> - throw IOException("Test write exception") - } - } - - @Test - fun write_ioExceptionDuringWrite_cleanupsTempFile() = runTest { - // Arrange - val coverName = "error-cleanup.jpg" - val tmpFileName = "$coverName.tmp" - - try { - // Act - will throw - coverStorage.write(coverName) { outputStream -> - // Write some data first - outputStream.write(byteArrayOf(1, 2, 3)) - throw IOException("Test exception") - } - } catch (e: IOException) { - // Expected - } - - // Assert - temp file should be deleted - val tmpFile = File(storageDir, tmpFileName) - assertTrue(!tmpFile.exists()) - } - - @Test - fun ls_noExcludeFilter_returnsAllFiles() = runTest { - // Arrange - val files = listOf("cover1.jpg", "cover2.png", "cover3.jpeg") - - files.forEach { - File(storageDir, it).createNewFile() - } - - // Act - val result = coverStorage.ls(emptySet()) - - // Assert - assertEquals(files.size, result.size) - files.forEach { - assertTrue(result.contains(it)) - } - } - - @Test - fun ls_withExcludeFilter_returnsFilteredFiles() = runTest { - // Arrange - val files = listOf("cover1.jpg", "cover2.png", "cover3.jpeg") - val excluded = setOf("cover1.jpg", "cover3.jpeg") - - files.forEach { - File(storageDir, it).createNewFile() - } - - // Act - val result = coverStorage.ls(excluded) - - // Assert - assertEquals(1, result.size) - assertTrue(result.contains("cover2.png")) - assertTrue(!result.contains("cover1.jpg")) - assertTrue(!result.contains("cover3.jpeg")) - } - - @Test - fun ls_emptyDirectory_returnsEmptyList() = runTest { - // Act - val result = coverStorage.ls(emptySet()) - - // Assert - assertTrue(result.isEmpty()) - } - - @Test - fun rm_existingFile_deletesFile() = runTest { - // Arrange - val coverName = "to-delete.jpg" - val file = File(storageDir, coverName) - file.createNewFile() - - assertTrue(file.exists()) - - // Act - coverStorage.rm(coverName) - - // Assert - assertTrue(!file.exists()) - } - - @Test - fun rm_nonExistentFile_doesNothing() = runTest { - // Act - should not throw - coverStorage.rm("nonexistent.jpg") - } - - @Test - fun fdCover_fd_returnsValidFileDescriptor() = runTest { - // Arrange - val coverName = "fd-test.jpg" - val testData = byteArrayOf(1, 2, 3, 4, 5) - - val coverFile = File(storageDir, coverName) - coverFile.writeBytes(testData) - - // Act - val cover = coverStorage.find(coverName) - val fd = cover?.fd() - - // Assert - assertNotNull(fd) - - // Clean up - fd?.close() - } - - @Test - fun fdCover_fd_returnsNullOnIOException() = runTest { - // Arrange - val coverName = "fd-error.jpg" - - // Create a mock file that throws on ParcelFileDescriptor.open - val mockFile = mockk() - every { mockFile.exists() } returns true - every { mockFile.name } returns coverName - - mockkStatic(ParcelFileDescriptor::class) - coEvery { - ParcelFileDescriptor.open(any(), any()) - } throws IOException("Test fd exception") - - // Create mock cover - val cover = FSStoredCover(mockFile) - - // Act - val fd = cover.fd() - - // Assert - assertNull(fd) - } -} - -// Exposing the private FSStoredCover class for testing -private class FSStoredCover(private val file: File) : org.oxycblt.musikr.covers.FDCover { - override val id: String = file.name - - override suspend fun fd() = - try { - ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) - } catch (e: IOException) { - null - } - - override suspend fun open() = file.inputStream() - - override fun equals(other: Any?) = other is FSStoredCover && file == other.file - - override fun hashCode() = file.hashCode() -} \ No newline at end of file diff --git a/musikr/src/test/java/org/oxycblt/musikr/fs/device/DeviceFSTest.kt b/musikr/src/test/java/org/oxycblt/musikr/fs/device/DeviceFSTest.kt deleted file mode 100644 index 72572eea3..000000000 --- a/musikr/src/test/java/org/oxycblt/musikr/fs/device/DeviceFSTest.kt +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright (c) 2024 Auxio Project - * DeviceFSTest.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.fs.device - -import android.content.ContentResolver -import android.content.Context -import android.database.Cursor -import android.database.MatrixCursor -import android.net.Uri -import android.provider.DocumentsContract -import io.mockk.Runs -import io.mockk.every -import io.mockk.just -import io.mockk.mockk -import io.mockk.mockkStatic -import io.mockk.slot -import io.mockk.spyk -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.flow.toList -import kotlinx.coroutines.test.runTest -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.oxycblt.musikr.fs.Components -import org.oxycblt.musikr.fs.MusicLocation -import org.oxycblt.musikr.fs.Path -import org.oxycblt.musikr.fs.Volume -import org.oxycblt.musikr.fs.path.DocumentPathFactory -import org.robolectric.RobolectricTestRunner -import org.robolectric.annotation.Config - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [30]) -class DeviceFSTest { - - private lateinit var contentResolver: ContentResolver - private lateinit var context: Context - private lateinit var mockRootUri: Uri - private lateinit var mockChildUri: Uri - private lateinit var documentPathFactory: DocumentPathFactory - private lateinit var deviceFS: DeviceFS - private lateinit var testPath: Path - - @Before - fun setup() { - // Set up mocks - contentResolver = mockk(relaxed = true) - context = mockk(relaxed = true) - mockRootUri = mockk() - mockChildUri = mockk() - documentPathFactory = mockk() - - // Create test path - val testVolume = TestVolume("primary") - val components = Components.parseUnix("") - testPath = Path(testVolume, components) - - // Mock context to return our contentResolver - every { context.contentResolverSafe } returns contentResolver - - // Mock DocumentsContract static methods - mockkStatic(DocumentsContract::class) - every { DocumentsContract.buildChildDocumentsUriUsingTree(any(), any()) } returns mockRootUri - every { DocumentsContract.buildDocumentUriUsingTree(any(), any()) } returns mockChildUri - every { DocumentsContract.getTreeDocumentId(any()) } returns "tree-doc-id" - every { DocumentsContract.isTreeUri(any()) } returns true - - // Mock DocumentPathFactory - mockkStatic(DocumentPathFactory::class) - every { DocumentPathFactory.from(any()) } returns documentPathFactory - every { documentPathFactory.unpackDocumentTreeUri(any()) } returns testPath - - // Mock MusicLocation resolving - every { - contentResolver.persistedUriPermissions - } returns emptyList() - - every { - contentResolver.takePersistableUriPermission(any(), any()) - } just Runs - - // Create DeviceFS instance via the companion function - deviceFS = DeviceFS.from(context, withHidden = false) - } - - @Test - fun explore_emptyDirectory_returnsNoFiles() = runTest { - // Arrange - val location = createTestMusicLocation("primary", emptyList()) - val emptyCursor = createMockCursor(emptyList()) - - // Set up the query to return our empty cursor - mockContentResolverQuery(emptyCursor) - - // Act - val result = deviceFS.explore(flow { emit(location) }).toList() - - // Assert - assertTrue(result.isEmpty()) - } - - @Test - fun explore_filtersHiddenFiles() = runTest { - // Arrange - val location = createTestMusicLocation("primary", emptyList()) - - val entries = listOf( - MockFileEntry("doc1", "visible.mp3", "audio/mpeg", 1024, 1000), - MockFileEntry("doc2", ".hidden.mp3", "audio/mpeg", 2048, 2000) - ) - - val cursor = createMockCursor(entries) - mockContentResolverQuery(cursor) - - // Act - val result = deviceFS.explore(flow { emit(location) }).toList() - - // Assert - assertEquals(1, result.size) - assertEquals("visible.mp3", result[0].path.name) - } - - @Test - fun explore_includesHiddenFiles_whenConfigured() = runTest { - // Arrange - val deviceFSWithHidden = DeviceFS.from(context, withHidden = true) - val location = createTestMusicLocation("primary", emptyList()) - - val entries = listOf( - MockFileEntry("doc1", "visible.mp3", "audio/mpeg", 1024, 1000), - MockFileEntry("doc2", ".hidden.mp3", "audio/mpeg", 2048, 2000) - ) - - val cursor = createMockCursor(entries) - mockContentResolverQuery(cursor) - - // Act - val result = deviceFSWithHidden.explore(flow { emit(location) }).toList() - - // Assert - assertEquals(2, result.size) - val fileNames = result.map { it.path.name } - assertTrue(fileNames.contains("visible.mp3")) - assertTrue(fileNames.contains(".hidden.mp3")) - } - - @Test - fun explore_traversesDirectories() = runTest { - // Arrange - val location = createTestMusicLocation("primary", emptyList()) - - // Root directory contains 1 file and 1 subdirectory - val rootEntries = listOf( - MockFileEntry("doc1", "root.mp3", "audio/mpeg", 1024, 1000), - MockDirEntry("dir1", "subdir") - ) - - // Subdirectory contains 2 files - val subdirEntries = listOf( - MockFileEntry("doc2", "sub1.mp3", "audio/mpeg", 2048, 2000), - MockFileEntry("doc3", "sub2.mp3", "audio/mpeg", 3072, 3000) - ) - - // Set up cursor behavior to return different cursors for different queries - val rootCursor = createMockCursor(rootEntries) - val subdirCursor = createMockCursor(subdirEntries) - - // First call will get root entries, second call will get subdir entries - mockContentResolverQuery(rootCursor, subdirCursor) - - // Act - val result = deviceFS.explore(flow { emit(location) }).toList() - - // Assert - assertEquals(3, result.size) - - val fileNames = result.map { it.path.name } - assertTrue(fileNames.contains("root.mp3")) - assertTrue(fileNames.contains("sub1.mp3")) - assertTrue(fileNames.contains("sub2.mp3")) - } - - @Test - fun explore_multipleLocations_returnsAllFiles() = runTest { - // Arrange - val location1 = createTestMusicLocation("primary", listOf("Music")) - val location2 = createTestMusicLocation("secondary", listOf("Downloads")) - - val location1Entries = listOf( - MockFileEntry("doc1", "music1.mp3", "audio/mpeg", 1024, 1000), - MockFileEntry("doc2", "music2.mp3", "audio/mpeg", 2048, 2000) - ) - - val location2Entries = listOf( - MockFileEntry("doc3", "download1.mp3", "audio/mpeg", 3072, 3000) - ) - - val location1Cursor = createMockCursor(location1Entries) - val location2Cursor = createMockCursor(location2Entries) - - // First call will process location1, second call will process location2 - mockContentResolverQuery(location1Cursor, location2Cursor) - - // Act - val result = deviceFS.explore(flow { - emit(location1) - emit(location2) - }).toList() - - // Assert - assertEquals(3, result.size) - - val fileNames = result.map { it.path.name } - assertTrue(fileNames.contains("music1.mp3")) - assertTrue(fileNames.contains("music2.mp3")) - assertTrue(fileNames.contains("download1.mp3")) - } - - @Test - fun explore_fileMetadata_isCorrect() = runTest { - // Arrange - val location = createTestMusicLocation("primary", emptyList()) - - val entries = listOf( - MockFileEntry("doc1", "test.mp3", "audio/mpeg", 1024, 1000) - ) - - val cursor = createMockCursor(entries) - mockContentResolverQuery(cursor) - - // Act - val result = deviceFS.explore(flow { emit(location) }).toList() - - // Assert - assertEquals(1, result.size) - with(result[0]) { - assertEquals("test.mp3", path.name) - assertEquals("audio/mpeg", mimeType) - assertEquals(1024, size) - assertEquals(1000, modifiedMs) - } - } - - /** - * Mock the content resolver's query method to handle cursor interactions - */ - private fun mockContentResolverQuery(vararg cursors: Cursor) { - val cursorList = cursors.toList() - var callCount = 0 - - // Mock the useQuery extension function - every { - contentResolver.useQuery(any(), any(), any(), any(), any()) - } answers { call -> - val cursor = cursorList[callCount % cursorList.size] - callCount++ - val block = call.invocation.args[4] as (Cursor) -> Any - block(cursor) - } - } - - /** - * Create a mock cursor with the given entries - */ - private fun createMockCursor(entries: List): Cursor { - val cursor = MatrixCursor( - arrayOf( - DocumentsContract.Document.COLUMN_DOCUMENT_ID, - DocumentsContract.Document.COLUMN_DISPLAY_NAME, - DocumentsContract.Document.COLUMN_MIME_TYPE, - DocumentsContract.Document.COLUMN_SIZE, - DocumentsContract.Document.COLUMN_LAST_MODIFIED - ) - ) - - entries.forEach { entry -> - when (entry) { - is MockFileEntry -> { - cursor.addRow(arrayOf( - entry.id, - entry.name, - entry.mimeType, - entry.size, - entry.lastModified - )) - } - is MockDirEntry -> { - cursor.addRow(arrayOf( - entry.id, - entry.name, - DocumentsContract.Document.MIME_TYPE_DIR, - 0, - 0 - )) - } - } - } - - return cursor - } - - /** - * Create a test MusicLocation using the factory method - */ - private fun createTestMusicLocation(volumeId: String, pathComponents: List): MusicLocation { - // For each different location, we need a slightly different path to be returned - val volume = TestVolume(volumeId) - val components = Components.parseUnix(pathComponents.joinToString("/")) - val path = Path(volume, components) - - // Override the path that will be returned for this specific call - every { documentPathFactory.unpackDocumentTreeUri(mockRootUri) } returns path - - // Use MusicLocation.new which is a public factory method - return MusicLocation.new(context, mockRootUri)!! - } - - // Mock classes for test data - sealed class MockFSEntry - - data class MockFileEntry( - val id: String, - val name: String, - val mimeType: String, - val size: Long, - val lastModified: Long - ) : MockFSEntry() - - data class MockDirEntry( - val id: String, - val name: String - ) : MockFSEntry() - - class TestVolume(override val id: String?) : Volume.External { - override val mediaStoreName: String? = id - override val components: Components? = null - - override fun resolveName(context: Context): String = id ?: "unknown" - } -} \ No newline at end of file From 3fcc1688f10fbfcc6e42bf23f0770432ee368955 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 17:45:56 -0600 Subject: [PATCH 08/38] all: reformat --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 1 - .../musikr/fs/device/DeviceFSEntries.kt | 21 +- .../musikr/tag/interpret/NamingTest.kt | 2 +- .../oxycblt/musikr/tag/parse/TagFieldsTest.kt | 195 +++++++---------- .../oxycblt/musikr/tag/parse/TagParserTest.kt | 99 ++++----- .../tag/parse/TagParsingEdgeCasesTest.kt | 200 +++++++----------- 6 files changed, 218 insertions(+), 300 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index c9879aa98..a6831cc71 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -43,7 +43,6 @@ internal interface DeviceFS { } } - @OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( private val contentResolver: ContentResolver, diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index 3e3e27d6b..dc43e8dab 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -1,10 +1,27 @@ +/* + * Copyright (c) 2025 Auxio Project + * DeviceFSEntries.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.fs.device import android.net.Uri import kotlinx.coroutines.Deferred import org.oxycblt.musikr.fs.Path - sealed interface DeviceFSEntry { val uri: Uri val path: Path @@ -24,4 +41,4 @@ data class DeviceFile( val mimeType: String, val size: Long, val parent: Deferred -) : DeviceFSEntry \ No newline at end of file +) : DeviceFSEntry diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/NamingTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/NamingTest.kt index ebe3f8109..d52d3f0e3 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/NamingTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/NamingTest.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2023 Auxio Project - * NameTest.kt is part of Auxio. + * NamingTest.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 diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt index 9409f32e7..27e794eda 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt @@ -15,21 +15,19 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.tag.parse -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.annotation.Config - import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test +import org.junit.runner.RunWith import org.oxycblt.musikr.metadata.Metadata import org.oxycblt.musikr.metadata.Properties -import org.oxycblt.musikr.tag.Date +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [30]) @@ -50,11 +48,11 @@ class TagFieldsTest { assertEquals("Xiph Title", metadata.name()) // Test priority (xiph > mp4 > id3v2) - metadata = createTestMetadata( - id3v2Tags = mapOf("TIT2" to listOf("ID3 Title")), - mp4Tags = mapOf("©nam" to listOf("MP4 Title")), - xiphTags = mapOf("TITLE" to listOf("Xiph Title")) - ) + metadata = + createTestMetadata( + id3v2Tags = mapOf("TIT2" to listOf("ID3 Title")), + mp4Tags = mapOf("©nam" to listOf("MP4 Title")), + xiphTags = mapOf("TITLE" to listOf("Xiph Title"))) assertEquals("Xiph Title", metadata.name()) } @@ -73,21 +71,15 @@ class TagFieldsTest { assertEquals(7, metadata.track()) // Test Xiph format - metadata = createTestMetadata( - xiphTags = mapOf( - "TRACKNUMBER" to listOf("9"), - "TOTALTRACKS" to listOf("15") - ) - ) + metadata = + createTestMetadata( + xiphTags = mapOf("TRACKNUMBER" to listOf("9"), "TOTALTRACKS" to listOf("15"))) assertEquals(9, metadata.track()) // Test Xiph alternative total tracks - metadata = createTestMetadata( - xiphTags = mapOf( - "TRACKNUMBER" to listOf("8"), - "TRACKTOTAL" to listOf("16") - ) - ) + metadata = + createTestMetadata( + xiphTags = mapOf("TRACKNUMBER" to listOf("8"), "TRACKTOTAL" to listOf("16"))) assertEquals(8, metadata.track()) } @@ -102,21 +94,15 @@ class TagFieldsTest { assertEquals(1, metadata.disc()) // Test Xiph format - metadata = createTestMetadata( - xiphTags = mapOf( - "DISCNUMBER" to listOf("3"), - "TOTALDISCS" to listOf("4") - ) - ) + metadata = + createTestMetadata( + xiphTags = mapOf("DISCNUMBER" to listOf("3"), "TOTALDISCS" to listOf("4"))) assertEquals(3, metadata.disc()) // Test Xiph alternative total discs - metadata = createTestMetadata( - xiphTags = mapOf( - "DISCNUMBER" to listOf("2"), - "DISCTOTAL" to listOf("5") - ) - ) + metadata = + createTestMetadata( + xiphTags = mapOf("DISCNUMBER" to listOf("2"), "DISCTOTAL" to listOf("5"))) assertEquals(2, metadata.disc()) } @@ -129,10 +115,10 @@ class TagFieldsTest { assertEquals("Rarities", metadata.subtitle()) // Test priority - metadata = createTestMetadata( - id3v2Tags = mapOf("TSST" to listOf("ID3 Subtitle")), - xiphTags = mapOf("DISCSUBTITLE" to listOf("Xiph Subtitle")) - ) + metadata = + createTestMetadata( + id3v2Tags = mapOf("TSST" to listOf("ID3 Subtitle")), + xiphTags = mapOf("DISCSUBTITLE" to listOf("Xiph Subtitle"))) assertEquals("Xiph Subtitle", metadata.subtitle()) } @@ -155,12 +141,10 @@ class TagFieldsTest { assertEquals("2021-12-25", metadata.date().toString()) // Test date priority (ORIGINALDATE > DATE) - metadata = createTestMetadata( - xiphTags = mapOf( - "DATE" to listOf("2023-01-01"), - "ORIGINALDATE" to listOf("2021-01-01") - ) - ) + metadata = + createTestMetadata( + xiphTags = + mapOf("DATE" to listOf("2023-01-01"), "ORIGINALDATE" to listOf("2021-01-01"))) assertEquals("2021-01-01", metadata.date().toString()) // Test MP4 date @@ -171,13 +155,14 @@ class TagFieldsTest { @Test fun metadata_id3v23Date() { // Test ID3v2.3 date components - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TYER" to listOf("2019"), - "TDAT" to listOf("0523"), // May 23 - "TIME" to listOf("2145") // 21:45 - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TYER" to listOf("2019"), + "TDAT" to listOf("0523"), // May 23 + "TIME" to listOf("2145") // 21:45 + )) val date = metadata.date() assertEquals(2019, date?.year) assertEquals(5, date?.month) @@ -188,13 +173,13 @@ class TagFieldsTest { @Test fun metadata_albumInfo() { - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TALB" to listOf("Album Name"), - "TSOA" to listOf("Sort Album Name"), - "TXXX:RELEASETYPE" to listOf("compilation") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TALB" to listOf("Album Name"), + "TSOA" to listOf("Sort Album Name"), + "TXXX:RELEASETYPE" to listOf("compilation"))) assertEquals("Album Name", metadata.albumName()) assertEquals("Sort Album Name", metadata.albumSortName()) @@ -203,14 +188,14 @@ class TagFieldsTest { @Test fun metadata_artistInfo() { - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TPE1" to listOf("Artist 1"), - "TPE2" to listOf("Album Artist 1"), - "TSOP" to listOf("Artist 1 Sort"), - "TSO2" to listOf("Album Artist 1 Sort") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TPE1" to listOf("Artist 1"), + "TPE2" to listOf("Album Artist 1"), + "TSOP" to listOf("Artist 1 Sort"), + "TSO2" to listOf("Album Artist 1 Sort"))) assertEquals(listOf("Artist 1"), metadata.artistNames()) assertEquals(listOf("Album Artist 1"), metadata.albumArtistNames()) @@ -221,23 +206,24 @@ class TagFieldsTest { @Test fun metadata_musicBrainzIds() { // Test different formats and variants of MusicBrainz identifiers - val metadata = createTestMetadata( - xiphTags = mapOf( - "MUSICBRAINZ_RELEASETRACKID" to listOf("track-mb-id"), - "MUSICBRAINZ_ALBUMID" to listOf("album-mb-id") - ) - ) + val metadata = + createTestMetadata( + xiphTags = + mapOf( + "MUSICBRAINZ_RELEASETRACKID" to listOf("track-mb-id"), + "MUSICBRAINZ_ALBUMID" to listOf("album-mb-id"))) assertEquals("track-mb-id", metadata.musicBrainzId()) assertEquals("album-mb-id", metadata.albumMusicBrainzId()) // Test Apple iTunes MP4 variants - val metadata2 = createTestMetadata( - mp4Tags = mapOf( - "----:COM.APPLE.ITUNES:MUSICBRAINZ RELEASE TRACK ID" to listOf("track-mb-id-2"), - "----:COM.APPLE.ITUNES:MUSICBRAINZ ALBUM ID" to listOf("album-mb-id-2") - ) - ) + val metadata2 = + createTestMetadata( + mp4Tags = + mapOf( + "----:COM.APPLE.ITUNES:MUSICBRAINZ RELEASE TRACK ID" to + listOf("track-mb-id-2"), + "----:COM.APPLE.ITUNES:MUSICBRAINZ ALBUM ID" to listOf("album-mb-id-2"))) assertEquals("track-mb-id-2", metadata2.musicBrainzId()) assertEquals("album-mb-id-2", metadata2.albumMusicBrainzId()) @@ -246,76 +232,53 @@ class TagFieldsTest { @Test fun metadata_isCompilation() { // Test various compilation flags - var metadata = createTestMetadata( - id3v2Tags = mapOf("TCMP" to listOf("1")) - ) + var metadata = createTestMetadata(id3v2Tags = mapOf("TCMP" to listOf("1"))) assertTrue(metadata.isCompilation()) - metadata = createTestMetadata( - id3v2Tags = mapOf("TCMP" to listOf("0")) - ) + metadata = createTestMetadata(id3v2Tags = mapOf("TCMP" to listOf("0"))) assertFalse(metadata.isCompilation()) - metadata = createTestMetadata( - xiphTags = mapOf("COMPILATION" to listOf("1")) - ) + metadata = createTestMetadata(xiphTags = mapOf("COMPILATION" to listOf("1"))) assertTrue(metadata.isCompilation()) - metadata = createTestMetadata( - mp4Tags = mapOf("cpil" to listOf("1")) - ) + metadata = createTestMetadata(mp4Tags = mapOf("cpil" to listOf("1"))) assertTrue(metadata.isCompilation()) // Test invalid value - metadata = createTestMetadata( - id3v2Tags = mapOf("TCMP" to listOf("yes")) - ) + metadata = createTestMetadata(id3v2Tags = mapOf("TCMP" to listOf("yes"))) assertFalse(metadata.isCompilation()) } @Test fun metadata_replayGain() { // Test ReplayGain track adjustment - var metadata = createTestMetadata( - xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("-5.5 dB")) - ) + var metadata = + createTestMetadata(xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("-5.5 dB"))) assertEquals(-5.5f, metadata.replayGainTrackAdjustment()) // Test ReplayGain album adjustment - metadata = createTestMetadata( - xiphTags = mapOf("REPLAYGAIN_ALBUM_GAIN" to listOf("3.2 dB")) - ) + metadata = createTestMetadata(xiphTags = mapOf("REPLAYGAIN_ALBUM_GAIN" to listOf("3.2 dB"))) assertEquals(3.2f, metadata.replayGainAlbumAdjustment()) // Test R128 track gain - metadata = createTestMetadata( - xiphTags = mapOf("R128_TRACK_GAIN" to listOf("-2560")) - ) + metadata = createTestMetadata(xiphTags = mapOf("R128_TRACK_GAIN" to listOf("-2560"))) // R128 is converted to match ReplayGain scale (-2560/256 + 5 = -5.0) assertEquals(-5.0f, metadata.replayGainTrackAdjustment()) // Test zero value - metadata = createTestMetadata( - xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("0.0 dB")) - ) + metadata = createTestMetadata(xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("0.0 dB"))) assertNull(metadata.replayGainTrackAdjustment()) } @Test fun metadata_genreNames() { - var metadata = createTestMetadata( - id3v2Tags = mapOf("TCON" to listOf("Rock", "Electronic")) - ) + var metadata = createTestMetadata(id3v2Tags = mapOf("TCON" to listOf("Rock", "Electronic"))) assertEquals(listOf("Rock", "Electronic"), metadata.genreNames()) - metadata = createTestMetadata( - mp4Tags = mapOf("©gen" to listOf("Hip Hop", "Jazz")) - ) + metadata = createTestMetadata(mp4Tags = mapOf("©gen" to listOf("Hip Hop", "Jazz"))) assertEquals(listOf("Hip Hop", "Jazz"), metadata.genreNames()) - metadata = createTestMetadata( - xiphTags = mapOf("GENRE" to listOf("Classical", "Ambient")) - ) + metadata = createTestMetadata(xiphTags = mapOf("GENRE" to listOf("Classical", "Ambient"))) assertEquals(listOf("Classical", "Ambient"), metadata.genreNames()) } @@ -332,4 +295,4 @@ class TagFieldsTest { val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) } -} \ No newline at end of file +} diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt index 79135683f..f52950015 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt @@ -15,19 +15,17 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.tag.parse -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.annotation.Config - import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test +import org.junit.runner.RunWith import org.oxycblt.musikr.metadata.Metadata import org.oxycblt.musikr.metadata.Properties -import org.oxycblt.musikr.tag.Date +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [30]) @@ -36,18 +34,18 @@ class TagParserTest { @Test fun tagParser_parse_basic() { - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TIT2" to listOf("Test Song"), - "TALB" to listOf("Test Album"), - "TPE1" to listOf("Test Artist"), - "TPE2" to listOf("Test Album Artist"), - "TYER" to listOf("2020"), - "TRCK" to listOf("1/10"), - "TPOS" to listOf("1/2"), - "TCON" to listOf("Rock", "Electronic") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TIT2" to listOf("Test Song"), + "TALB" to listOf("Test Album"), + "TPE1" to listOf("Test Artist"), + "TPE2" to listOf("Test Album Artist"), + "TYER" to listOf("2020"), + "TRCK" to listOf("1/10"), + "TPOS" to listOf("1/2"), + "TCON" to listOf("Rock", "Electronic"))) val tags = tagParser.parse(metadata) @@ -64,20 +62,11 @@ class TagParserTest { @Test fun tagParser_parse_multipleFormats() { // Test priority handling between different tag formats - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TIT2" to listOf("ID3 Song"), - "TALB" to listOf("ID3 Album") - ), - xiphTags = mapOf( - "TITLE" to listOf("Xiph Song"), - "ALBUM" to listOf("Xiph Album") - ), - mp4Tags = mapOf( - "©nam" to listOf("MP4 Song"), - "©alb" to listOf("MP4 Album") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = mapOf("TIT2" to listOf("ID3 Song"), "TALB" to listOf("ID3 Album")), + xiphTags = mapOf("TITLE" to listOf("Xiph Song"), "ALBUM" to listOf("Xiph Album")), + mp4Tags = mapOf("©nam" to listOf("MP4 Song"), "©alb" to listOf("MP4 Album"))) val tags = tagParser.parse(metadata) @@ -89,11 +78,7 @@ class TagParserTest { @Test fun tagParser_parse_compilation() { // Test compilation album behavior - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TCMP" to listOf("1") - ) - ) + val metadata = createTestMetadata(id3v2Tags = mapOf("TCMP" to listOf("1"))) val tags = tagParser.parse(metadata) @@ -104,12 +89,10 @@ class TagParserTest { @Test fun tagParser_parse_compilationWithReleaseType() { // Test compilation album with explicit release type - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TCMP" to listOf("1"), - "TXXX:RELEASETYPE" to listOf("soundtrack") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = + mapOf("TCMP" to listOf("1"), "TXXX:RELEASETYPE" to listOf("soundtrack"))) val tags = tagParser.parse(metadata) @@ -130,14 +113,14 @@ class TagParserTest { @Test fun tagParser_musicBrainzIds() { - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TXXX:MUSICBRAINZ RELEASE TRACK ID" to listOf("track-id-123"), - "TXXX:MUSICBRAINZ ALBUM ID" to listOf("album-id-456"), - "TXXX:MUSICBRAINZ ARTIST ID" to listOf("artist-id-789"), - "TXXX:MUSICBRAINZ ALBUM ARTIST ID" to listOf("album-artist-id-012") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TXXX:MUSICBRAINZ RELEASE TRACK ID" to listOf("track-id-123"), + "TXXX:MUSICBRAINZ ALBUM ID" to listOf("album-id-456"), + "TXXX:MUSICBRAINZ ARTIST ID" to listOf("artist-id-789"), + "TXXX:MUSICBRAINZ ALBUM ARTIST ID" to listOf("album-artist-id-012"))) val tags = tagParser.parse(metadata) @@ -149,12 +132,12 @@ class TagParserTest { @Test fun tagParser_replayGain() { - val metadata = createTestMetadata( - xiphTags = mapOf( - "REPLAYGAIN_TRACK_GAIN" to listOf("-3.5 dB"), - "REPLAYGAIN_ALBUM_GAIN" to listOf("-2.1 dB") - ) - ) + val metadata = + createTestMetadata( + xiphTags = + mapOf( + "REPLAYGAIN_TRACK_GAIN" to listOf("-3.5 dB"), + "REPLAYGAIN_ALBUM_GAIN" to listOf("-2.1 dB"))) val tags = tagParser.parse(metadata) @@ -175,4 +158,4 @@ class TagParserTest { val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) } -} \ No newline at end of file +} diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt index 2442d3422..6eef3a43d 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.tag.parse import org.junit.Assert.assertEquals @@ -59,14 +59,14 @@ class TagParsingEdgeCasesTest { @Test fun tagParser_malformedTags() { // Test behavior with malformed tags - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TRCK" to listOf("not-a-number"), - "TPOS" to listOf("also-not-a-number"), - "TYER" to listOf("invalid-year"), - "REPLAYGAIN_TRACK_GAIN" to listOf("not-a-float dB") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TRCK" to listOf("not-a-number"), + "TPOS" to listOf("also-not-a-number"), + "TYER" to listOf("invalid-year"), + "REPLAYGAIN_TRACK_GAIN" to listOf("not-a-float dB"))) val parsedTags = tagParser.parse(metadata) // Verify all numeric fields are null when given invalid values @@ -79,20 +79,11 @@ class TagParsingEdgeCasesTest { @Test fun tagParser_priorityHandling() { // Test that field priority is handled correctly when multiple formats have the same field - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TIT2" to listOf("ID3 Title"), - "TALB" to listOf("ID3 Album") - ), - mp4Tags = mapOf( - "©nam" to listOf("MP4 Title"), - "©alb" to listOf("MP4 Album") - ), - xiphTags = mapOf( - "TITLE" to listOf("Xiph Title"), - "ALBUM" to listOf("Xiph Album") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = mapOf("TIT2" to listOf("ID3 Title"), "TALB" to listOf("ID3 Album")), + mp4Tags = mapOf("©nam" to listOf("MP4 Title"), "©alb" to listOf("MP4 Album")), + xiphTags = mapOf("TITLE" to listOf("Xiph Title"), "ALBUM" to listOf("Xiph Album"))) // Individual field extraction assertEquals("Xiph Title", metadata.name()) @@ -107,20 +98,18 @@ class TagParsingEdgeCasesTest { @Test fun tagParser_fieldBackoffHandling() { // Test that when a format doesn't have a field, it falls back to the next format - val metadata = createTestMetadata( - id3v2Tags = mapOf( - "TIT2" to listOf("ID3 Title"), - "TALB" to listOf("ID3 Album") - ), - mp4Tags = mapOf( - "©nam" to listOf("MP4 Title") - // No album in MP4 - ), - xiphTags = mapOf( - // No title in Xiph - "ALBUM" to listOf("Xiph Album") - ) - ) + val metadata = + createTestMetadata( + id3v2Tags = mapOf("TIT2" to listOf("ID3 Title"), "TALB" to listOf("ID3 Album")), + mp4Tags = + mapOf( + "©nam" to listOf("MP4 Title") + // No album in MP4 + ), + xiphTags = + mapOf( + // No title in Xiph + "ALBUM" to listOf("Xiph Album"))) // Individual field extraction assertEquals("MP4 Title", metadata.name()) // Xiph missing, falls back to MP4 @@ -135,35 +124,26 @@ class TagParsingEdgeCasesTest { @Test fun tagParser_compilationBehavior() { // Test the special behavior for compilation albums - + // Case 1: Compilation flag only - var metadata = createTestMetadata( - id3v2Tags = mapOf( - "TCMP" to listOf("1") - ) - ) + var metadata = createTestMetadata(id3v2Tags = mapOf("TCMP" to listOf("1"))) var tags = tagParser.parse(metadata) assertEquals(listOf("Various Artists"), tags.albumArtistNames) assertEquals(listOf("compilation"), tags.releaseTypes) // Case 2: Compilation flag with explicit album artist - metadata = createTestMetadata( - id3v2Tags = mapOf( - "TCMP" to listOf("1"), - "TPE2" to listOf("Custom Album Artist") - ) - ) + metadata = + createTestMetadata( + id3v2Tags = mapOf("TCMP" to listOf("1"), "TPE2" to listOf("Custom Album Artist"))) tags = tagParser.parse(metadata) assertEquals(listOf("Custom Album Artist"), tags.albumArtistNames) assertEquals(listOf("compilation"), tags.releaseTypes) - + // Case 3: Compilation flag with explicit release type - metadata = createTestMetadata( - id3v2Tags = mapOf( - "TCMP" to listOf("1"), - "TXXX:RELEASETYPE" to listOf("soundtrack") - ) - ) + metadata = + createTestMetadata( + id3v2Tags = + mapOf("TCMP" to listOf("1"), "TXXX:RELEASETYPE" to listOf("soundtrack"))) tags = tagParser.parse(metadata) assertEquals(listOf("Various Artists"), tags.albumArtistNames) assertEquals(listOf("soundtrack"), tags.releaseTypes) @@ -172,95 +152,71 @@ class TagParsingEdgeCasesTest { @Test fun tagFields_replayGainEdgeCases() { // Test various ReplayGain edge cases - + // Non-numeric characters filtered out - var metadata = createTestMetadata( - xiphTags = mapOf( - "REPLAYGAIN_TRACK_GAIN" to listOf("+2.5 dB some text") - ) - ) + var metadata = + createTestMetadata( + xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("+2.5 dB some text"))) assertEquals(2.5f, metadata.replayGainTrackAdjustment()) - + // Zero values filtered - metadata = createTestMetadata( - xiphTags = mapOf( - "REPLAYGAIN_ALBUM_GAIN" to listOf("0.0 dB") - ) - ) + metadata = createTestMetadata(xiphTags = mapOf("REPLAYGAIN_ALBUM_GAIN" to listOf("0.0 dB"))) assertNull(metadata.replayGainAlbumAdjustment()) - + // R128 value with special parsing - metadata = createTestMetadata( - xiphTags = mapOf( - "R128_TRACK_GAIN" to listOf("-1280") - ) - ) + metadata = createTestMetadata(xiphTags = mapOf("R128_TRACK_GAIN" to listOf("-1280"))) assertEquals(0.0f, metadata.replayGainTrackAdjustment()) // -1280/256 + 5 = 0.0 - + // Completely invalid value - metadata = createTestMetadata( - xiphTags = mapOf( - "REPLAYGAIN_TRACK_GAIN" to listOf("not a number") - ) - ) + metadata = + createTestMetadata(xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("not a number"))) assertNull(metadata.replayGainTrackAdjustment()) } @Test fun tagFields_id3v23DateEdgeCases() { // Test ID3v2.3 date edge cases - + // Just year - var metadata = createTestMetadata( - id3v2Tags = mapOf( - "TYER" to listOf("2018") - ) - ) + var metadata = createTestMetadata(id3v2Tags = mapOf("TYER" to listOf("2018"))) assertEquals("2018", metadata.date().toString()) - + // Year and date - metadata = createTestMetadata( - id3v2Tags = mapOf( - "TYER" to listOf("2018"), - "TDAT" to listOf("0315") // March 15 - ) - ) + metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TYER" to listOf("2018"), "TDAT" to listOf("0315") // March 15 + )) assertEquals("2018-03-15", metadata.date().toString()) - + // Year, date and time - metadata = createTestMetadata( - id3v2Tags = mapOf( - "TYER" to listOf("2018"), - "TDAT" to listOf("0315"), // March 15 - "TIME" to listOf("1422") // 14:22 - ) - ) + metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TYER" to listOf("2018"), + "TDAT" to listOf("0315"), // March 15 + "TIME" to listOf("1422") // 14:22 + )) assertEquals("2018-03-15T14:22Z", metadata.date().toString()) - + // Original year - metadata = createTestMetadata( - id3v2Tags = mapOf( - "TORY" to listOf("1995") - ) - ) + metadata = createTestMetadata(id3v2Tags = mapOf("TORY" to listOf("1995"))) assertEquals("1995", metadata.date().toString()) - + // Invalid date components - metadata = createTestMetadata( - id3v2Tags = mapOf( - "TYER" to listOf("2018"), - "TDAT" to listOf("invalid"), - "TIME" to listOf("invalid") - ) - ) + metadata = + createTestMetadata( + id3v2Tags = + mapOf( + "TYER" to listOf("2018"), + "TDAT" to listOf("invalid"), + "TIME" to listOf("invalid"))) assertEquals("2018", metadata.date().toString()) - + // Non-numeric date components - metadata = createTestMetadata( - id3v2Tags = mapOf( - "TYER" to listOf("year") - ) - ) + metadata = createTestMetadata(id3v2Tags = mapOf("TYER" to listOf("year"))) assertNull(metadata.date()) } @@ -277,4 +233,4 @@ class TagParsingEdgeCasesTest { val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) } -} \ No newline at end of file +} From 3913499e2043294c605ec970ce9a90a848d9e8f5 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 18:13:56 -0600 Subject: [PATCH 09/38] musikr: prototype fs cache system Created by Claude 3.7 Sonnet --- build.gradle | 3 +- musikr/build.gradle | 3 + .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 170 ++++++++--- .../oxycblt/musikr/fs/device/DeviceFSCache.kt | 278 ++++++++++++++++++ 4 files changed, 406 insertions(+), 48 deletions(-) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt diff --git a/build.gradle b/build.gradle index 7bc5b84a9..deed629ef 100644 --- a/build.gradle +++ b/build.gradle @@ -30,7 +30,8 @@ plugins { //noinspection GradlePluginVersion id 'com.android.library' version "$agp_version" apply false id "org.jetbrains.kotlin.android" version "$kotlin_version" apply false - id "com.google.devtools.ksp" version '2.0.21-1.0.25' apply false + id 'org.jetbrains.kotlin.plugin.serialization' version "$kotlin_version" apply false + id "com.google.devtools.ksp" version '2.0.21-1.0.27' apply false // We use spotless in the root build.gradle to apply to all modules. id "com.diffplug.spotless" version "6.25.0" apply true } diff --git a/musikr/build.gradle b/musikr/build.gradle index 9e819dcff..a5d021a6e 100644 --- a/musikr/build.gradle +++ b/musikr/build.gradle @@ -7,6 +7,7 @@ plugins { id "com.diffplug.spotless" id "kotlin-parcelize" id "org.jetbrains.dokka" + id "org.jetbrains.kotlin.plugin.serialization" } android { @@ -62,6 +63,8 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version" + implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0' + // AndroidX implementation "androidx.core:core-ktx:$core_version" diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index a6831cc71..a1ae49deb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -15,15 +15,17 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract +import android.util.Log import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow @@ -31,30 +33,52 @@ import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.onCompletion +import kotlinx.coroutines.flow.onStart import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path +private const val TAG = "DeviceFS" + internal interface DeviceFS { fun explore(locations: Flow): Flow companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.contentResolverSafe, withHidden) + DeviceFSImpl(context, withHidden) } } @OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( - private val contentResolver: ContentResolver, + private val context: Context, private val withHidden: Boolean ) : DeviceFS { + private val contentResolver = context.contentResolverSafe + private val cache = DeviceFSCache(context) + override fun explore(locations: Flow): Flow = - locations.flatMapMerge { location -> - exploreDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null) + flow { + // Initialize the cache + cache.loadCache() + // Start a new traversal to track processed URIs for cleanup + cache.resetTraversalTracking() + + emitAll( + locations.flatMapMerge { location -> + exploreDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null + ) + }.flowOn(Dispatchers.IO) + ) + }.onCompletion { + // Cleanup and save cache when exploration is complete + cache.cleanupCache() + cache.saveCache() } private fun exploreDirectoryImpl( @@ -63,56 +87,108 @@ private class DeviceFSImpl( relativePath: Path, parent: Deferred? ): Flow = flow { - // Make a kotlin future - val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) + // Create deferred value for this directory + val directoryUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) val directoryDeferred = CompletableDeferred() val recursive = mutableListOf>() val children = mutableListOf() - contentResolver.useQuery(uri, PROJECTION) { cursor -> - val childUriIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - while (cursor.moveToNext()) { - val childId = cursor.getString(childUriIndex) - val displayName = cursor.getString(displayNameIndex) + // Try to use cached directory contents + val cacheHit = cache.validateDirectoryCache(directoryUri) - // Skip hidden files/directories if ignoreHidden is true - if (!withHidden && displayName.startsWith(".")) { - continue - } + if (cacheHit) { + // We got a cache hit, process the cached children + Log.d(TAG, "Cache hit for $directoryUri") + val cachedChildren = cache.getCachedChildren(directoryUri) - val newPath = relativePath.file(displayName) - val mimeType = cursor.getString(mimeTypeIndex) - val lastModified = cursor.getLong(lastModifiedIndex) + if (cachedChildren != null) { + for (child in cachedChildren) { + val childUri = Uri.parse(child.uri) + val childName = child.name - if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) - } else { - val size = cursor.getLong(sizeIndex) - val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) - val file = - DeviceFile( + // Skip hidden files/directories if withHidden is false + if (!withHidden && childName.startsWith(".")) { + continue + } + + val newPath = relativePath.file(childName) + + if (child.type == EntryType.DIRECTORY) { + // For directories, recursively process them + val childId = DocumentsContract.getDocumentId(childUri) + recursive.add( + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) + ) + } else { + // For files, create DeviceFile objects and emit them + val file = DeviceFile( uri = childUri, - mimeType = mimeType, + mimeType = "", // We don't cache mime type but it's not used elsewhere path = newPath, - size = size, - modifiedMs = lastModified, - parent = directoryDeferred) - children.add(file) - emit(file) + size = 0, // We don't cache size but it's not used elsewhere + modifiedMs = child.modifiedDate, + parent = directoryDeferred + ) + children.add(file) + emit(file) + } + } + } + } else { + // Cache miss or stale data, query the directory contents directly + Log.d(TAG, "Cache miss for $directoryUri, querying directory contents") + val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) + + contentResolver.useQuery(uri, PROJECTION) { cursor -> + val childUriIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + while (cursor.moveToNext()) { + val childId = cursor.getString(childUriIndex) + val displayName = cursor.getString(displayNameIndex) + + // Skip hidden files/directories if ignoreHidden is true + if (!withHidden && displayName.startsWith(".")) { + continue + } + + val newPath = relativePath.file(displayName) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + recursive.add( + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + } else { + val size = cursor.getLong(sizeIndex) + val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) + val file = + DeviceFile( + uri = childUri, + mimeType = mimeType, + path = newPath, + size = size, + modifiedMs = lastModified, + parent = directoryDeferred) + children.add(file) + emit(file) + } } } - directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children)) - emitAll(recursive.asFlow().flattenMerge()) } + + // Complete the directory structure + directoryDeferred.complete(DeviceDirectory(directoryUri, relativePath, parent, children)) + + // Process all subdirectories + emitAll(recursive.asFlow().flattenMerge()) } private companion object { diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt new file mode 100644 index 000000000..c6a893828 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2024 Auxio Project + * DeviceFSCache.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.fs.device + +import android.content.ContentResolver +import android.content.Context +import android.net.Uri +import android.provider.DocumentsContract +import android.util.Log +import androidx.annotation.VisibleForTesting +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import java.io.File + +private const val TAG = "DeviceFSCache" +private const val CACHE_FILE_NAME = "device_fs_cache.json" +private const val SCHEMA_VERSION = "1.0" + +/** + * Caches directory structure information to minimize ContentResolver queries. + * + * This cache is based on the concept that a directory's modification date changes + * when its direct contents change (files added, removed, renamed). We can avoid + * expensive children queries by caching directory contents and validating them + * against the directory's modification timestamp. + */ +internal class DeviceFSCache(private val context: Context) { + + private val contentResolver: ContentResolver = context.contentResolver + private val cache: MutableMap = mutableMapOf() + private val processedUris = mutableSetOf() + + /** + * Gets information about a directory URI. + * + * @param uri The document URI to get information for + * @return A DirectoryInfo object or null if there was an error + */ + fun getDirectoryInfo(uri: Uri): DirectoryInfo? { + return contentResolver.useQuery( + uri, + arrayOf( + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_LAST_MODIFIED + ) + ) { cursor -> + if (cursor.moveToFirst()) { + val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + val name = cursor.getString(nameIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + DirectoryInfo(name, lastModified) + } else { + null + } + } + } + + /** + * Gets the children of a directory URI. + * + * @param uri The document URI to get children for + * @return A list of DirectoryChildren or null if there was an error + */ + fun getDirectoryChildren(uri: Uri): List? { + val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( + uri, + DocumentsContract.getDocumentId(uri) + ) + + return contentResolver.useQuery( + childrenUri, + CHILDREN_PROJECTION + ) { cursor -> + val children = mutableListOf() + + val documentIdIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + while (cursor.moveToNext()) { + val childId = cursor.getString(documentIdIndex) + val displayName = cursor.getString(displayNameIndex) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + val isDirectory = mimeType == DocumentsContract.Document.MIME_TYPE_DIR + val childUri = DocumentsContract.buildDocumentUriUsingTree(uri, childId) + + children.add( + DirectoryChild( + uri = childUri.toString(), + name = displayName, + type = if (isDirectory) EntryType.DIRECTORY else EntryType.FILE, + modifiedDate = lastModified + ) + ) + } + + children + } ?: emptyList() + } + + /** + * Validates the cached data against directory's current state. + * If directory's modification time has changed, cache is updated. + * + * @param uri The URI of the directory to validate + * @return Whether the cache was hit (true) or needed updating (false) + */ + fun validateDirectoryCache(uri: Uri): Boolean { + val uriString = uri.toString() + processedUris.add(uriString) + + val dirInfo = getDirectoryInfo(uri) ?: run { + // Directory no longer exists or accessible, remove from cache + cache.remove(uriString) + return false + } + + // Check if we have cache entry and whether it's still valid + val cachedDir = cache[uriString] + if (cachedDir != null && cachedDir.modifiedDate == dirInfo.lastModified) { + // Cache hit - modification timestamp matches, so content hasn't changed + return true + } + + // Cache miss or stale data - need to update + val children = getDirectoryChildren(uri) ?: emptyList() + cache[uriString] = CachedDirectory( + modifiedDate = dirInfo.lastModified, + children = children + ) + + return false + } + + /** + * Gets cached directory children without validation. + * Use validateDirectoryCache() first to ensure cached data is valid. + * + * @param uri The URI of the directory + * @return The cached children or null if not cached + */ + fun getCachedChildren(uri: Uri): List? { + return cache[uri.toString()]?.children + } + + /** + * Cleans up the cache by removing entries that weren't accessed + * in the current traversal. + */ + fun cleanupCache() { + val toRemove = cache.keys.filter { it !in processedUris } + toRemove.forEach { cache.remove(it) } + } + + /** + * Resets the processed URIs tracking set for a new full traversal. + */ + fun resetTraversalTracking() { + processedUris.clear() + } + + /** + * Saves the cache to disk. + */ + suspend fun saveCache() = withContext(Dispatchers.IO) { + try { + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + val cacheData = CacheData( + schemaVersion = SCHEMA_VERSION, + entries = cache + ) + cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) + } catch (e: Exception) { + Log.e(TAG, "Failed to save cache", e) + } + } + + /** + * Loads the cache from disk. + */ + suspend fun loadCache() = withContext(Dispatchers.IO) { + try { + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + if (cacheFile.exists()) { + val cacheDataString = cacheFile.readText() + val cacheData = Json.decodeFromString(cacheDataString) + + // Only load if schema version matches + if (cacheData.schemaVersion == SCHEMA_VERSION) { + cache.clear() + cache.putAll(cacheData.entries) + } + } + } catch (e: Exception) { + Log.e(TAG, "Failed to load cache", e) + // Start with empty cache if loading fails + cache.clear() + } + } + + companion object { + val CHILDREN_PROJECTION = arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + DocumentsContract.Document.COLUMN_LAST_MODIFIED + ) + } +} + +/** + * Information about a directory. + */ +data class DirectoryInfo( + val name: String, + val lastModified: Long +) + +/** + * Type of a directory entry. + */ +enum class EntryType { + FILE, + DIRECTORY +} + +/** + * Child entry in a directory. + */ +@Serializable +data class DirectoryChild( + val uri: String, + val name: String, + val type: EntryType, + val modifiedDate: Long +) + +/** + * Cached information about a directory. + */ +@Serializable +data class CachedDirectory( + val modifiedDate: Long, + val children: List +) + +/** + * Structure for serializing/deserializing the entire cache. + */ +@Serializable +data class CacheData( + val schemaVersion: String, + val entries: Map +) \ No newline at end of file From 920dda0fe0198c3534c7ce7cb97b23c6b4798d83 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 18:21:33 -0600 Subject: [PATCH 10/38] all: reformat --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 69 +++-- .../oxycblt/musikr/fs/device/DeviceFSCache.kt | 263 ++++++++---------- 2 files changed, 148 insertions(+), 184 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index a1ae49deb..cc3c28829 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -15,10 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device -import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract @@ -35,7 +34,6 @@ import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.onCompletion -import kotlinx.coroutines.flow.onStart import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path @@ -51,35 +49,34 @@ internal interface DeviceFS { } @OptIn(ExperimentalCoroutinesApi::class) -private class DeviceFSImpl( - private val context: Context, - private val withHidden: Boolean -) : DeviceFS { +private class DeviceFSImpl(private val context: Context, private val withHidden: Boolean) : + DeviceFS { private val contentResolver = context.contentResolverSafe private val cache = DeviceFSCache(context) override fun explore(locations: Flow): Flow = flow { - // Initialize the cache - cache.loadCache() - // Start a new traversal to track processed URIs for cleanup - cache.resetTraversalTracking() + // Initialize the cache + cache.loadCache() + // Start a new traversal to track processed URIs for cleanup + cache.resetTraversalTracking() - emitAll( - locations.flatMapMerge { location -> - exploreDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null - ) - }.flowOn(Dispatchers.IO) - ) - }.onCompletion { - // Cleanup and save cache when exploration is complete - cache.cleanupCache() - cache.saveCache() - } + emitAll( + locations + .flatMapMerge { location -> + exploreDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null) + } + .flowOn(Dispatchers.IO)) + } + .onCompletion { + // Cleanup and save cache when exploration is complete + cache.cleanupCache() + cache.saveCache() + } private fun exploreDirectoryImpl( rootUri: Uri, @@ -117,18 +114,18 @@ private class DeviceFSImpl( // For directories, recursively process them val childId = DocumentsContract.getDocumentId(childUri) recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) - ) + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) } else { // For files, create DeviceFile objects and emit them - val file = DeviceFile( - uri = childUri, - mimeType = "", // We don't cache mime type but it's not used elsewhere - path = newPath, - size = 0, // We don't cache size but it's not used elsewhere - modifiedMs = child.modifiedDate, - parent = directoryDeferred - ) + val file = + DeviceFile( + uri = childUri, + mimeType = + "", // We don't cache mime type but it's not used elsewhere + path = newPath, + size = 0, // We don't cache size but it's not used elsewhere + modifiedMs = child.modifiedDate, + parent = directoryDeferred) children.add(file) emit(file) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt index c6a893828..9685d025a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device import android.content.ContentResolver @@ -23,12 +23,11 @@ import android.content.Context import android.net.Uri import android.provider.DocumentsContract import android.util.Log -import androidx.annotation.VisibleForTesting +import java.io.File import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json -import java.io.File private const val TAG = "DeviceFSCache" private const val CACHE_FILE_NAME = "device_fs_cache.json" @@ -36,21 +35,20 @@ private const val SCHEMA_VERSION = "1.0" /** * Caches directory structure information to minimize ContentResolver queries. - * - * This cache is based on the concept that a directory's modification date changes - * when its direct contents change (files added, removed, renamed). We can avoid - * expensive children queries by caching directory contents and validating them - * against the directory's modification timestamp. + * + * This cache is based on the concept that a directory's modification date changes when its direct + * contents change (files added, removed, renamed). We can avoid expensive children queries by + * caching directory contents and validating them against the directory's modification timestamp. */ internal class DeviceFSCache(private val context: Context) { private val contentResolver: ContentResolver = context.contentResolver private val cache: MutableMap = mutableMapOf() private val processedUris = mutableSetOf() - + /** * Gets information about a directory URI. - * + * * @param uri The document URI to get information for * @return A DirectoryInfo object or null if there was an error */ @@ -59,198 +57,177 @@ internal class DeviceFSCache(private val context: Context) { uri, arrayOf( DocumentsContract.Document.COLUMN_DISPLAY_NAME, - DocumentsContract.Document.COLUMN_LAST_MODIFIED - ) - ) { cursor -> - if (cursor.moveToFirst()) { - val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - - val name = cursor.getString(nameIndex) - val lastModified = cursor.getLong(lastModifiedIndex) - - DirectoryInfo(name, lastModified) - } else { - null + DocumentsContract.Document.COLUMN_LAST_MODIFIED)) { cursor -> + if (cursor.moveToFirst()) { + val nameIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow( + DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + val name = cursor.getString(nameIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + DirectoryInfo(name, lastModified) + } else { + null + } } - } } - + /** * Gets the children of a directory URI. - * + * * @param uri The document URI to get children for * @return A list of DirectoryChildren or null if there was an error */ fun getDirectoryChildren(uri: Uri): List? { - val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( - uri, - DocumentsContract.getDocumentId(uri) - ) - - return contentResolver.useQuery( - childrenUri, - CHILDREN_PROJECTION - ) { cursor -> + val childrenUri = + DocumentsContract.buildChildDocumentsUriUsingTree( + uri, DocumentsContract.getDocumentId(uri)) + + return contentResolver.useQuery(childrenUri, CHILDREN_PROJECTION) { cursor -> val children = mutableListOf() - - val documentIdIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - + + val documentIdIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + while (cursor.moveToNext()) { val childId = cursor.getString(documentIdIndex) val displayName = cursor.getString(displayNameIndex) val mimeType = cursor.getString(mimeTypeIndex) val lastModified = cursor.getLong(lastModifiedIndex) - + val isDirectory = mimeType == DocumentsContract.Document.MIME_TYPE_DIR val childUri = DocumentsContract.buildDocumentUriUsingTree(uri, childId) - + children.add( DirectoryChild( uri = childUri.toString(), name = displayName, type = if (isDirectory) EntryType.DIRECTORY else EntryType.FILE, - modifiedDate = lastModified - ) - ) + modifiedDate = lastModified)) } - + children } ?: emptyList() } - + /** - * Validates the cached data against directory's current state. - * If directory's modification time has changed, cache is updated. - * + * Validates the cached data against directory's current state. If directory's modification time + * has changed, cache is updated. + * * @param uri The URI of the directory to validate * @return Whether the cache was hit (true) or needed updating (false) */ fun validateDirectoryCache(uri: Uri): Boolean { val uriString = uri.toString() processedUris.add(uriString) - - val dirInfo = getDirectoryInfo(uri) ?: run { - // Directory no longer exists or accessible, remove from cache - cache.remove(uriString) - return false - } - + + val dirInfo = + getDirectoryInfo(uri) + ?: run { + // Directory no longer exists or accessible, remove from cache + cache.remove(uriString) + return false + } + // Check if we have cache entry and whether it's still valid val cachedDir = cache[uriString] if (cachedDir != null && cachedDir.modifiedDate == dirInfo.lastModified) { // Cache hit - modification timestamp matches, so content hasn't changed return true } - + // Cache miss or stale data - need to update val children = getDirectoryChildren(uri) ?: emptyList() - cache[uriString] = CachedDirectory( - modifiedDate = dirInfo.lastModified, - children = children - ) - + cache[uriString] = CachedDirectory(modifiedDate = dirInfo.lastModified, children = children) + return false } - + /** - * Gets cached directory children without validation. - * Use validateDirectoryCache() first to ensure cached data is valid. - * + * Gets cached directory children without validation. Use validateDirectoryCache() first to + * ensure cached data is valid. + * * @param uri The URI of the directory * @return The cached children or null if not cached */ fun getCachedChildren(uri: Uri): List? { return cache[uri.toString()]?.children } - - /** - * Cleans up the cache by removing entries that weren't accessed - * in the current traversal. - */ + + /** Cleans up the cache by removing entries that weren't accessed in the current traversal. */ fun cleanupCache() { val toRemove = cache.keys.filter { it !in processedUris } toRemove.forEach { cache.remove(it) } } - - /** - * Resets the processed URIs tracking set for a new full traversal. - */ + + /** Resets the processed URIs tracking set for a new full traversal. */ fun resetTraversalTracking() { processedUris.clear() } - - /** - * Saves the cache to disk. - */ - suspend fun saveCache() = withContext(Dispatchers.IO) { - try { - val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) - val cacheData = CacheData( - schemaVersion = SCHEMA_VERSION, - entries = cache - ) - cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) - } catch (e: Exception) { - Log.e(TAG, "Failed to save cache", e) - } - } - - /** - * Loads the cache from disk. - */ - suspend fun loadCache() = withContext(Dispatchers.IO) { - try { - val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) - if (cacheFile.exists()) { - val cacheDataString = cacheFile.readText() - val cacheData = Json.decodeFromString(cacheDataString) - - // Only load if schema version matches - if (cacheData.schemaVersion == SCHEMA_VERSION) { - cache.clear() - cache.putAll(cacheData.entries) - } + + /** Saves the cache to disk. */ + suspend fun saveCache() = + withContext(Dispatchers.IO) { + try { + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + val cacheData = CacheData(schemaVersion = SCHEMA_VERSION, entries = cache) + cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) + } catch (e: Exception) { + Log.e(TAG, "Failed to save cache", e) } - } catch (e: Exception) { - Log.e(TAG, "Failed to load cache", e) - // Start with empty cache if loading fails - cache.clear() } - } - + + /** Loads the cache from disk. */ + suspend fun loadCache() = + withContext(Dispatchers.IO) { + try { + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + if (cacheFile.exists()) { + val cacheDataString = cacheFile.readText() + val cacheData = Json.decodeFromString(cacheDataString) + + // Only load if schema version matches + if (cacheData.schemaVersion == SCHEMA_VERSION) { + cache.clear() + cache.putAll(cacheData.entries) + } + } + } catch (e: Exception) { + Log.e(TAG, "Failed to load cache", e) + // Start with empty cache if loading fails + cache.clear() + } + } + companion object { - val CHILDREN_PROJECTION = arrayOf( - DocumentsContract.Document.COLUMN_DOCUMENT_ID, - DocumentsContract.Document.COLUMN_DISPLAY_NAME, - DocumentsContract.Document.COLUMN_MIME_TYPE, - DocumentsContract.Document.COLUMN_LAST_MODIFIED - ) + val CHILDREN_PROJECTION = + arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + DocumentsContract.Document.COLUMN_LAST_MODIFIED) } } -/** - * Information about a directory. - */ -data class DirectoryInfo( - val name: String, - val lastModified: Long -) +/** Information about a directory. */ +data class DirectoryInfo(val name: String, val lastModified: Long) -/** - * Type of a directory entry. - */ +/** Type of a directory entry. */ enum class EntryType { FILE, DIRECTORY } -/** - * Child entry in a directory. - */ +/** Child entry in a directory. */ @Serializable data class DirectoryChild( val uri: String, @@ -259,20 +236,10 @@ data class DirectoryChild( val modifiedDate: Long ) -/** - * Cached information about a directory. - */ +/** Cached information about a directory. */ @Serializable -data class CachedDirectory( - val modifiedDate: Long, - val children: List -) +data class CachedDirectory(val modifiedDate: Long, val children: List) -/** - * Structure for serializing/deserializing the entire cache. - */ +/** Structure for serializing/deserializing the entire cache. */ @Serializable -data class CacheData( - val schemaVersion: String, - val entries: Map -) \ No newline at end of file +data class CacheData(val schemaVersion: String, val entries: Map) From f39c95af2336a16132a86e81510640096349a6b9 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 21:00:54 -0600 Subject: [PATCH 11/38] musikr: commit fs cache to files --- .../main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt index 9685d025a..1342b0dbc 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt @@ -178,7 +178,7 @@ internal class DeviceFSCache(private val context: Context) { suspend fun saveCache() = withContext(Dispatchers.IO) { try { - val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + val cacheFile = File(context.filesDir, CACHE_FILE_NAME) val cacheData = CacheData(schemaVersion = SCHEMA_VERSION, entries = cache) cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) } catch (e: Exception) { @@ -190,7 +190,7 @@ internal class DeviceFSCache(private val context: Context) { suspend fun loadCache() = withContext(Dispatchers.IO) { try { - val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + val cacheFile = File(context.filesDir, CACHE_FILE_NAME) if (cacheFile.exists()) { val cacheDataString = cacheFile.readText() val cacheData = Json.decodeFromString(cacheDataString) From 154bfb3c970c2a2168e71c59106622d397d497a3 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 21:56:54 -0600 Subject: [PATCH 12/38] Revert "musikr: commit fs cache to files" This reverts commit f39c95af2336a16132a86e81510640096349a6b9. --- .../main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt index 1342b0dbc..9685d025a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt @@ -178,7 +178,7 @@ internal class DeviceFSCache(private val context: Context) { suspend fun saveCache() = withContext(Dispatchers.IO) { try { - val cacheFile = File(context.filesDir, CACHE_FILE_NAME) + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) val cacheData = CacheData(schemaVersion = SCHEMA_VERSION, entries = cache) cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) } catch (e: Exception) { @@ -190,7 +190,7 @@ internal class DeviceFSCache(private val context: Context) { suspend fun loadCache() = withContext(Dispatchers.IO) { try { - val cacheFile = File(context.filesDir, CACHE_FILE_NAME) + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) if (cacheFile.exists()) { val cacheDataString = cacheFile.readText() val cacheData = Json.decodeFromString(cacheDataString) From dbc46e75677f937d4678a33f27483237cd329f65 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 21:57:05 -0600 Subject: [PATCH 13/38] Revert "all: reformat" This reverts commit 920dda0fe0198c3534c7ce7cb97b23c6b4798d83. --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 69 ++--- .../oxycblt/musikr/fs/device/DeviceFSCache.kt | 259 ++++++++++-------- 2 files changed, 182 insertions(+), 146 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index cc3c28829..a1ae49deb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -15,9 +15,10 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device +import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract @@ -34,6 +35,7 @@ import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.onCompletion +import kotlinx.coroutines.flow.onStart import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path @@ -49,34 +51,35 @@ internal interface DeviceFS { } @OptIn(ExperimentalCoroutinesApi::class) -private class DeviceFSImpl(private val context: Context, private val withHidden: Boolean) : - DeviceFS { +private class DeviceFSImpl( + private val context: Context, + private val withHidden: Boolean +) : DeviceFS { private val contentResolver = context.contentResolverSafe private val cache = DeviceFSCache(context) override fun explore(locations: Flow): Flow = flow { - // Initialize the cache - cache.loadCache() - // Start a new traversal to track processed URIs for cleanup - cache.resetTraversalTracking() + // Initialize the cache + cache.loadCache() + // Start a new traversal to track processed URIs for cleanup + cache.resetTraversalTracking() - emitAll( - locations - .flatMapMerge { location -> - exploreDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null) - } - .flowOn(Dispatchers.IO)) - } - .onCompletion { - // Cleanup and save cache when exploration is complete - cache.cleanupCache() - cache.saveCache() - } + emitAll( + locations.flatMapMerge { location -> + exploreDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null + ) + }.flowOn(Dispatchers.IO) + ) + }.onCompletion { + // Cleanup and save cache when exploration is complete + cache.cleanupCache() + cache.saveCache() + } private fun exploreDirectoryImpl( rootUri: Uri, @@ -114,18 +117,18 @@ private class DeviceFSImpl(private val context: Context, private val withHidden: // For directories, recursively process them val childId = DocumentsContract.getDocumentId(childUri) recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) + ) } else { // For files, create DeviceFile objects and emit them - val file = - DeviceFile( - uri = childUri, - mimeType = - "", // We don't cache mime type but it's not used elsewhere - path = newPath, - size = 0, // We don't cache size but it's not used elsewhere - modifiedMs = child.modifiedDate, - parent = directoryDeferred) + val file = DeviceFile( + uri = childUri, + mimeType = "", // We don't cache mime type but it's not used elsewhere + path = newPath, + size = 0, // We don't cache size but it's not used elsewhere + modifiedMs = child.modifiedDate, + parent = directoryDeferred + ) children.add(file) emit(file) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt index 9685d025a..c6a893828 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device import android.content.ContentResolver @@ -23,11 +23,12 @@ import android.content.Context import android.net.Uri import android.provider.DocumentsContract import android.util.Log -import java.io.File +import androidx.annotation.VisibleForTesting import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +import java.io.File private const val TAG = "DeviceFSCache" private const val CACHE_FILE_NAME = "device_fs_cache.json" @@ -35,20 +36,21 @@ private const val SCHEMA_VERSION = "1.0" /** * Caches directory structure information to minimize ContentResolver queries. - * - * This cache is based on the concept that a directory's modification date changes when its direct - * contents change (files added, removed, renamed). We can avoid expensive children queries by - * caching directory contents and validating them against the directory's modification timestamp. + * + * This cache is based on the concept that a directory's modification date changes + * when its direct contents change (files added, removed, renamed). We can avoid + * expensive children queries by caching directory contents and validating them + * against the directory's modification timestamp. */ internal class DeviceFSCache(private val context: Context) { private val contentResolver: ContentResolver = context.contentResolver private val cache: MutableMap = mutableMapOf() private val processedUris = mutableSetOf() - + /** * Gets information about a directory URI. - * + * * @param uri The document URI to get information for * @return A DirectoryInfo object or null if there was an error */ @@ -57,177 +59,198 @@ internal class DeviceFSCache(private val context: Context) { uri, arrayOf( DocumentsContract.Document.COLUMN_DISPLAY_NAME, - DocumentsContract.Document.COLUMN_LAST_MODIFIED)) { cursor -> - if (cursor.moveToFirst()) { - val nameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow( - DocumentsContract.Document.COLUMN_LAST_MODIFIED) - - val name = cursor.getString(nameIndex) - val lastModified = cursor.getLong(lastModifiedIndex) - - DirectoryInfo(name, lastModified) - } else { - null - } + DocumentsContract.Document.COLUMN_LAST_MODIFIED + ) + ) { cursor -> + if (cursor.moveToFirst()) { + val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + val name = cursor.getString(nameIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + DirectoryInfo(name, lastModified) + } else { + null } + } } - + /** * Gets the children of a directory URI. - * + * * @param uri The document URI to get children for * @return A list of DirectoryChildren or null if there was an error */ fun getDirectoryChildren(uri: Uri): List? { - val childrenUri = - DocumentsContract.buildChildDocumentsUriUsingTree( - uri, DocumentsContract.getDocumentId(uri)) - - return contentResolver.useQuery(childrenUri, CHILDREN_PROJECTION) { cursor -> + val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( + uri, + DocumentsContract.getDocumentId(uri) + ) + + return contentResolver.useQuery( + childrenUri, + CHILDREN_PROJECTION + ) { cursor -> val children = mutableListOf() - - val documentIdIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - + + val documentIdIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + while (cursor.moveToNext()) { val childId = cursor.getString(documentIdIndex) val displayName = cursor.getString(displayNameIndex) val mimeType = cursor.getString(mimeTypeIndex) val lastModified = cursor.getLong(lastModifiedIndex) - + val isDirectory = mimeType == DocumentsContract.Document.MIME_TYPE_DIR val childUri = DocumentsContract.buildDocumentUriUsingTree(uri, childId) - + children.add( DirectoryChild( uri = childUri.toString(), name = displayName, type = if (isDirectory) EntryType.DIRECTORY else EntryType.FILE, - modifiedDate = lastModified)) + modifiedDate = lastModified + ) + ) } - + children } ?: emptyList() } - + /** - * Validates the cached data against directory's current state. If directory's modification time - * has changed, cache is updated. - * + * Validates the cached data against directory's current state. + * If directory's modification time has changed, cache is updated. + * * @param uri The URI of the directory to validate * @return Whether the cache was hit (true) or needed updating (false) */ fun validateDirectoryCache(uri: Uri): Boolean { val uriString = uri.toString() processedUris.add(uriString) - - val dirInfo = - getDirectoryInfo(uri) - ?: run { - // Directory no longer exists or accessible, remove from cache - cache.remove(uriString) - return false - } - + + val dirInfo = getDirectoryInfo(uri) ?: run { + // Directory no longer exists or accessible, remove from cache + cache.remove(uriString) + return false + } + // Check if we have cache entry and whether it's still valid val cachedDir = cache[uriString] if (cachedDir != null && cachedDir.modifiedDate == dirInfo.lastModified) { // Cache hit - modification timestamp matches, so content hasn't changed return true } - + // Cache miss or stale data - need to update val children = getDirectoryChildren(uri) ?: emptyList() - cache[uriString] = CachedDirectory(modifiedDate = dirInfo.lastModified, children = children) - + cache[uriString] = CachedDirectory( + modifiedDate = dirInfo.lastModified, + children = children + ) + return false } - + /** - * Gets cached directory children without validation. Use validateDirectoryCache() first to - * ensure cached data is valid. - * + * Gets cached directory children without validation. + * Use validateDirectoryCache() first to ensure cached data is valid. + * * @param uri The URI of the directory * @return The cached children or null if not cached */ fun getCachedChildren(uri: Uri): List? { return cache[uri.toString()]?.children } - - /** Cleans up the cache by removing entries that weren't accessed in the current traversal. */ + + /** + * Cleans up the cache by removing entries that weren't accessed + * in the current traversal. + */ fun cleanupCache() { val toRemove = cache.keys.filter { it !in processedUris } toRemove.forEach { cache.remove(it) } } - - /** Resets the processed URIs tracking set for a new full traversal. */ + + /** + * Resets the processed URIs tracking set for a new full traversal. + */ fun resetTraversalTracking() { processedUris.clear() } - - /** Saves the cache to disk. */ - suspend fun saveCache() = - withContext(Dispatchers.IO) { - try { - val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) - val cacheData = CacheData(schemaVersion = SCHEMA_VERSION, entries = cache) - cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) - } catch (e: Exception) { - Log.e(TAG, "Failed to save cache", e) - } + + /** + * Saves the cache to disk. + */ + suspend fun saveCache() = withContext(Dispatchers.IO) { + try { + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + val cacheData = CacheData( + schemaVersion = SCHEMA_VERSION, + entries = cache + ) + cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) + } catch (e: Exception) { + Log.e(TAG, "Failed to save cache", e) } - - /** Loads the cache from disk. */ - suspend fun loadCache() = - withContext(Dispatchers.IO) { - try { - val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) - if (cacheFile.exists()) { - val cacheDataString = cacheFile.readText() - val cacheData = Json.decodeFromString(cacheDataString) - - // Only load if schema version matches - if (cacheData.schemaVersion == SCHEMA_VERSION) { - cache.clear() - cache.putAll(cacheData.entries) - } + } + + /** + * Loads the cache from disk. + */ + suspend fun loadCache() = withContext(Dispatchers.IO) { + try { + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + if (cacheFile.exists()) { + val cacheDataString = cacheFile.readText() + val cacheData = Json.decodeFromString(cacheDataString) + + // Only load if schema version matches + if (cacheData.schemaVersion == SCHEMA_VERSION) { + cache.clear() + cache.putAll(cacheData.entries) } - } catch (e: Exception) { - Log.e(TAG, "Failed to load cache", e) - // Start with empty cache if loading fails - cache.clear() } + } catch (e: Exception) { + Log.e(TAG, "Failed to load cache", e) + // Start with empty cache if loading fails + cache.clear() } - + } + companion object { - val CHILDREN_PROJECTION = - arrayOf( - DocumentsContract.Document.COLUMN_DOCUMENT_ID, - DocumentsContract.Document.COLUMN_DISPLAY_NAME, - DocumentsContract.Document.COLUMN_MIME_TYPE, - DocumentsContract.Document.COLUMN_LAST_MODIFIED) + val CHILDREN_PROJECTION = arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + DocumentsContract.Document.COLUMN_LAST_MODIFIED + ) } } -/** Information about a directory. */ -data class DirectoryInfo(val name: String, val lastModified: Long) +/** + * Information about a directory. + */ +data class DirectoryInfo( + val name: String, + val lastModified: Long +) -/** Type of a directory entry. */ +/** + * Type of a directory entry. + */ enum class EntryType { FILE, DIRECTORY } -/** Child entry in a directory. */ +/** + * Child entry in a directory. + */ @Serializable data class DirectoryChild( val uri: String, @@ -236,10 +259,20 @@ data class DirectoryChild( val modifiedDate: Long ) -/** Cached information about a directory. */ +/** + * Cached information about a directory. + */ @Serializable -data class CachedDirectory(val modifiedDate: Long, val children: List) +data class CachedDirectory( + val modifiedDate: Long, + val children: List +) -/** Structure for serializing/deserializing the entire cache. */ +/** + * Structure for serializing/deserializing the entire cache. + */ @Serializable -data class CacheData(val schemaVersion: String, val entries: Map) +data class CacheData( + val schemaVersion: String, + val entries: Map +) \ No newline at end of file From 1355be1e349bc4f4891dc9ff516d6ec82e65cbd5 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 21:57:50 -0600 Subject: [PATCH 14/38] Revert "musikr: prototype fs cache system" This reverts commit 3913499e2043294c605ec970ce9a90a848d9e8f5. --- build.gradle | 3 +- musikr/build.gradle | 3 - .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 170 +++-------- .../oxycblt/musikr/fs/device/DeviceFSCache.kt | 278 ------------------ 4 files changed, 48 insertions(+), 406 deletions(-) delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt diff --git a/build.gradle b/build.gradle index deed629ef..7bc5b84a9 100644 --- a/build.gradle +++ b/build.gradle @@ -30,8 +30,7 @@ plugins { //noinspection GradlePluginVersion id 'com.android.library' version "$agp_version" apply false id "org.jetbrains.kotlin.android" version "$kotlin_version" apply false - id 'org.jetbrains.kotlin.plugin.serialization' version "$kotlin_version" apply false - id "com.google.devtools.ksp" version '2.0.21-1.0.27' apply false + id "com.google.devtools.ksp" version '2.0.21-1.0.25' apply false // We use spotless in the root build.gradle to apply to all modules. id "com.diffplug.spotless" version "6.25.0" apply true } diff --git a/musikr/build.gradle b/musikr/build.gradle index a5d021a6e..9e819dcff 100644 --- a/musikr/build.gradle +++ b/musikr/build.gradle @@ -7,7 +7,6 @@ plugins { id "com.diffplug.spotless" id "kotlin-parcelize" id "org.jetbrains.dokka" - id "org.jetbrains.kotlin.plugin.serialization" } android { @@ -63,8 +62,6 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version" - implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0' - // AndroidX implementation "androidx.core:core-ktx:$core_version" diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index a1ae49deb..a6831cc71 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -15,17 +15,15 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract -import android.util.Log import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred -import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow @@ -33,52 +31,30 @@ import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.flow.flowOn -import kotlinx.coroutines.flow.onCompletion -import kotlinx.coroutines.flow.onStart import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path -private const val TAG = "DeviceFS" - internal interface DeviceFS { fun explore(locations: Flow): Flow companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context, withHidden) + DeviceFSImpl(context.contentResolverSafe, withHidden) } } @OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( - private val context: Context, + private val contentResolver: ContentResolver, private val withHidden: Boolean ) : DeviceFS { - private val contentResolver = context.contentResolverSafe - private val cache = DeviceFSCache(context) - override fun explore(locations: Flow): Flow = - flow { - // Initialize the cache - cache.loadCache() - // Start a new traversal to track processed URIs for cleanup - cache.resetTraversalTracking() - - emitAll( - locations.flatMapMerge { location -> - exploreDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null - ) - }.flowOn(Dispatchers.IO) - ) - }.onCompletion { - // Cleanup and save cache when exploration is complete - cache.cleanupCache() - cache.saveCache() + locations.flatMapMerge { location -> + exploreDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null) } private fun exploreDirectoryImpl( @@ -87,108 +63,56 @@ private class DeviceFSImpl( relativePath: Path, parent: Deferred? ): Flow = flow { - // Create deferred value for this directory - val directoryUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) + // Make a kotlin future + val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) val directoryDeferred = CompletableDeferred() val recursive = mutableListOf>() val children = mutableListOf() + contentResolver.useQuery(uri, PROJECTION) { cursor -> + val childUriIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - // Try to use cached directory contents - val cacheHit = cache.validateDirectoryCache(directoryUri) + while (cursor.moveToNext()) { + val childId = cursor.getString(childUriIndex) + val displayName = cursor.getString(displayNameIndex) - if (cacheHit) { - // We got a cache hit, process the cached children - Log.d(TAG, "Cache hit for $directoryUri") - val cachedChildren = cache.getCachedChildren(directoryUri) + // Skip hidden files/directories if ignoreHidden is true + if (!withHidden && displayName.startsWith(".")) { + continue + } - if (cachedChildren != null) { - for (child in cachedChildren) { - val childUri = Uri.parse(child.uri) - val childName = child.name + val newPath = relativePath.file(displayName) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) - // Skip hidden files/directories if withHidden is false - if (!withHidden && childName.startsWith(".")) { - continue - } - - val newPath = relativePath.file(childName) - - if (child.type == EntryType.DIRECTORY) { - // For directories, recursively process them - val childId = DocumentsContract.getDocumentId(childUri) - recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) - ) - } else { - // For files, create DeviceFile objects and emit them - val file = DeviceFile( + if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + recursive.add( + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + } else { + val size = cursor.getLong(sizeIndex) + val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) + val file = + DeviceFile( uri = childUri, - mimeType = "", // We don't cache mime type but it's not used elsewhere + mimeType = mimeType, path = newPath, - size = 0, // We don't cache size but it's not used elsewhere - modifiedMs = child.modifiedDate, - parent = directoryDeferred - ) - children.add(file) - emit(file) - } - } - } - } else { - // Cache miss or stale data, query the directory contents directly - Log.d(TAG, "Cache miss for $directoryUri, querying directory contents") - val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) - - contentResolver.useQuery(uri, PROJECTION) { cursor -> - val childUriIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - - while (cursor.moveToNext()) { - val childId = cursor.getString(childUriIndex) - val displayName = cursor.getString(displayNameIndex) - - // Skip hidden files/directories if ignoreHidden is true - if (!withHidden && displayName.startsWith(".")) { - continue - } - - val newPath = relativePath.file(displayName) - val mimeType = cursor.getString(mimeTypeIndex) - val lastModified = cursor.getLong(lastModifiedIndex) - - if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) - } else { - val size = cursor.getLong(sizeIndex) - val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) - val file = - DeviceFile( - uri = childUri, - mimeType = mimeType, - path = newPath, - size = size, - modifiedMs = lastModified, - parent = directoryDeferred) - children.add(file) - emit(file) - } + size = size, + modifiedMs = lastModified, + parent = directoryDeferred) + children.add(file) + emit(file) } } + directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children)) + emitAll(recursive.asFlow().flattenMerge()) } - - // Complete the directory structure - directoryDeferred.complete(DeviceDirectory(directoryUri, relativePath, parent, children)) - - // Process all subdirectories - emitAll(recursive.asFlow().flattenMerge()) } private companion object { diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt deleted file mode 100644 index c6a893828..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (c) 2024 Auxio Project - * DeviceFSCache.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.fs.device - -import android.content.ContentResolver -import android.content.Context -import android.net.Uri -import android.provider.DocumentsContract -import android.util.Log -import androidx.annotation.VisibleForTesting -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json -import java.io.File - -private const val TAG = "DeviceFSCache" -private const val CACHE_FILE_NAME = "device_fs_cache.json" -private const val SCHEMA_VERSION = "1.0" - -/** - * Caches directory structure information to minimize ContentResolver queries. - * - * This cache is based on the concept that a directory's modification date changes - * when its direct contents change (files added, removed, renamed). We can avoid - * expensive children queries by caching directory contents and validating them - * against the directory's modification timestamp. - */ -internal class DeviceFSCache(private val context: Context) { - - private val contentResolver: ContentResolver = context.contentResolver - private val cache: MutableMap = mutableMapOf() - private val processedUris = mutableSetOf() - - /** - * Gets information about a directory URI. - * - * @param uri The document URI to get information for - * @return A DirectoryInfo object or null if there was an error - */ - fun getDirectoryInfo(uri: Uri): DirectoryInfo? { - return contentResolver.useQuery( - uri, - arrayOf( - DocumentsContract.Document.COLUMN_DISPLAY_NAME, - DocumentsContract.Document.COLUMN_LAST_MODIFIED - ) - ) { cursor -> - if (cursor.moveToFirst()) { - val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - - val name = cursor.getString(nameIndex) - val lastModified = cursor.getLong(lastModifiedIndex) - - DirectoryInfo(name, lastModified) - } else { - null - } - } - } - - /** - * Gets the children of a directory URI. - * - * @param uri The document URI to get children for - * @return A list of DirectoryChildren or null if there was an error - */ - fun getDirectoryChildren(uri: Uri): List? { - val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( - uri, - DocumentsContract.getDocumentId(uri) - ) - - return contentResolver.useQuery( - childrenUri, - CHILDREN_PROJECTION - ) { cursor -> - val children = mutableListOf() - - val documentIdIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - - while (cursor.moveToNext()) { - val childId = cursor.getString(documentIdIndex) - val displayName = cursor.getString(displayNameIndex) - val mimeType = cursor.getString(mimeTypeIndex) - val lastModified = cursor.getLong(lastModifiedIndex) - - val isDirectory = mimeType == DocumentsContract.Document.MIME_TYPE_DIR - val childUri = DocumentsContract.buildDocumentUriUsingTree(uri, childId) - - children.add( - DirectoryChild( - uri = childUri.toString(), - name = displayName, - type = if (isDirectory) EntryType.DIRECTORY else EntryType.FILE, - modifiedDate = lastModified - ) - ) - } - - children - } ?: emptyList() - } - - /** - * Validates the cached data against directory's current state. - * If directory's modification time has changed, cache is updated. - * - * @param uri The URI of the directory to validate - * @return Whether the cache was hit (true) or needed updating (false) - */ - fun validateDirectoryCache(uri: Uri): Boolean { - val uriString = uri.toString() - processedUris.add(uriString) - - val dirInfo = getDirectoryInfo(uri) ?: run { - // Directory no longer exists or accessible, remove from cache - cache.remove(uriString) - return false - } - - // Check if we have cache entry and whether it's still valid - val cachedDir = cache[uriString] - if (cachedDir != null && cachedDir.modifiedDate == dirInfo.lastModified) { - // Cache hit - modification timestamp matches, so content hasn't changed - return true - } - - // Cache miss or stale data - need to update - val children = getDirectoryChildren(uri) ?: emptyList() - cache[uriString] = CachedDirectory( - modifiedDate = dirInfo.lastModified, - children = children - ) - - return false - } - - /** - * Gets cached directory children without validation. - * Use validateDirectoryCache() first to ensure cached data is valid. - * - * @param uri The URI of the directory - * @return The cached children or null if not cached - */ - fun getCachedChildren(uri: Uri): List? { - return cache[uri.toString()]?.children - } - - /** - * Cleans up the cache by removing entries that weren't accessed - * in the current traversal. - */ - fun cleanupCache() { - val toRemove = cache.keys.filter { it !in processedUris } - toRemove.forEach { cache.remove(it) } - } - - /** - * Resets the processed URIs tracking set for a new full traversal. - */ - fun resetTraversalTracking() { - processedUris.clear() - } - - /** - * Saves the cache to disk. - */ - suspend fun saveCache() = withContext(Dispatchers.IO) { - try { - val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) - val cacheData = CacheData( - schemaVersion = SCHEMA_VERSION, - entries = cache - ) - cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) - } catch (e: Exception) { - Log.e(TAG, "Failed to save cache", e) - } - } - - /** - * Loads the cache from disk. - */ - suspend fun loadCache() = withContext(Dispatchers.IO) { - try { - val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) - if (cacheFile.exists()) { - val cacheDataString = cacheFile.readText() - val cacheData = Json.decodeFromString(cacheDataString) - - // Only load if schema version matches - if (cacheData.schemaVersion == SCHEMA_VERSION) { - cache.clear() - cache.putAll(cacheData.entries) - } - } - } catch (e: Exception) { - Log.e(TAG, "Failed to load cache", e) - // Start with empty cache if loading fails - cache.clear() - } - } - - companion object { - val CHILDREN_PROJECTION = arrayOf( - DocumentsContract.Document.COLUMN_DOCUMENT_ID, - DocumentsContract.Document.COLUMN_DISPLAY_NAME, - DocumentsContract.Document.COLUMN_MIME_TYPE, - DocumentsContract.Document.COLUMN_LAST_MODIFIED - ) - } -} - -/** - * Information about a directory. - */ -data class DirectoryInfo( - val name: String, - val lastModified: Long -) - -/** - * Type of a directory entry. - */ -enum class EntryType { - FILE, - DIRECTORY -} - -/** - * Child entry in a directory. - */ -@Serializable -data class DirectoryChild( - val uri: String, - val name: String, - val type: EntryType, - val modifiedDate: Long -) - -/** - * Cached information about a directory. - */ -@Serializable -data class CachedDirectory( - val modifiedDate: Long, - val children: List -) - -/** - * Structure for serializing/deserializing the entire cache. - */ -@Serializable -data class CacheData( - val schemaVersion: String, - val entries: Map -) \ No newline at end of file From baf63b60a00858026c87a525ab2baf3303e4fb94 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Mon, 12 May 2025 11:32:52 -0600 Subject: [PATCH 15/38] musikr.fs: fully encode dir structure Previous children did not include subdirectories due to difficulties in recursive async queries, now they are included at the cost children also being asyncronously populated. --- .../org/oxycblt/musikr/covers/fs/FSCovers.kt | 1 + .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 102 ++++++++++-------- .../musikr/fs/device/DeviceFSEntries.kt | 2 +- 3 files changed, 58 insertions(+), 47 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt index 96f969fad..bda94df6a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt @@ -99,6 +99,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers { val parent = file.parent.await() val bestCover = parent.children + .await() .filterIsInstance() .map { it to coverArtScore(it) } .maxBy { it.second } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index a6831cc71..370a9ffc6 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -50,11 +50,13 @@ private class DeviceFSImpl( ) : DeviceFS { override fun explore(locations: Flow): Flow = locations.flatMapMerge { location -> - exploreDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null) + val (_, query) = + exploreDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null) + query } private fun exploreDirectoryImpl( @@ -62,57 +64,65 @@ private class DeviceFSImpl( treeDocumentId: String, relativePath: Path, parent: Deferred? - ): Flow = flow { + ): Pair> { // Make a kotlin future val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) val directoryDeferred = CompletableDeferred() - val recursive = mutableListOf>() - val children = mutableListOf() - contentResolver.useQuery(uri, PROJECTION) { cursor -> - val childUriIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + val childrenDeferred = CompletableDeferred>() + val dir = DeviceDirectory(uri, relativePath, parent, childrenDeferred) + val query = flow { + val recursive = mutableListOf>() + val children = mutableListOf() + contentResolver.useQuery(uri, PROJECTION) { cursor -> + val childUriIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - while (cursor.moveToNext()) { - val childId = cursor.getString(childUriIndex) - val displayName = cursor.getString(displayNameIndex) + while (cursor.moveToNext()) { + val childId = cursor.getString(childUriIndex) + val displayName = cursor.getString(displayNameIndex) - // Skip hidden files/directories if ignoreHidden is true - if (!withHidden && displayName.startsWith(".")) { - continue - } + // Skip hidden files/directories if ignoreHidden is true + if (!withHidden && displayName.startsWith(".")) { + continue + } - val newPath = relativePath.file(displayName) - val mimeType = cursor.getString(mimeTypeIndex) - val lastModified = cursor.getLong(lastModifiedIndex) + val newPath = relativePath.file(displayName) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) - if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) - } else { - val size = cursor.getLong(sizeIndex) - val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) - val file = - DeviceFile( - uri = childUri, - mimeType = mimeType, - path = newPath, - size = size, - modifiedMs = lastModified, - parent = directoryDeferred) - children.add(file) - emit(file) + if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + val (dir, query) = + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) + children.add(dir) + recursive.add(query) + } else { + val size = cursor.getLong(sizeIndex) + val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) + val file = + DeviceFile( + uri = childUri, + mimeType = mimeType, + path = newPath, + size = size, + modifiedMs = lastModified, + parent = directoryDeferred) + children.add(file) + emit(file) + } } + childrenDeferred.complete(children) + directoryDeferred.complete(dir) + emitAll(recursive.asFlow().flattenMerge()) } - directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children)) - emitAll(recursive.asFlow().flattenMerge()) } + return dir to query } private companion object { diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index dc43e8dab..167f19994 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -31,7 +31,7 @@ data class DeviceDirectory( override val uri: Uri, override val path: Path, val parent: Deferred?, - var children: List + var children: Deferred> ) : DeviceFSEntry data class DeviceFile( From e3fe7c433df5950dd8250440699f41c8c52bf871 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Tue, 13 May 2025 17:11:22 -0600 Subject: [PATCH 16/38] Revert "musikr.fs: fully encode dir structure" This reverts commit baf63b60a00858026c87a525ab2baf3303e4fb94. --- .../org/oxycblt/musikr/covers/fs/FSCovers.kt | 1 - .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 102 ++++++++---------- .../musikr/fs/device/DeviceFSEntries.kt | 2 +- 3 files changed, 47 insertions(+), 58 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt index bda94df6a..96f969fad 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt @@ -99,7 +99,6 @@ class MutableFSCovers(private val context: Context) : MutableCovers { val parent = file.parent.await() val bestCover = parent.children - .await() .filterIsInstance() .map { it to coverArtScore(it) } .maxBy { it.second } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 370a9ffc6..a6831cc71 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -50,13 +50,11 @@ private class DeviceFSImpl( ) : DeviceFS { override fun explore(locations: Flow): Flow = locations.flatMapMerge { location -> - val (_, query) = - exploreDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null) - query + exploreDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null) } private fun exploreDirectoryImpl( @@ -64,65 +62,57 @@ private class DeviceFSImpl( treeDocumentId: String, relativePath: Path, parent: Deferred? - ): Pair> { + ): Flow = flow { // Make a kotlin future val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) val directoryDeferred = CompletableDeferred() - val childrenDeferred = CompletableDeferred>() - val dir = DeviceDirectory(uri, relativePath, parent, childrenDeferred) - val query = flow { - val recursive = mutableListOf>() - val children = mutableListOf() - contentResolver.useQuery(uri, PROJECTION) { cursor -> - val childUriIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + val recursive = mutableListOf>() + val children = mutableListOf() + contentResolver.useQuery(uri, PROJECTION) { cursor -> + val childUriIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - while (cursor.moveToNext()) { - val childId = cursor.getString(childUriIndex) - val displayName = cursor.getString(displayNameIndex) + while (cursor.moveToNext()) { + val childId = cursor.getString(childUriIndex) + val displayName = cursor.getString(displayNameIndex) - // Skip hidden files/directories if ignoreHidden is true - if (!withHidden && displayName.startsWith(".")) { - continue - } + // Skip hidden files/directories if ignoreHidden is true + if (!withHidden && displayName.startsWith(".")) { + continue + } - val newPath = relativePath.file(displayName) - val mimeType = cursor.getString(mimeTypeIndex) - val lastModified = cursor.getLong(lastModifiedIndex) + val newPath = relativePath.file(displayName) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) - if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - val (dir, query) = - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) - children.add(dir) - recursive.add(query) - } else { - val size = cursor.getLong(sizeIndex) - val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) - val file = - DeviceFile( - uri = childUri, - mimeType = mimeType, - path = newPath, - size = size, - modifiedMs = lastModified, - parent = directoryDeferred) - children.add(file) - emit(file) - } + if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + recursive.add( + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + } else { + val size = cursor.getLong(sizeIndex) + val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) + val file = + DeviceFile( + uri = childUri, + mimeType = mimeType, + path = newPath, + size = size, + modifiedMs = lastModified, + parent = directoryDeferred) + children.add(file) + emit(file) } - childrenDeferred.complete(children) - directoryDeferred.complete(dir) - emitAll(recursive.asFlow().flattenMerge()) } + directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children)) + emitAll(recursive.asFlow().flattenMerge()) } - return dir to query } private companion object { diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index 167f19994..dc43e8dab 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -31,7 +31,7 @@ data class DeviceDirectory( override val uri: Uri, override val path: Path, val parent: Deferred?, - var children: Deferred> + var children: List ) : DeviceFSEntry data class DeviceFile( From 6905b51e6652dc49bda7f6cb9c70ef27dbc83c91 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Tue, 13 May 2025 19:45:04 -0600 Subject: [PATCH 17/38] musikr: introduce streaming file tree Probably the best way I can go about this. --- .../org/oxycblt/musikr/covers/fs/FSCovers.kt | 10 ++- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 86 ++++++++++++------- .../musikr/fs/device/DeviceFSEntries.kt | 24 ++++-- .../oxycblt/musikr/fs/device/FiniteHotFlow.kt | 31 +++++++ .../oxycblt/musikr/pipeline/ExploreStep.kt | 9 +- 5 files changed, 117 insertions(+), 43 deletions(-) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/FiniteHotFlow.kt diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt index 96f969fad..e194cd9b1 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt @@ -25,6 +25,9 @@ import android.os.ParcelFileDescriptor import androidx.core.net.toUri import java.io.InputStream import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.filterIsInstance +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.toList import kotlinx.coroutines.withContext import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult @@ -96,11 +99,12 @@ class MutableFSCovers(private val context: Context) : MutableCovers { override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult { // Since DeviceFiles is a streaming API, we have to wait for the current recursive // query to finally finish to be able to have a complete list of siblings to search for. - val parent = file.parent.await() + val parent = file.parent val bestCover = - parent.children + parent.children.flow() .filterIsInstance() .map { it to coverArtScore(it) } + .toList() .maxBy { it.second } if (bestCover.second > 0) { return CoverResult.Hit(FolderCoverImpl(context, bestCover.first.uri)) @@ -128,7 +132,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers { // See if the name contains any of the preferred cover names. This helps weed out // images that are not actually cover art and are just there., var score = - (preferredCoverNames + requireNotNull(file.parent.await().path.name)) + (preferredCoverNames + requireNotNull(file.parent.path.name)) .withIndex() .filter { name.contains(it.value, ignoreCase = true) } .sumOf { it.index + 1 } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index a6831cc71..6b99e245e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device import android.content.ContentResolver @@ -23,19 +23,23 @@ import android.content.Context import android.net.Uri import android.provider.DocumentsContract import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path internal interface DeviceFS { - fun explore(locations: Flow): Flow + fun explore(locations: Flow): Flow companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = @@ -48,27 +52,39 @@ private class DeviceFSImpl( private val contentResolver: ContentResolver, private val withHidden: Boolean ) : DeviceFS { - override fun explore(locations: Flow): Flow = - locations.flatMapMerge { location -> - exploreDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null) + override fun explore(locations: Flow): Flow = + locations.map { location -> + coroutineScope { + DeviceDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null, + coroutineScope = CoroutineScope(Dispatchers.IO), + contentResolver = contentResolver, + withHidden = withHidden + ) + } } +} - private fun exploreDirectoryImpl( - rootUri: Uri, - treeDocumentId: String, - relativePath: Path, - parent: Deferred? - ): Flow = flow { - // Make a kotlin future - val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) - val directoryDeferred = CompletableDeferred() - val recursive = mutableListOf>() - val children = mutableListOf() - contentResolver.useQuery(uri, PROJECTION) { cursor -> +private class DeviceDirectoryImpl( + rootUri: Uri, + treeDocumentId: String, + override val path: Path, + override val parent: DeviceDirectoryImpl?, + coroutineScope: CoroutineScope, + contentResolver: ContentResolver, + withHidden: Boolean +) : DeviceDirectory { + override val uri: Uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) + override val children = FiniteHotFlow(coroutineScope) { emit -> + contentResolver.useQuery( + DocumentsContract.buildChildDocumentsUriUsingTree( + rootUri, + treeDocumentId + ), PROJECTION + ) { cursor -> val childUriIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) val displayNameIndex = @@ -88,13 +104,22 @@ private class DeviceFSImpl( continue } - val newPath = relativePath.file(displayName) + val newPath = path.file(displayName) val mimeType = cursor.getString(mimeTypeIndex) val lastModified = cursor.getLong(lastModifiedIndex) if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + emit( + DeviceDirectoryImpl( + rootUri, + childId, + path = newPath, + parent = this, + coroutineScope, + contentResolver, + withHidden + ) + ) } else { val size = cursor.getLong(sizeIndex) val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) @@ -105,23 +130,24 @@ private class DeviceFSImpl( path = newPath, size = size, modifiedMs = lastModified, - parent = directoryDeferred) - children.add(file) + parent = this + ) emit(file) } } - directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children)) - emitAll(recursive.asFlow().flattenMerge()) } } private companion object { - val PROJECTION = + private val PROJECTION = arrayOf( DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_SIZE, - DocumentsContract.Document.COLUMN_LAST_MODIFIED) + DocumentsContract.Document.COLUMN_LAST_MODIFIED + ) } } + + diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index dc43e8dab..57ba874e8 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -20,6 +20,10 @@ package org.oxycblt.musikr.fs.device import android.net.Uri import kotlinx.coroutines.Deferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flatMapMerge +import kotlinx.coroutines.flow.flowOf import org.oxycblt.musikr.fs.Path sealed interface DeviceFSEntry { @@ -27,12 +31,10 @@ sealed interface DeviceFSEntry { val path: Path } -data class DeviceDirectory( - override val uri: Uri, - override val path: Path, - val parent: Deferred?, - var children: List -) : DeviceFSEntry +interface DeviceDirectory : DeviceFSEntry { + val parent: DeviceDirectory? + val children: FiniteHotFlow +} data class DeviceFile( override val uri: Uri, @@ -40,5 +42,13 @@ data class DeviceFile( val modifiedMs: Long, val mimeType: String, val size: Long, - val parent: Deferred + val parent: DeviceDirectory ) : DeviceFSEntry + +@OptIn(ExperimentalCoroutinesApi::class) +fun DeviceDirectory.flatten(): Flow = children.flow().flatMapMerge { + when (it) { + is DeviceDirectory -> it.flatten() + is DeviceFile -> flowOf(it) + } +} \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FiniteHotFlow.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FiniteHotFlow.kt new file mode 100644 index 000000000..c94e0ea2d --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FiniteHotFlow.kt @@ -0,0 +1,31 @@ +package org.oxycblt.musikr.fs.device + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.FlowCollector +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.shareIn +import kotlinx.coroutines.flow.takeWhile + +class FiniteHotFlow(scope: CoroutineScope, emitter: suspend (emit: suspend (T) -> Unit) -> Unit) { + private sealed interface HotObject { + data class More(val value: T) : HotObject + data object Done : HotObject + } + + private val sharedFlow = flow { + emitter { + emit(HotObject.More(it)) + } + emit(HotObject.Done) + }.shareIn(scope, SharingStarted.Lazily, replay = Int.MAX_VALUE) + + @Suppress("UNCHECKED_CAST") + fun flow() = flow { + sharedFlow.takeWhile { it is HotObject.More<*> }.collect { + emit((it as HotObject.More<*>).value as T) + } + } +} \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 675fd6db9..3561100fc 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -20,12 +20,14 @@ package org.oxycblt.musikr.pipeline import android.content.Context import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map @@ -40,6 +42,7 @@ import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.device.DeviceFS +import org.oxycblt.musikr.fs.device.flatten import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.m3u.M3U @@ -62,13 +65,13 @@ private class ExploreStepImpl( private val covers: Covers, private val storedPlaylists: StoredPlaylists ) : ExploreStep { + @OptIn(ExperimentalCoroutinesApi::class) override fun explore(locations: List): Flow { val addingMs = System.currentTimeMillis() return merge( deviceFS - .explore( - locations.asFlow(), - ) + .explore(locations.asFlow()) + .flatMapMerge { it.flatten() } .filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE } .distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file -> when (val cacheResult = cache.read(file)) { From 3aa56ad5b68c7756f4ff83b48b3885e5a64aaa6f Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Tue, 13 May 2025 19:58:38 -0600 Subject: [PATCH 18/38] musikr.fs: simplify streaming tree impl --- .../main/java/org/oxycblt/musikr/Musikr.kt | 5 +++ .../org/oxycblt/musikr/covers/fs/FSCovers.kt | 2 +- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 27 +++++++++++----- .../musikr/fs/device/DeviceFSEntries.kt | 17 +++++++--- .../oxycblt/musikr/fs/device/FiniteHotFlow.kt | 31 ------------------- 5 files changed, 38 insertions(+), 44 deletions(-) delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/FiniteHotFlow.kt diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 27b84f1f2..29e5ff67f 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -19,6 +19,7 @@ package org.oxycblt.musikr import android.content.Context +import android.util.Log import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.buffer @@ -119,6 +120,7 @@ private class MusikrImpl( locations: List, onProgress: suspend (IndexingProgress) -> Unit ) = coroutineScope { + val start = System.currentTimeMillis() var exploredCount = 0 var extractedCount = 0 val explored = @@ -134,6 +136,9 @@ private class MusikrImpl( .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } .onCompletion { onProgress(IndexingProgress.Indeterminate) } val library = evaluateStep.evaluate(extracted) + Log.d( + "Musikr", + "Loaded ${library.songs.size} songs in ${System.currentTimeMillis() - start}ms") LibraryResultImpl(storage, library) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt index e194cd9b1..480a58d08 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt @@ -101,7 +101,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers { // query to finally finish to be able to have a complete list of siblings to search for. val parent = file.parent val bestCover = - parent.children.flow() + parent.children .filterIsInstance() .map { it to coverArtScore(it) } .toList() diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 6b99e245e..db8fcf383 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -29,14 +29,19 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.shareIn +import kotlinx.coroutines.flow.takeWhile import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path +import org.oxycblt.musikr.fs.device.FiniteHotFlow.HotObject internal interface DeviceFS { fun explore(locations: Flow): Flow @@ -77,8 +82,13 @@ private class DeviceDirectoryImpl( contentResolver: ContentResolver, withHidden: Boolean ) : DeviceDirectory { + private sealed interface HotObject { + data class More(val value: DeviceFSEntry) : HotObject + data object Done : HotObject + } + override val uri: Uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) - override val children = FiniteHotFlow(coroutineScope) { emit -> + override val children = flow { contentResolver.useQuery( DocumentsContract.buildChildDocumentsUriUsingTree( rootUri, @@ -109,17 +119,17 @@ private class DeviceDirectoryImpl( val lastModified = cursor.getLong(lastModifiedIndex) if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - emit( + val dir = DeviceDirectoryImpl( rootUri, childId, path = newPath, - parent = this, + parent = this@DeviceDirectoryImpl, coroutineScope, contentResolver, withHidden ) - ) + emit(HotObject.More(dir)) } else { val size = cursor.getLong(sizeIndex) val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) @@ -130,13 +140,16 @@ private class DeviceDirectoryImpl( path = newPath, size = size, modifiedMs = lastModified, - parent = this + parent = this@DeviceDirectoryImpl ) - emit(file) + emit(HotObject.More(file)) } } + emit(HotObject.Done) } - } + }.shareIn(coroutineScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) + .takeWhile { it is HotObject.More } + .map { (it as HotObject.More).value } private companion object { private val PROJECTION = diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index 57ba874e8..bb8c1160a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -22,7 +22,10 @@ import android.net.Uri import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.asFlow +import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapMerge +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import org.oxycblt.musikr.fs.Path @@ -33,7 +36,7 @@ sealed interface DeviceFSEntry { interface DeviceDirectory : DeviceFSEntry { val parent: DeviceDirectory? - val children: FiniteHotFlow + val children: Flow } data class DeviceFile( @@ -46,9 +49,13 @@ data class DeviceFile( ) : DeviceFSEntry @OptIn(ExperimentalCoroutinesApi::class) -fun DeviceDirectory.flatten(): Flow = children.flow().flatMapMerge { - when (it) { - is DeviceDirectory -> it.flatten() - is DeviceFile -> flowOf(it) +fun DeviceDirectory.flatten(): Flow = flow { + val recursive = mutableListOf>() + children.collect { + when (it) { + is DeviceDirectory -> recursive.add(it.flatten()) + is DeviceFile -> emit(it) + } } + emitAll(recursive.asFlow().flatMapMerge { it }) } \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FiniteHotFlow.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FiniteHotFlow.kt deleted file mode 100644 index c94e0ea2d..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FiniteHotFlow.kt +++ /dev/null @@ -1,31 +0,0 @@ -package org.oxycblt.musikr.fs.device - -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.FlowCollector -import kotlinx.coroutines.flow.SharingStarted -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.shareIn -import kotlinx.coroutines.flow.takeWhile - -class FiniteHotFlow(scope: CoroutineScope, emitter: suspend (emit: suspend (T) -> Unit) -> Unit) { - private sealed interface HotObject { - data class More(val value: T) : HotObject - data object Done : HotObject - } - - private val sharedFlow = flow { - emitter { - emit(HotObject.More(it)) - } - emit(HotObject.Done) - }.shareIn(scope, SharingStarted.Lazily, replay = Int.MAX_VALUE) - - @Suppress("UNCHECKED_CAST") - fun flow() = flow { - sharedFlow.takeWhile { it is HotObject.More<*> }.collect { - emit((it as HotObject.More<*>).value as T) - } - } -} \ No newline at end of file From 84cf0bf29f4260f6ee880bae5d68f27b53bfbdcd Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Tue, 13 May 2025 20:22:26 -0600 Subject: [PATCH 19/38] musikr: further streamline tree query --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 209 ++++++++++-------- .../musikr/fs/device/DeviceFSEntries.kt | 3 +- 2 files changed, 116 insertions(+), 96 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index db8fcf383..6b67bbe42 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -22,26 +22,21 @@ import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract -import kotlinx.coroutines.CompletableDeferred +import android.util.Log import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted -import kotlinx.coroutines.flow.asFlow -import kotlinx.coroutines.flow.emitAll -import kotlinx.coroutines.flow.filterIsInstance -import kotlinx.coroutines.flow.flatMapMerge -import kotlinx.coroutines.flow.flattenMerge +import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.takeWhile import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path -import org.oxycblt.musikr.fs.device.FiniteHotFlow.HotObject internal interface DeviceFS { fun explore(locations: Flow): Flow @@ -58,98 +53,113 @@ private class DeviceFSImpl( private val withHidden: Boolean ) : DeviceFS { override fun explore(locations: Flow): Flow = - locations.map { location -> - coroutineScope { - DeviceDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null, - coroutineScope = CoroutineScope(Dispatchers.IO), - contentResolver = contentResolver, - withHidden = withHidden - ) + locations.mapNotNull { location -> + val treeDocumentId = + DocumentsContract.getTreeDocumentId(location.uri) + val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId) + val modifiedMs = contentResolver.useQuery( + uri, + arrayOf(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + ) { cursor -> + if (!cursor.moveToFirst()) return@useQuery null + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + cursor.getLong(lastModifiedIndex) } + if (modifiedMs == null) { + return@mapNotNull null + } + query( + location.uri, + treeDocumentId, + location.path, + 0, + null + ) } -} -private class DeviceDirectoryImpl( - rootUri: Uri, - treeDocumentId: String, - override val path: Path, - override val parent: DeviceDirectoryImpl?, - coroutineScope: CoroutineScope, - contentResolver: ContentResolver, - withHidden: Boolean -) : DeviceDirectory { - private sealed interface HotObject { - data class More(val value: DeviceFSEntry) : HotObject - data object Done : HotObject + private suspend fun query( + rootUri: Uri, + treeDocumentId: String, + path: Path, + modifiedMs: Long, + parent: DeviceDirectory?, + ): DeviceDirectory = coroutineScope { + val dir = DeviceDirectoryImpl( + uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId), + path = path, + modifiedMs = modifiedMs, + parent = parent, + children = emptyFlow() + ) + dir.children = flow { + Log.d("DeviceFS", "Finished querying $path") + contentResolver.useQuery( + DocumentsContract.buildChildDocumentsUriUsingTree( + rootUri, + treeDocumentId + ), PROJECTION + ) { cursor -> + val childUriIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + while (cursor.moveToNext()) { + val childId = cursor.getString(childUriIndex) + val displayName = cursor.getString(displayNameIndex) + + // Skip hidden files/directories if ignoreHidden is true + if (!withHidden && displayName.startsWith(".")) { + continue + } + + val newPath = path.file(displayName) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + val subdir = + query( + rootUri = rootUri, + treeDocumentId = childId, + path = newPath, + modifiedMs = modifiedMs, + parent = dir + ) + emit(StreamedFile.More(subdir)) + } else { + val size = cursor.getLong(sizeIndex) + val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) + val file = + DeviceFile( + uri = childUri, + mimeType = mimeType, + path = newPath, + size = size, + modifiedMs = lastModified, + parent = dir + ) + emit(StreamedFile.More(file)) + } + } + emit(StreamedFile.Done) + } + }.shareIn(this, SharingStarted.Eagerly, replay = Int.MAX_VALUE) + .takeWhile { it is StreamedFile.More } + .map { (it as StreamedFile.More).value } + dir } - override val uri: Uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) - override val children = flow { - contentResolver.useQuery( - DocumentsContract.buildChildDocumentsUriUsingTree( - rootUri, - treeDocumentId - ), PROJECTION - ) { cursor -> - val childUriIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - - while (cursor.moveToNext()) { - val childId = cursor.getString(childUriIndex) - val displayName = cursor.getString(displayNameIndex) - - // Skip hidden files/directories if ignoreHidden is true - if (!withHidden && displayName.startsWith(".")) { - continue - } - - val newPath = path.file(displayName) - val mimeType = cursor.getString(mimeTypeIndex) - val lastModified = cursor.getLong(lastModifiedIndex) - - if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - val dir = - DeviceDirectoryImpl( - rootUri, - childId, - path = newPath, - parent = this@DeviceDirectoryImpl, - coroutineScope, - contentResolver, - withHidden - ) - emit(HotObject.More(dir)) - } else { - val size = cursor.getLong(sizeIndex) - val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) - val file = - DeviceFile( - uri = childUri, - mimeType = mimeType, - path = newPath, - size = size, - modifiedMs = lastModified, - parent = this@DeviceDirectoryImpl - ) - emit(HotObject.More(file)) - } - } - emit(HotObject.Done) - } - }.shareIn(coroutineScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) - .takeWhile { it is HotObject.More } - .map { (it as HotObject.More).value } + private sealed interface StreamedFile { + data class More(val value: DeviceFSEntry) : StreamedFile + data object Done : StreamedFile + } private companion object { private val PROJECTION = @@ -163,4 +173,13 @@ private class DeviceDirectoryImpl( } } +private class DeviceDirectoryImpl( + override val uri: Uri, + override val path: Path, + override val modifiedMs: Long, + override val parent: DeviceDirectory?, + override var children: Flow, +) : DeviceDirectory + + diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index bb8c1160a..606b3ba64 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -32,6 +32,7 @@ import org.oxycblt.musikr.fs.Path sealed interface DeviceFSEntry { val uri: Uri val path: Path + val modifiedMs: Long } interface DeviceDirectory : DeviceFSEntry { @@ -42,7 +43,7 @@ interface DeviceDirectory : DeviceFSEntry { data class DeviceFile( override val uri: Uri, override val path: Path, - val modifiedMs: Long, + override val modifiedMs: Long, val mimeType: String, val size: Long, val parent: DeviceDirectory From b3f51ea4b79c1998b3c5600c74a4bc57f4ab62e3 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Wed, 14 May 2025 11:07:52 -0600 Subject: [PATCH 20/38] checkpt --- build.gradle | 1 + musikr/build.gradle | 3 + .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 11 ++-- .../oxycblt/musikr/fs/device/FileTreeCache.kt | 59 +++++++++++++++++++ 4 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt diff --git a/build.gradle b/build.gradle index 7bc5b84a9..c62c033d1 100644 --- a/build.gradle +++ b/build.gradle @@ -30,6 +30,7 @@ plugins { //noinspection GradlePluginVersion id 'com.android.library' version "$agp_version" apply false id "org.jetbrains.kotlin.android" version "$kotlin_version" apply false + id "org.jetbrains.kotlin.plugin.serialization" version "$kotlin_version" apply false id "com.google.devtools.ksp" version '2.0.21-1.0.25' apply false // We use spotless in the root build.gradle to apply to all modules. id "com.diffplug.spotless" version "6.25.0" apply true diff --git a/musikr/build.gradle b/musikr/build.gradle index 9e819dcff..31d256899 100644 --- a/musikr/build.gradle +++ b/musikr/build.gradle @@ -4,6 +4,7 @@ plugins { id 'com.android.library' id 'org.jetbrains.kotlin.android' id "com.google.devtools.ksp" + id "org.jetbrains.kotlin.plugin.serialization" id "com.diffplug.spotless" id "kotlin-parcelize" id "org.jetbrains.dokka" @@ -62,6 +63,8 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version" + implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0' + // AndroidX implementation "androidx.core:core-ktx:$core_version" diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 6b67bbe42..eae70db4a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -39,20 +39,21 @@ import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path internal interface DeviceFS { - fun explore(locations: Flow): Flow + suspend fun explore(locations: Flow): Flow companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.contentResolverSafe, withHidden) + DeviceFSImpl(context.contentResolverSafe, JsonFileTreeCache(context), withHidden) } } @OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( private val contentResolver: ContentResolver, + private val cache: FileTreeCache, private val withHidden: Boolean ) : DeviceFS { - override fun explore(locations: Flow): Flow = + override fun explore(locations: Flow): Flow { locations.mapNotNull { location -> val treeDocumentId = DocumentsContract.getTreeDocumentId(location.uri) @@ -73,10 +74,11 @@ private class DeviceFSImpl( location.uri, treeDocumentId, location.path, - 0, + modifiedMs, null ) } + } private suspend fun query( rootUri: Uri, @@ -93,7 +95,6 @@ private class DeviceFSImpl( children = emptyFlow() ) dir.children = flow { - Log.d("DeviceFS", "Finished querying $path") contentResolver.useQuery( DocumentsContract.buildChildDocumentsUriUsingTree( rootUri, diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt new file mode 100644 index 000000000..daf112dee --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2024 Auxio Project + * FileTreeCache.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.fs.device + +import android.content.Context +import android.net.Uri +import android.util.Log +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import java.io.File + +interface FileTreeCache { + suspend fun queryRootDirectory(uri: Uri): CachedRoot + suspend fun updateRootDirectory(uri: Uri, cachedRoot: CachedRoot) + + suspend fun queryDirectory(uri: Uri): CachedDirectory + suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) + + suspend fun queryFile(uri: Uri): CachedFile? + suspend fun updateFile(uri: Uri, file: CachedFile) +} + +data class CachedRoot( + val uri: String, + val path: String, + val modifiedMs: Long, + val childUris: List +) + +data class CachedDirectory( + val uri: String, + val name: String, + val modifiedMs: Long, + val childUris: List +) + +data class CachedFile( + val uri: String, + val name: String, + val modifiedMs: Long, + val mimeType: String, + val size: Long +) From 93c892afed20736a0431b3d67e90279393a61632 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Wed, 14 May 2025 12:06:25 -0600 Subject: [PATCH 21/38] musikr.fs: prototype file tree caching --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 138 ++++++++++++++---- .../oxycblt/musikr/fs/device/FileTreeCache.kt | 134 +++++++++++++++-- .../oxycblt/musikr/pipeline/ExploreStep.kt | 9 +- 3 files changed, 234 insertions(+), 47 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index eae70db4a..8fe3f08d9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -22,62 +22,69 @@ import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract -import android.util.Log -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers +import androidx.core.net.toUri import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull +import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.takeWhile import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path +import org.oxycblt.musikr.fs.path.DocumentPathFactory internal interface DeviceFS { - suspend fun explore(locations: Flow): Flow + fun explore(locations: Flow, fileTree: FileTree): Flow companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.contentResolverSafe, JsonFileTreeCache(context), withHidden) + DeviceFSImpl(context.contentResolverSafe, withHidden) } } @OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( private val contentResolver: ContentResolver, - private val cache: FileTreeCache, private val withHidden: Boolean ) : DeviceFS { - override fun explore(locations: Flow): Flow { + override fun explore(locations: Flow, fileTree: FileTree) = locations.mapNotNull { location -> - val treeDocumentId = - DocumentsContract.getTreeDocumentId(location.uri) - val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId) - val modifiedMs = contentResolver.useQuery( - uri, - arrayOf(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - ) { cursor -> - if (!cursor.moveToFirst()) return@useQuery null - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - cursor.getLong(lastModifiedIndex) - } - if (modifiedMs == null) { - return@mapNotNull null - } - query( - location.uri, - treeDocumentId, - location.path, - modifiedMs, - null - ) + queryRoot(location, fileTree) } + + private suspend fun queryRoot( + location: MusicLocation, + fileTree: FileTree + ): DeviceDirectory? { + val treeDocumentId = + DocumentsContract.getTreeDocumentId(location.uri) + val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId) + val modifiedMs = contentResolver.useQuery( + uri, + arrayOf(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + ) { cursor -> + if (!cursor.moveToFirst()) return@useQuery null + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + cursor.getLong(lastModifiedIndex) + } + if (modifiedMs == null) { + return null + } + return query( + location.uri, + treeDocumentId, + location.path, + modifiedMs, + null, + fileTree + ) } private suspend fun query( @@ -86,9 +93,20 @@ private class DeviceFSImpl( path: Path, modifiedMs: Long, parent: DeviceDirectory?, + fileTree: FileTree ): DeviceDirectory = coroutineScope { + val uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) + val cached = fileTree.queryDirectory(uri) + if (cached != null && cached.modifiedMs == modifiedMs) { + return@coroutineScope hydrateCached( + cached = cached, + parentDir = parent, + path = path, + fileTree = fileTree + ) + } val dir = DeviceDirectoryImpl( - uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId), + uri = uri, path = path, modifiedMs = modifiedMs, parent = parent, @@ -111,6 +129,9 @@ private class DeviceFSImpl( val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + val childSubdirUris = mutableListOf() + val childFileUris = mutableListOf() + while (cursor.moveToNext()) { val childId = cursor.getString(childUriIndex) val displayName = cursor.getString(displayNameIndex) @@ -131,8 +152,10 @@ private class DeviceFSImpl( treeDocumentId = childId, path = newPath, modifiedMs = modifiedMs, - parent = dir + parent = dir, + fileTree = fileTree ) + childSubdirUris.add(subdir.uri.toString()) emit(StreamedFile.More(subdir)) } else { val size = cursor.getLong(sizeIndex) @@ -146,9 +169,26 @@ private class DeviceFSImpl( modifiedMs = lastModified, parent = dir ) + val write = CachedFile( + uri = childUri.toString(), + name = displayName, + modifiedMs = lastModified, + mimeType = mimeType, + size = size + ) + fileTree.updateFile(childUri, write) + childFileUris.add(childUri.toString()) emit(StreamedFile.More(file)) } } + val writeDir = CachedDirectory( + uri = uri.toString(), + name = requireNotNull(path.name), + modifiedMs = modifiedMs, + subdirUris = childSubdirUris, + fileUris = childFileUris + ) + fileTree.updateDirectory(uri, writeDir) emit(StreamedFile.Done) } }.shareIn(this, SharingStarted.Eagerly, replay = Int.MAX_VALUE) @@ -157,6 +197,42 @@ private class DeviceFSImpl( dir } + private fun hydrateCached( + cached: CachedDirectory, + parentDir: DeviceDirectory?, + path: Path, + fileTree: FileTree + ): DeviceDirectory { + val dir = DeviceDirectoryImpl( + uri = cached.uri.toUri(), + path = path, + modifiedMs = cached.modifiedMs, + parent = parentDir, + children = emptyFlow() + ) + dir.children = merge( + cached.subdirUris.asFlow().map { subdirUriString -> + val subdirUri = subdirUriString.toUri() + val cachedSubdir = requireNotNull(fileTree.queryDirectory(subdirUri)) { + "No cached subdir for $subdirUri, malformed cache! Rescan needed." + } + hydrateCached(cachedSubdir, dir, dir.path.file(cachedSubdir.name), fileTree) + }, + cached.fileUris.asFlow().map { + val cachedFile = requireNotNull(fileTree.queryFile(it.toUri())) + DeviceFile( + uri = it.toUri(), + path = dir.path.file(cachedFile.name), + modifiedMs = cachedFile.modifiedMs, + mimeType = cachedFile.mimeType, + size = cachedFile.size, + parent = dir + ) + } + ) + return dir + } + private sealed interface StreamedFile { data class More(val value: DeviceFSEntry) : StreamedFile data object Done : StreamedFile diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt index daf112dee..6fde36ee5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt @@ -21,39 +21,143 @@ package org.oxycblt.musikr.fs.device import android.content.Context import android.net.Uri import android.util.Log +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.encodeToString import java.io.File interface FileTreeCache { - suspend fun queryRootDirectory(uri: Uri): CachedRoot - suspend fun updateRootDirectory(uri: Uri, cachedRoot: CachedRoot) + fun read(): FileTree +} - suspend fun queryDirectory(uri: Uri): CachedDirectory +interface FileTree { + suspend fun queryDirectory(uri: Uri): CachedDirectory? suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) suspend fun queryFile(uri: Uri): CachedFile? suspend fun updateFile(uri: Uri, file: CachedFile) + + suspend fun write() } -data class CachedRoot( - val uri: String, - val path: String, - val modifiedMs: Long, - val childUris: List -) +// Define the sealed interface +@Serializable +sealed interface FileSystemEntry { + val uri: String + val modifiedMs: Long +} +@Serializable data class CachedDirectory( - val uri: String, + override val uri: String, val name: String, - val modifiedMs: Long, - val childUris: List -) + override val modifiedMs: Long, + val subdirUris: List, + val fileUris: List +) : FileSystemEntry +@Serializable data class CachedFile( - val uri: String, + override val uri: String, val name: String, - val modifiedMs: Long, + override val modifiedMs: Long, val mimeType: String, val size: Long +) : FileSystemEntry + +@Serializable +data class FileTreeData( + val directories: Map = mapOf(), + val files: Map = mapOf() ) + +class FileTreeCacheImpl(private val context: Context) : FileTreeCache { + companion object { + private const val TAG = "FileTreeCache" + private const val CACHE_FILENAME = "file_tree_cache.json" + private val json = Json { + ignoreUnknownKeys = true + prettyPrint = true + } + } + + override fun read(): FileTree { + val cacheFile = File(context.cacheDir, CACHE_FILENAME) + + return if (cacheFile.exists()) { + try { + val jsonContent = cacheFile.readText() + val fileTreeCache = json.decodeFromString(jsonContent) + FileTreeImpl(context, fileTreeCache.directories.toMutableMap(), fileTreeCache.files.toMutableMap()) + } catch (e: Exception) { + Log.e(TAG, "Failed to read cache file", e) + FileTreeImpl(context, mutableMapOf(), mutableMapOf()) + } + } else { + Log.i(TAG, "Cache file does not exist, creating new FileTree") + FileTreeImpl(context, mutableMapOf(), mutableMapOf()) + } + } +} + +class FileTreeImpl( + private val context: Context, + private val mutableDirectories: MutableMap = mutableMapOf(), + private val mutableFiles: MutableMap = mutableMapOf() +) : FileTree { + companion object { + private const val TAG = "FileTree" + private const val CACHE_FILENAME = "file_tree_cache.json" + private val json = Json { + ignoreUnknownKeys = true + prettyPrint = true + } + } + + // Directory operations + override suspend fun queryDirectory(uri: Uri): CachedDirectory? { + Log.d("FileTreeCache", "Querying directory: $uri ${mutableDirectories[uri.toString()]}") + val uriString = uri.toString() + return mutableDirectories[uriString] + } + + override suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) { + Log.d("FileTreeCache", "Updating directory: $uri") + val uriString = uri.toString() + mutableDirectories[uriString] = directory + } + + // File operations + override suspend fun queryFile(uri: Uri): CachedFile? { + Log.d("FileTreeCache", "Querying file: $uri") + val uriString = uri.toString() + return mutableFiles[uriString] + } + + override suspend fun updateFile(uri: Uri, file: CachedFile) { + Log.d("FileTreeCache", "Updating file: $uri") + val uriString = uri.toString() + mutableFiles[uriString] = file + } + + override suspend fun write() = withContext(Dispatchers.IO) { + Log.d(TAG, "Writing cache to disk") + val cacheFile = File(context.cacheDir, CACHE_FILENAME) + try { + val fileTreeCache = FileTreeData( + directories = mutableDirectories.toMap(), + files = mutableFiles.toMap() + ) + + val jsonContent = json.encodeToString(fileTreeCache) + cacheFile.writeText(jsonContent) + Log.d(TAG, "Successfully wrote cache to disk") + } catch (e: Exception) { + Log.e(TAG, "Failed to write cache file", e) + } + Unit + } +} diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 3561100fc..7cb5d2f10 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -32,6 +32,7 @@ import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge +import kotlinx.coroutines.flow.onCompletion import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Storage import org.oxycblt.musikr.cache.Cache @@ -42,6 +43,8 @@ import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.device.DeviceFS +import org.oxycblt.musikr.fs.device.FileTreeCache +import org.oxycblt.musikr.fs.device.FileTreeCacheImpl import org.oxycblt.musikr.fs.device.flatten import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.m3u.M3U @@ -55,6 +58,7 @@ internal interface ExploreStep { DeviceFS.from(context, interpretation.withHidden), storage.cache, storage.covers, + FileTreeCacheImpl(context), storage.storedPlaylists) } } @@ -63,15 +67,18 @@ private class ExploreStepImpl( private val deviceFS: DeviceFS, private val cache: Cache, private val covers: Covers, + private val fileTreeCache: FileTreeCache, private val storedPlaylists: StoredPlaylists ) : ExploreStep { @OptIn(ExperimentalCoroutinesApi::class) override fun explore(locations: List): Flow { val addingMs = System.currentTimeMillis() + val fileTree = fileTreeCache.read() return merge( deviceFS - .explore(locations.asFlow()) + .explore(locations.asFlow(), fileTree) .flatMapMerge { it.flatten() } + .onCompletion { fileTree.write() } .filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE } .distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file -> when (val cacheResult = cache.read(file)) { From ab906ce2866a2a1e85eb404cf11b26fadf83d892 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Wed, 14 May 2025 22:18:01 -0600 Subject: [PATCH 22/38] musikr.fs: optimize file tree exploration --- .../main/java/org/oxycblt/musikr/Musikr.kt | 4 +- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 73 ++++++++++++------- .../musikr/fs/device/DeviceFSEntries.kt | 12 +-- .../org/oxycblt/musikr/fs/device/QueryUtil.kt | 8 +- 4 files changed, 58 insertions(+), 39 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 29e5ff67f..627694385 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -128,7 +128,9 @@ private class MusikrImpl( .explore(locations) .buffer(Channel.UNLIMITED) .onStart { onProgress(IndexingProgress.Songs(0, 0)) } - .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } + .onEach { + onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) + } val extracted = extractStep .extract(explored) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 8fe3f08d9..b74800e32 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -22,14 +22,20 @@ import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract +import android.util.Log import androidx.core.net.toUri +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asFlow +import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.merge @@ -48,11 +54,11 @@ internal interface DeviceFS { } } -@OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( private val contentResolver: ContentResolver, private val withHidden: Boolean ) : DeviceFS { + private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) override fun explore(locations: Flow, fileTree: FileTree) = locations.mapNotNull { location -> queryRoot(location, fileTree) @@ -113,11 +119,12 @@ private class DeviceFSImpl( children = emptyFlow() ) dir.children = flow { + Log.d("DeviceFS", "Querying $uri") contentResolver.useQuery( DocumentsContract.buildChildDocumentsUriUsingTree( rootUri, - treeDocumentId - ), PROJECTION + treeDocumentId, + ), projection = PROJECTION, sortOrder = "${DocumentsContract.Document.COLUMN_DISPLAY_NAME} DESC" ) { cursor -> val childUriIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) @@ -132,6 +139,8 @@ private class DeviceFSImpl( val childSubdirUris = mutableListOf() val childFileUris = mutableListOf() + val subqueries = mutableListOf() + while (cursor.moveToNext()) { val childId = cursor.getString(childUriIndex) val displayName = cursor.getString(displayNameIndex) @@ -158,6 +167,7 @@ private class DeviceFSImpl( childSubdirUris.add(subdir.uri.toString()) emit(StreamedFile.More(subdir)) } else { + Log.d("DeviceFS", "Querying file $childId") val size = cursor.getLong(sizeIndex) val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) val file = @@ -191,18 +201,18 @@ private class DeviceFSImpl( fileTree.updateDirectory(uri, writeDir) emit(StreamedFile.Done) } - }.shareIn(this, SharingStarted.Eagerly, replay = Int.MAX_VALUE) + }.shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) .takeWhile { it is StreamedFile.More } .map { (it as StreamedFile.More).value } dir } - private fun hydrateCached( + private suspend fun hydrateCached( cached: CachedDirectory, parentDir: DeviceDirectory?, path: Path, fileTree: FileTree - ): DeviceDirectory { + ): DeviceDirectory = coroutineScope { val dir = DeviceDirectoryImpl( uri = cached.uri.toUri(), path = path, @@ -210,27 +220,36 @@ private class DeviceFSImpl( parent = parentDir, children = emptyFlow() ) - dir.children = merge( - cached.subdirUris.asFlow().map { subdirUriString -> - val subdirUri = subdirUriString.toUri() - val cachedSubdir = requireNotNull(fileTree.queryDirectory(subdirUri)) { - "No cached subdir for $subdirUri, malformed cache! Rescan needed." - } - hydrateCached(cachedSubdir, dir, dir.path.file(cachedSubdir.name), fileTree) - }, - cached.fileUris.asFlow().map { - val cachedFile = requireNotNull(fileTree.queryFile(it.toUri())) - DeviceFile( - uri = it.toUri(), - path = dir.path.file(cachedFile.name), - modifiedMs = cachedFile.modifiedMs, - mimeType = cachedFile.mimeType, - size = cachedFile.size, - parent = dir - ) - } - ) - return dir + dir.children = flow { + emitAll( + merge( + cached.subdirUris.asFlow().map { subdirUriString -> + val subdirUri = subdirUriString.toUri() + val cachedSubdir = requireNotNull(fileTree.queryDirectory(subdirUri)) { + "No cached subdir for $subdirUri, malformed cache! Rescan needed." + } + hydrateCached(cachedSubdir, dir, dir.path.file(cachedSubdir.name), fileTree) + }, + cached.fileUris.asFlow().map { + val cachedFile = requireNotNull(fileTree.queryFile(it.toUri())) + DeviceFile( + uri = it.toUri(), + path = dir.path.file(cachedFile.name), + modifiedMs = cachedFile.modifiedMs, + mimeType = cachedFile.mimeType, + size = cachedFile.size, + parent = dir + ) + } + ).map { StreamedFile.More(it) } + ) + emit(StreamedFile.Done) + } + .flowOn(Dispatchers.IO) + .shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) + .takeWhile { it is StreamedFile.More } + .map { (it as StreamedFile.More).value } + dir } private sealed interface StreamedFile { diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index 606b3ba64..7e4ab954b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -27,6 +27,7 @@ import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.transform import org.oxycblt.musikr.fs.Path sealed interface DeviceFSEntry { @@ -49,14 +50,9 @@ data class DeviceFile( val parent: DeviceDirectory ) : DeviceFSEntry -@OptIn(ExperimentalCoroutinesApi::class) -fun DeviceDirectory.flatten(): Flow = flow { - val recursive = mutableListOf>() - children.collect { +fun DeviceDirectory.flatten(): Flow = children.transform { when (it) { - is DeviceDirectory -> recursive.add(it.flatten()) + is DeviceDirectory -> emitAll(it.flatten()) is DeviceFile -> emit(it) } - } - emitAll(recursive.asFlow().flatMapMerge { it }) -} \ No newline at end of file + } \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt index a305108d6..57e483c98 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt @@ -46,8 +46,9 @@ internal fun ContentResolver.safeQuery( uri: Uri, projection: Array, selector: String? = null, - args: Array? = null -) = requireNotNull(query(uri, projection, selector, args, null)) { "ContentResolver query failed" } + args: Array? = null, + sortOrder: String? = null +) = requireNotNull(query(uri, projection, selector, args, sortOrder)) { "ContentResolver query failed" } /** * A shortcut for [safeQuery] with [use] applied, automatically cleaning up the [Cursor]'s resources @@ -68,5 +69,6 @@ internal inline fun ContentResolver.useQuery( projection: Array, selector: String? = null, args: Array? = null, + sortOrder: String? = null, block: (Cursor) -> R -) = safeQuery(uri, projection, selector, args).use(block) +) = safeQuery(uri, projection, selector, args, sortOrder).use(block) From 22d43e58493f9c1f1aecbe7c4af2aad81db3878e Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 15 May 2025 16:59:21 -0600 Subject: [PATCH 23/38] musikr.cache: bulk read cache into memory I didn't want to do this, but it's just faster than before. --- .../oxycblt/musikr/cache/db/CacheDatabase.kt | 2 ++ .../java/org/oxycblt/musikr/cache/db/DBCache.kt | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt index 9386322e4..c760de2a2 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt @@ -55,6 +55,8 @@ internal abstract class CacheDatabase : RoomDatabase() { internal interface CacheReadDao { @Query("SELECT * FROM CachedSongData WHERE uri = :uri") suspend fun selectSong(uri: String): CachedSongData? + + @Query("SELECT * FROM CachedSongData") suspend fun selectAllSongs(): List } @Dao diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt index 6835dd40b..4bd301c5b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt @@ -19,6 +19,9 @@ package org.oxycblt.musikr.cache.db import android.content.Context +import android.net.Uri +import android.util.Log +import kotlinx.coroutines.sync.Mutex import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.CacheResult import org.oxycblt.musikr.cache.CachedSong @@ -33,8 +36,20 @@ import org.oxycblt.musikr.tag.parse.ParsedTags * Create an instance with [from]. */ class DBCache private constructor(private val readDao: CacheReadDao) : Cache { + @Volatile private var mapping: MutableMap? = null + private var mappingLock = Mutex() + override suspend fun read(file: DeviceFile): CacheResult { - val dbSong = readDao.selectSong(file.uri.toString()) ?: return CacheResult.Miss(file) + mappingLock.lock() + val mapping = + this.mapping + ?: readDao + .selectAllSongs() + .associateBy { it.uri } + .toMutableMap() + .also { mapping = it } + mappingLock.unlock() + val dbSong = mapping[file.uri] ?: return CacheResult.Miss(file) if (dbSong.modifiedMs != file.modifiedMs) { return CacheResult.Stale(file, dbSong.addedMs) } From ec4d003af8c469faf09b0eb61924b0f34ac121a8 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 15 May 2025 17:00:36 -0600 Subject: [PATCH 24/38] all: reformat --- .../main/java/org/oxycblt/musikr/Musikr.kt | 4 +- .../org/oxycblt/musikr/cache/db/DBCache.kt | 1 - .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 316 +++++++++--------- .../musikr/fs/device/DeviceFSEntries.kt | 11 +- .../oxycblt/musikr/fs/device/FileTreeCache.kt | 61 ++-- .../org/oxycblt/musikr/fs/device/QueryUtil.kt | 5 +- 6 files changed, 195 insertions(+), 203 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 627694385..29e5ff67f 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -128,9 +128,7 @@ private class MusikrImpl( .explore(locations) .buffer(Channel.UNLIMITED) .onStart { onProgress(IndexingProgress.Songs(0, 0)) } - .onEach { - onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) - } + .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } val extracted = extractStep .extract(explored) diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt index 4bd301c5b..572f6bdd3 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt @@ -20,7 +20,6 @@ package org.oxycblt.musikr.cache.db import android.content.Context import android.net.Uri -import android.util.Log import kotlinx.coroutines.sync.Mutex import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.CacheResult diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index b74800e32..c0c27f5ae 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device import android.content.ContentResolver @@ -26,7 +26,6 @@ import android.util.Log import androidx.core.net.toUri import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow @@ -43,7 +42,6 @@ import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.takeWhile import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path -import org.oxycblt.musikr.fs.path.DocumentPathFactory internal interface DeviceFS { fun explore(locations: Flow, fileTree: FileTree): Flow @@ -59,38 +57,26 @@ private class DeviceFSImpl( private val withHidden: Boolean ) : DeviceFS { private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) - override fun explore(locations: Flow, fileTree: FileTree) = - locations.mapNotNull { location -> - queryRoot(location, fileTree) - } - private suspend fun queryRoot( - location: MusicLocation, - fileTree: FileTree - ): DeviceDirectory? { - val treeDocumentId = - DocumentsContract.getTreeDocumentId(location.uri) + override fun explore(locations: Flow, fileTree: FileTree) = + locations.mapNotNull { location -> queryRoot(location, fileTree) } + + private suspend fun queryRoot(location: MusicLocation, fileTree: FileTree): DeviceDirectory? { + val treeDocumentId = DocumentsContract.getTreeDocumentId(location.uri) val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId) - val modifiedMs = contentResolver.useQuery( - uri, - arrayOf(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - ) { cursor -> - if (!cursor.moveToFirst()) return@useQuery null - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - cursor.getLong(lastModifiedIndex) - } + val modifiedMs = + contentResolver.useQuery( + uri, arrayOf(DocumentsContract.Document.COLUMN_LAST_MODIFIED)) { cursor -> + if (!cursor.moveToFirst()) return@useQuery null + val lastModifiedIndex = + cursor.getColumnIndexOrThrow( + DocumentsContract.Document.COLUMN_LAST_MODIFIED) + cursor.getLong(lastModifiedIndex) + } if (modifiedMs == null) { return null } - return query( - location.uri, - treeDocumentId, - location.path, - modifiedMs, - null, - fileTree - ) + return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree) } private suspend fun query( @@ -105,105 +91,110 @@ private class DeviceFSImpl( val cached = fileTree.queryDirectory(uri) if (cached != null && cached.modifiedMs == modifiedMs) { return@coroutineScope hydrateCached( - cached = cached, - parentDir = parent, - path = path, - fileTree = fileTree - ) + cached = cached, parentDir = parent, path = path, fileTree = fileTree) } - val dir = DeviceDirectoryImpl( - uri = uri, - path = path, - modifiedMs = modifiedMs, - parent = parent, - children = emptyFlow() - ) - dir.children = flow { - Log.d("DeviceFS", "Querying $uri") - contentResolver.useQuery( - DocumentsContract.buildChildDocumentsUriUsingTree( - rootUri, - treeDocumentId, - ), projection = PROJECTION, sortOrder = "${DocumentsContract.Document.COLUMN_DISPLAY_NAME} DESC" - ) { cursor -> - val childUriIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + val dir = + DeviceDirectoryImpl( + uri = uri, + path = path, + modifiedMs = modifiedMs, + parent = parent, + children = emptyFlow()) + dir.children = + flow { + Log.d("DeviceFS", "Querying $uri") + contentResolver.useQuery( + DocumentsContract.buildChildDocumentsUriUsingTree( + rootUri, + treeDocumentId, + ), + projection = PROJECTION, + sortOrder = "${DocumentsContract.Document.COLUMN_DISPLAY_NAME} DESC") { + cursor -> + val childUriIndex = + cursor.getColumnIndexOrThrow( + DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = + cursor.getColumnIndexOrThrow( + DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow( + DocumentsContract.Document.COLUMN_MIME_TYPE) + val sizeIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow( + DocumentsContract.Document.COLUMN_LAST_MODIFIED) - val childSubdirUris = mutableListOf() - val childFileUris = mutableListOf() + val childSubdirUris = mutableListOf() + val childFileUris = mutableListOf() - val subqueries = mutableListOf() + val subqueries = mutableListOf() - while (cursor.moveToNext()) { - val childId = cursor.getString(childUriIndex) - val displayName = cursor.getString(displayNameIndex) + while (cursor.moveToNext()) { + val childId = cursor.getString(childUriIndex) + val displayName = cursor.getString(displayNameIndex) - // Skip hidden files/directories if ignoreHidden is true - if (!withHidden && displayName.startsWith(".")) { - continue - } + // Skip hidden files/directories if ignoreHidden is true + if (!withHidden && displayName.startsWith(".")) { + continue + } - val newPath = path.file(displayName) - val mimeType = cursor.getString(mimeTypeIndex) - val lastModified = cursor.getLong(lastModifiedIndex) + val newPath = path.file(displayName) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) - if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - val subdir = - query( - rootUri = rootUri, - treeDocumentId = childId, - path = newPath, - modifiedMs = modifiedMs, - parent = dir, - fileTree = fileTree - ) - childSubdirUris.add(subdir.uri.toString()) - emit(StreamedFile.More(subdir)) - } else { - Log.d("DeviceFS", "Querying file $childId") - val size = cursor.getLong(sizeIndex) - val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) - val file = - DeviceFile( - uri = childUri, - mimeType = mimeType, - path = newPath, - size = size, - modifiedMs = lastModified, - parent = dir - ) - val write = CachedFile( - uri = childUri.toString(), - name = displayName, - modifiedMs = lastModified, - mimeType = mimeType, - size = size - ) - fileTree.updateFile(childUri, write) - childFileUris.add(childUri.toString()) - emit(StreamedFile.More(file)) - } + if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + val subdir = + query( + rootUri = rootUri, + treeDocumentId = childId, + path = newPath, + modifiedMs = modifiedMs, + parent = dir, + fileTree = fileTree) + childSubdirUris.add(subdir.uri.toString()) + emit(StreamedFile.More(subdir)) + } else { + Log.d("DeviceFS", "Querying file $childId") + val size = cursor.getLong(sizeIndex) + val childUri = + DocumentsContract.buildDocumentUriUsingTree( + rootUri, childId) + val file = + DeviceFile( + uri = childUri, + mimeType = mimeType, + path = newPath, + size = size, + modifiedMs = lastModified, + parent = dir) + val write = + CachedFile( + uri = childUri.toString(), + name = displayName, + modifiedMs = lastModified, + mimeType = mimeType, + size = size) + fileTree.updateFile(childUri, write) + childFileUris.add(childUri.toString()) + emit(StreamedFile.More(file)) + } + } + val writeDir = + CachedDirectory( + uri = uri.toString(), + name = requireNotNull(path.name), + modifiedMs = modifiedMs, + subdirUris = childSubdirUris, + fileUris = childFileUris) + fileTree.updateDirectory(uri, writeDir) + emit(StreamedFile.Done) + } } - val writeDir = CachedDirectory( - uri = uri.toString(), - name = requireNotNull(path.name), - modifiedMs = modifiedMs, - subdirUris = childSubdirUris, - fileUris = childFileUris - ) - fileTree.updateDirectory(uri, writeDir) - emit(StreamedFile.Done) - } - }.shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) - .takeWhile { it is StreamedFile.More } - .map { (it as StreamedFile.More).value } + .shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) + .takeWhile { it is StreamedFile.More } + .map { (it as StreamedFile.More).value } dir } @@ -213,47 +204,52 @@ private class DeviceFSImpl( path: Path, fileTree: FileTree ): DeviceDirectory = coroutineScope { - val dir = DeviceDirectoryImpl( - uri = cached.uri.toUri(), - path = path, - modifiedMs = cached.modifiedMs, - parent = parentDir, - children = emptyFlow() - ) - dir.children = flow { - emitAll( - merge( - cached.subdirUris.asFlow().map { subdirUriString -> - val subdirUri = subdirUriString.toUri() - val cachedSubdir = requireNotNull(fileTree.queryDirectory(subdirUri)) { - "No cached subdir for $subdirUri, malformed cache! Rescan needed." - } - hydrateCached(cachedSubdir, dir, dir.path.file(cachedSubdir.name), fileTree) - }, - cached.fileUris.asFlow().map { - val cachedFile = requireNotNull(fileTree.queryFile(it.toUri())) - DeviceFile( - uri = it.toUri(), - path = dir.path.file(cachedFile.name), - modifiedMs = cachedFile.modifiedMs, - mimeType = cachedFile.mimeType, - size = cachedFile.size, - parent = dir - ) - } - ).map { StreamedFile.More(it) } - ) - emit(StreamedFile.Done) - } - .flowOn(Dispatchers.IO) - .shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) - .takeWhile { it is StreamedFile.More } - .map { (it as StreamedFile.More).value } + val dir = + DeviceDirectoryImpl( + uri = cached.uri.toUri(), + path = path, + modifiedMs = cached.modifiedMs, + parent = parentDir, + children = emptyFlow()) + dir.children = + flow { + emitAll( + merge( + cached.subdirUris.asFlow().map { subdirUriString -> + val subdirUri = subdirUriString.toUri() + val cachedSubdir = + requireNotNull(fileTree.queryDirectory(subdirUri)) { + "No cached subdir for $subdirUri, malformed cache! Rescan needed." + } + hydrateCached( + cachedSubdir, + dir, + dir.path.file(cachedSubdir.name), + fileTree) + }, + cached.fileUris.asFlow().map { + val cachedFile = requireNotNull(fileTree.queryFile(it.toUri())) + DeviceFile( + uri = it.toUri(), + path = dir.path.file(cachedFile.name), + modifiedMs = cachedFile.modifiedMs, + mimeType = cachedFile.mimeType, + size = cachedFile.size, + parent = dir) + }) + .map { StreamedFile.More(it) }) + emit(StreamedFile.Done) + } + .flowOn(Dispatchers.IO) + .shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) + .takeWhile { it is StreamedFile.More } + .map { (it as StreamedFile.More).value } dir } private sealed interface StreamedFile { data class More(val value: DeviceFSEntry) : StreamedFile + data object Done : StreamedFile } @@ -264,8 +260,7 @@ private class DeviceFSImpl( DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_SIZE, - DocumentsContract.Document.COLUMN_LAST_MODIFIED - ) + DocumentsContract.Document.COLUMN_LAST_MODIFIED) } } @@ -276,6 +271,3 @@ private class DeviceDirectoryImpl( override val parent: DeviceDirectory?, override var children: Flow, ) : DeviceDirectory - - - diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index 7e4ab954b..0938fbab3 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -19,14 +19,8 @@ package org.oxycblt.musikr.fs.device import android.net.Uri -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emitAll -import kotlinx.coroutines.flow.flatMapMerge -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.transform import org.oxycblt.musikr.fs.Path @@ -50,9 +44,10 @@ data class DeviceFile( val parent: DeviceDirectory ) : DeviceFSEntry -fun DeviceDirectory.flatten(): Flow = children.transform { +fun DeviceDirectory.flatten(): Flow = + children.transform { when (it) { is DeviceDirectory -> emitAll(it.flatten()) is DeviceFile -> emit(it) } - } \ No newline at end of file + } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt index 6fde36ee5..df2a6acb6 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt @@ -15,19 +15,19 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.musikr.fs.device import android.content.Context import android.net.Uri import android.util.Log +import java.io.File import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString -import java.io.File +import kotlinx.serialization.json.Json interface FileTreeCache { fun read(): FileTree @@ -35,11 +35,13 @@ interface FileTreeCache { interface FileTree { suspend fun queryDirectory(uri: Uri): CachedDirectory? + suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) suspend fun queryFile(uri: Uri): CachedFile? + suspend fun updateFile(uri: Uri, file: CachedFile) - + suspend fun write() } @@ -78,20 +80,23 @@ class FileTreeCacheImpl(private val context: Context) : FileTreeCache { companion object { private const val TAG = "FileTreeCache" private const val CACHE_FILENAME = "file_tree_cache.json" - private val json = Json { - ignoreUnknownKeys = true + private val json = Json { + ignoreUnknownKeys = true prettyPrint = true } } - + override fun read(): FileTree { val cacheFile = File(context.cacheDir, CACHE_FILENAME) - + return if (cacheFile.exists()) { try { val jsonContent = cacheFile.readText() val fileTreeCache = json.decodeFromString(jsonContent) - FileTreeImpl(context, fileTreeCache.directories.toMutableMap(), fileTreeCache.files.toMutableMap()) + FileTreeImpl( + context, + fileTreeCache.directories.toMutableMap(), + fileTreeCache.files.toMutableMap()) } catch (e: Exception) { Log.e(TAG, "Failed to read cache file", e) FileTreeImpl(context, mutableMapOf(), mutableMapOf()) @@ -111,8 +116,8 @@ class FileTreeImpl( companion object { private const val TAG = "FileTree" private const val CACHE_FILENAME = "file_tree_cache.json" - private val json = Json { - ignoreUnknownKeys = true + private val json = Json { + ignoreUnknownKeys = true prettyPrint = true } } @@ -142,22 +147,22 @@ class FileTreeImpl( val uriString = uri.toString() mutableFiles[uriString] = file } - - override suspend fun write() = withContext(Dispatchers.IO) { - Log.d(TAG, "Writing cache to disk") - val cacheFile = File(context.cacheDir, CACHE_FILENAME) - try { - val fileTreeCache = FileTreeData( - directories = mutableDirectories.toMap(), - files = mutableFiles.toMap() - ) - - val jsonContent = json.encodeToString(fileTreeCache) - cacheFile.writeText(jsonContent) - Log.d(TAG, "Successfully wrote cache to disk") - } catch (e: Exception) { - Log.e(TAG, "Failed to write cache file", e) + + override suspend fun write() = + withContext(Dispatchers.IO) { + Log.d(TAG, "Writing cache to disk") + val cacheFile = File(context.cacheDir, CACHE_FILENAME) + try { + val fileTreeCache = + FileTreeData( + directories = mutableDirectories.toMap(), files = mutableFiles.toMap()) + + val jsonContent = json.encodeToString(fileTreeCache) + cacheFile.writeText(jsonContent) + Log.d(TAG, "Successfully wrote cache to disk") + } catch (e: Exception) { + Log.e(TAG, "Failed to write cache file", e) + } + Unit } - Unit - } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt index 57e483c98..a2dfbc041 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt @@ -48,7 +48,10 @@ internal fun ContentResolver.safeQuery( selector: String? = null, args: Array? = null, sortOrder: String? = null -) = requireNotNull(query(uri, projection, selector, args, sortOrder)) { "ContentResolver query failed" } +) = + requireNotNull(query(uri, projection, selector, args, sortOrder)) { + "ContentResolver query failed" + } /** * A shortcut for [safeQuery] with [use] applied, automatically cleaning up the [Cursor]'s resources From d3a35331463837be73e03fe2801c0442b49a400d Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 29 May 2025 19:34:08 -0600 Subject: [PATCH 25/38] music: integrate filetreecache --- .../oxycblt/auxio/music/MusicRepository.kt | 5 +- .../music/shim/WriteOnlyFileTreeCache.kt | 59 +++++++++++++++++++ .../main/java/org/oxycblt/musikr/Config.kt | 8 ++- .../oxycblt/musikr/fs/device/FileTreeCache.kt | 19 +++--- .../oxycblt/musikr/pipeline/ExploreStep.kt | 3 +- 5 files changed, 79 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index 6b478c520..b08a67ca4 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -30,6 +30,7 @@ import kotlinx.coroutines.yield import org.oxycblt.auxio.image.covers.SettingCovers import org.oxycblt.auxio.music.MusicRepository.IndexingWorker import org.oxycblt.auxio.music.shim.WriteOnlyMutableCache +import org.oxycblt.auxio.music.shim.WriteOnlyFileTreeCache import org.oxycblt.musikr.IndexingProgress import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Library @@ -39,6 +40,7 @@ import org.oxycblt.musikr.MutableLibrary import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Song import org.oxycblt.musikr.Storage +import org.oxycblt.musikr.fs.device.FileTreeCache import org.oxycblt.musikr.cache.MutableCache import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.tag.interpret.Naming @@ -391,7 +393,8 @@ constructor( val newRevision = currentRevision?.takeIf { withCache } ?: UUID.randomUUID() val cache = if (withCache) cache else WriteOnlyMutableCache(cache) val covers = settingCovers.mutate(context, newRevision) - val storage = Storage(cache, covers, storedPlaylists) + val fileTreeCache = if (withCache) FileTreeCache.from(context) else WriteOnlyFileTreeCache(FileTreeCache.from(context)) + val storage = Storage(cache, covers, storedPlaylists, fileTreeCache) val interpretation = Interpretation(nameFactory, separators, withHidden) val result = Musikr.new(context, storage, interpretation).run(locations, ::emitIndexingProgress) diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt new file mode 100644 index 000000000..5d24edc53 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Auxio Project + * WriteOnlyFileTreeCache.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.auxio.music.shim + +import android.net.Uri +import org.oxycblt.musikr.fs.device.CachedDirectory +import org.oxycblt.musikr.fs.device.CachedFile +import org.oxycblt.musikr.fs.device.FileTree +import org.oxycblt.musikr.fs.device.FileTreeCache + +class WriteOnlyFileTreeCache(private val inner: FileTreeCache) : FileTreeCache { + override fun read(): FileTree { + val innerTree = inner.read() + return WriteOnlyFileTree(innerTree) + } +} + +class WriteOnlyFileTree(private val innerTree: FileTree) : FileTree { + override suspend fun queryDirectory(uri: Uri): CachedDirectory? { + // Always return null to simulate a cache miss + return null + } + + override suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) { + // Forward update operations to the inner tree + innerTree.updateDirectory(uri, directory) + } + + override suspend fun queryFile(uri: Uri): CachedFile? { + // Always return null to simulate a cache miss + return null + } + + override suspend fun updateFile(uri: Uri, file: CachedFile) { + // Forward update operations to the inner tree + innerTree.updateFile(uri, file) + } + + override suspend fun write() { + // Forward write operations to the inner tree + innerTree.write() + } +} \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/Config.kt b/musikr/src/main/java/org/oxycblt/musikr/Config.kt index df7c5cf07..12061a56c 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Config.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Config.kt @@ -21,6 +21,7 @@ package org.oxycblt.musikr import org.oxycblt.musikr.cache.MutableCache import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.MutableCovers +import org.oxycblt.musikr.fs.device.FileTreeCache import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.tag.interpret.Naming import org.oxycblt.musikr.tag.interpret.Separators @@ -45,7 +46,12 @@ data class Storage( * be used during music loading and mutated when creating, renaming, or deleting playlists in * the library. */ - val storedPlaylists: StoredPlaylists + val storedPlaylists: StoredPlaylists, + + /** + * A cache for file tree information to optimize file system exploration. + */ + val fileTreeCache: FileTreeCache ) /** Configuration for how to interpret and extrapolate certain audio tags. */ diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt index df2a6acb6..e8d71bbd1 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt @@ -31,6 +31,10 @@ import kotlinx.serialization.json.Json interface FileTreeCache { fun read(): FileTree + + companion object { + fun from(context: Context): FileTreeCache = FileTreeCacheImpl(context) + } } interface FileTree { @@ -47,7 +51,7 @@ interface FileTree { // Define the sealed interface @Serializable -sealed interface FileSystemEntry { +private sealed interface FileSystemEntry { val uri: String val modifiedMs: Long } @@ -71,14 +75,13 @@ data class CachedFile( ) : FileSystemEntry @Serializable -data class FileTreeData( +private data class FileTreeData( val directories: Map = mapOf(), val files: Map = mapOf() ) -class FileTreeCacheImpl(private val context: Context) : FileTreeCache { +private class FileTreeCacheImpl(private val context: Context) : FileTreeCache { companion object { - private const val TAG = "FileTreeCache" private const val CACHE_FILENAME = "file_tree_cache.json" private val json = Json { ignoreUnknownKeys = true @@ -98,17 +101,15 @@ class FileTreeCacheImpl(private val context: Context) : FileTreeCache { fileTreeCache.directories.toMutableMap(), fileTreeCache.files.toMutableMap()) } catch (e: Exception) { - Log.e(TAG, "Failed to read cache file", e) FileTreeImpl(context, mutableMapOf(), mutableMapOf()) } } else { - Log.i(TAG, "Cache file does not exist, creating new FileTree") FileTreeImpl(context, mutableMapOf(), mutableMapOf()) } } } -class FileTreeImpl( +private class FileTreeImpl( private val context: Context, private val mutableDirectories: MutableMap = mutableMapOf(), private val mutableFiles: MutableMap = mutableMapOf() @@ -124,26 +125,22 @@ class FileTreeImpl( // Directory operations override suspend fun queryDirectory(uri: Uri): CachedDirectory? { - Log.d("FileTreeCache", "Querying directory: $uri ${mutableDirectories[uri.toString()]}") val uriString = uri.toString() return mutableDirectories[uriString] } override suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) { - Log.d("FileTreeCache", "Updating directory: $uri") val uriString = uri.toString() mutableDirectories[uriString] = directory } // File operations override suspend fun queryFile(uri: Uri): CachedFile? { - Log.d("FileTreeCache", "Querying file: $uri") val uriString = uri.toString() return mutableFiles[uriString] } override suspend fun updateFile(uri: Uri, file: CachedFile) { - Log.d("FileTreeCache", "Updating file: $uri") val uriString = uri.toString() mutableFiles[uriString] = file } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 7cb5d2f10..32caf0747 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -44,7 +44,6 @@ import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.device.DeviceFS import org.oxycblt.musikr.fs.device.FileTreeCache -import org.oxycblt.musikr.fs.device.FileTreeCacheImpl import org.oxycblt.musikr.fs.device.flatten import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.m3u.M3U @@ -58,7 +57,7 @@ internal interface ExploreStep { DeviceFS.from(context, interpretation.withHidden), storage.cache, storage.covers, - FileTreeCacheImpl(context), + storage.fileTreeCache, storage.storedPlaylists) } } From b36f0ca4a3215ea8feb3d62799990293b1212727 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 29 May 2025 19:55:59 -0600 Subject: [PATCH 26/38] build: agent support With Claude 4, agents are finally able to navigate Auxio's codebase without crashing and burning. Update them. --- AGENT.md | 1 + CLAUDE.md | 123 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 120000 AGENT.md create mode 100644 CLAUDE.md diff --git a/AGENT.md b/AGENT.md new file mode 120000 index 000000000..681311eb9 --- /dev/null +++ b/AGENT.md @@ -0,0 +1 @@ +CLAUDE.md \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..7ebb3c146 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,123 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +Auxio is a modern Android music player written in Kotlin that emphasizes simplicity and performance. It uses Media3 ExoPlayer for playback and includes a custom native music indexing library called musikr. + +## Build System & Commands + +### Prerequisites +- `cmake` and `ninja-build` must be installed before building +- Project uses git submodules - clone with `git clone --recurse-submodules` +- **Cannot build on Windows** - requires Unix-based system for Media3 build scripts + +### Common Build Commands +```bash +# Build debug version +./gradlew assembleDebug + +# Build release version +./gradlew assembleRelease + +# Run tests +./gradlew test + +# Run connected tests +./gradlew connectedAndroidTest + +# Code formatting (Spotless) +./gradlew spotlessApply + +# Check code formatting +./gradlew spotlessCheck +``` + +### Development Modules +- `app/` - Main Android application +- `musikr/` - Native music indexing library with TagLib integration +- `media/` - Patched Media3 ExoPlayer libraries (git submodule) + +## Architecture Overview + +### Core Architecture Pattern +- **MVVM** with ViewModels for each major screen (Home, Detail, Playback, Search) +- **Repository Pattern** - MusicRepository as single source of truth for music data +- **Dependency Injection** - Hilt/Dagger for modular dependency management +- **Single Activity Architecture** with Navigation Components +- **Service-Oriented** background music processing + +### Key Modules & Components + +#### Music Management (`app/src/main/java/org/oxycblt/auxio/music/`) +- `MusicRepository` - Central music library state management +- `MusicViewModel` - UI layer for music data access +- `service/` - MediaBrowserServiceCompat integration +- `shim/` - Abstraction layer for musikr integration + +#### Playback Engine (`app/src/main/java/org/oxycblt/auxio/playback/`) +- `PlaybackViewModel` - Main playback UI interface +- `PlaybackStateManager` - Core playback state management +- `service/` - Background ExoPlayer integration +- `queue/` - Playback queue management +- `persist/` - Playback state persistence (Room database) +- `replaygain/` - Audio processing for volume normalization + +#### UI Structure (`app/src/main/java/org/oxycblt/auxio/`) +- `home/` - Main library browsing with customizable tabs +- `detail/` - Album, artist, genre, and playlist detail views +- `search/` - Music search functionality +- `list/` - Shared list components with sorting/filtering +- `ui/` - Custom UI components, theming, animations + +#### Native Music Library (`musikr/`) +- **Pipeline-based indexing** - Multi-stage scanning (Explore → Extract → Evaluate) +- **TagLib integration** - Native C++ metadata extraction +- **File system caching** - Device storage access optimization +- **Cover art management** - Embedded and external cover support + +### Data Flow +1. musikr scans and indexes music files from device storage +2. MusicRepository manages indexed library and exposes to UI +3. ViewModels provide reactive state for UI components using StateFlow +4. PlaybackService handles audio playback via ExoPlayer +5. UI observes ViewModels and updates reactively + +## Code Conventions + +### Language & Libraries +- **Kotlin** - Primary language with coroutines for async operations +- **Hilt/Dagger** - Dependency injection +- **Room** - Local database for persistence +- **Navigation Components** - Fragment navigation +- **ViewBinding** - Type-safe view access +- **StateFlow/LiveData** - Reactive state management +- **Coil** - Image loading for cover art + +### Code Style +- Uses Spotless with ktfmt Dropbox style formatting +- License header required (see NOTICE file) +- C++ code uses Eclipse CDT formatting (eclipse-cdt.xml) + +## Testing + +### Test Structure +- Unit tests: `src/test/` directories +- Integration tests: `src/androidTest/` directories +- musikr module includes Robolectric tests + +### Test Dependencies +- JUnit 4 for unit testing +- MockK for mocking +- Robolectric for Android unit tests +- Espresso for UI tests + +## Key Development Notes + +- **Custom Media3**: Uses patched Media3 ExoPlayer for enhanced playback features +- **Native Dependencies**: musikr module builds TagLib from source during compilation +- **Permission Handling**: Requires storage permissions for music file access +- **Background Services**: Foreground service for continuous music playback +- **Widget Support**: Multiple widget layouts with automatic sizing adaptation +- **ReplayGain**: Full support for MP3, FLAC, OGG, OPUS, and MP4 files \ No newline at end of file From 294c3eb304d430ec27f20766feed1e45c47d7dc7 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 29 May 2025 20:48:46 -0600 Subject: [PATCH 27/38] all: reformat --- .../main/java/org/oxycblt/auxio/music/MusicRepository.kt | 8 +++++--- .../oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt | 4 ++-- musikr/src/main/java/org/oxycblt/musikr/Config.kt | 4 +--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index b08a67ca4..28f5d5fdd 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -29,8 +29,8 @@ import kotlinx.coroutines.withContext import kotlinx.coroutines.yield import org.oxycblt.auxio.image.covers.SettingCovers import org.oxycblt.auxio.music.MusicRepository.IndexingWorker -import org.oxycblt.auxio.music.shim.WriteOnlyMutableCache import org.oxycblt.auxio.music.shim.WriteOnlyFileTreeCache +import org.oxycblt.auxio.music.shim.WriteOnlyMutableCache import org.oxycblt.musikr.IndexingProgress import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Library @@ -40,8 +40,8 @@ import org.oxycblt.musikr.MutableLibrary import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Song import org.oxycblt.musikr.Storage -import org.oxycblt.musikr.fs.device.FileTreeCache import org.oxycblt.musikr.cache.MutableCache +import org.oxycblt.musikr.fs.device.FileTreeCache import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.tag.interpret.Naming import org.oxycblt.musikr.tag.interpret.Separators @@ -393,7 +393,9 @@ constructor( val newRevision = currentRevision?.takeIf { withCache } ?: UUID.randomUUID() val cache = if (withCache) cache else WriteOnlyMutableCache(cache) val covers = settingCovers.mutate(context, newRevision) - val fileTreeCache = if (withCache) FileTreeCache.from(context) else WriteOnlyFileTreeCache(FileTreeCache.from(context)) + val fileTreeCache = + if (withCache) FileTreeCache.from(context) + else WriteOnlyFileTreeCache(FileTreeCache.from(context)) val storage = Storage(cache, covers, storedPlaylists, fileTreeCache) val interpretation = Interpretation(nameFactory, separators, withHidden) val result = diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt index 5d24edc53..f4659cdcb 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + package org.oxycblt.auxio.music.shim import android.net.Uri @@ -56,4 +56,4 @@ class WriteOnlyFileTree(private val innerTree: FileTree) : FileTree { // Forward write operations to the inner tree innerTree.write() } -} \ No newline at end of file +} diff --git a/musikr/src/main/java/org/oxycblt/musikr/Config.kt b/musikr/src/main/java/org/oxycblt/musikr/Config.kt index 12061a56c..be499cfa4 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Config.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Config.kt @@ -48,9 +48,7 @@ data class Storage( */ val storedPlaylists: StoredPlaylists, - /** - * A cache for file tree information to optimize file system exploration. - */ + /** A cache for file tree information to optimize file system exploration. */ val fileTreeCache: FileTreeCache ) From 7f672d63da4d24b6d85cf2294a89aefeabca913f Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 29 May 2025 20:54:57 -0600 Subject: [PATCH 28/38] musikr: add agent lodestones Useful for making changes with amp/claude. --- musikr/ARCHITECTURE.md | 135 ++++++++++++++++++ musikr/src/main/cpp/README.md | 90 ++++++++++++ .../java/org/oxycblt/musikr/covers/README.md | 74 ++++++++++ .../main/java/org/oxycblt/musikr/fs/README.md | 72 ++++++++++ .../org/oxycblt/musikr/metadata/README.md | 64 +++++++++ .../java/org/oxycblt/musikr/model/README.md | 79 ++++++++++ .../org/oxycblt/musikr/pipeline/README.md | 64 +++++++++ .../java/org/oxycblt/musikr/tag/README.md | 83 +++++++++++ 8 files changed, 661 insertions(+) create mode 100644 musikr/ARCHITECTURE.md create mode 100644 musikr/src/main/cpp/README.md create mode 100644 musikr/src/main/java/org/oxycblt/musikr/covers/README.md create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/README.md create mode 100644 musikr/src/main/java/org/oxycblt/musikr/metadata/README.md create mode 100644 musikr/src/main/java/org/oxycblt/musikr/model/README.md create mode 100644 musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md create mode 100644 musikr/src/main/java/org/oxycblt/musikr/tag/README.md diff --git a/musikr/ARCHITECTURE.md b/musikr/ARCHITECTURE.md new file mode 100644 index 000000000..f8b6eb58b --- /dev/null +++ b/musikr/ARCHITECTURE.md @@ -0,0 +1,135 @@ +# Musikr Architecture + +## Overview + +Musikr is a highly opinionated multithreaded music loader that provides advanced music functionality for Auxio. It bypasses Android's MediaStore to directly access music files using the Storage Access Framework (SAF) and [TagLib](https://taglib.org/) for metadata extraction. + +## Core Components + +### Pipeline Architecture + +Musikr uses a three-stage pipeline for music indexing: + +1. **Explore Step** - Discovers music files on the device +2. **Extract Step** - Extracts metadata from discovered files +3. **Evaluate Step** - Processes extracted data to build the music library + +```mermaid +graph LR + A[Music Locations] --> B[Explore Step] + B --> C[Extract Step] + C --> D[Evaluate Step] + D --> E[Library] + + subgraph Pipeline + B + C + D + end +``` + +### Key Interfaces + +- **Musikr** - Main entry point for the library +- **Storage** - Manages persistent storage needs +- **Library** - Represents the loaded music collection +- **MutableLibrary** - Modifiable version of the library + +## Module Structure + +### 1. File System (`fs` package) +- **MusicLocation** - Represents a location to search for music +- **DeviceFS** - Provides access to device storage +- **FileTreeCache** - Caches filesystem structure for faster indexing + +### 2. Pipeline (`pipeline` package) +- **ExploreStep** - Discovers music files on the device +- **ExtractStep** - Extracts metadata from discovered files +- **EvaluateStep** - Processes extracted data to build the library +- **PipelineItem** - Data items flowing through the pipeline + +### 3. Metadata (`metadata` package) +- **Metadata** - Extracted file metadata +- **MetadataExtractor** - Extracts metadata using TagLib +- **TagLibJNI** - JNI bridge to native TagLib library + +### 4. Tag Processing (`tag` package) +- **TagParser** - Parses raw tag data into structured format +- **TagInterpreter** - Interprets tags based on user preferences +- **ParsedTags** - Represents parsed metadata tags + +### 5. Model (`model` package) +- **LibraryImpl** - Implementation of the music library +- **SongImpl**, **AlbumImpl**, **ArtistImpl**, **GenreImpl** - Music entity implementations +- **LibraryFactory** - Creates library instances from pipeline data + +### 6. Covers (`covers` package) +- **Covers** - Interface for album cover management +- **EmbeddedCovers** - Extracts covers embedded in music files +- **FSCovers** - Discovers cover art in the filesystem +- **StoredCovers** - Manages persistent storage of covers + +### 7. Cache (`cache` package) +- **Cache** - Caches processed music data +- **DBCache** - Database implementation of caching + +### 8. Playlist (`playlist` package) +- **PlaylistFile** - Represents a playlist file +- **ExternalPlaylistManager** - Manages external playlist files +- **PlaylistInterpreter** - Interprets playlist formats + +## Native Component + +Musikr includes a native component built with TagLib for fast and accurate metadata extraction: + +```mermaid +graph TD + A[TagLibJNI] --> B[JNI Bridge] + B --> C[TagLib Library] + C --> D[Music File Metadata] +``` + +### Native Files (`cpp` directory) +- **taglib_jni.cpp** - Main JNI implementation +- **JMetadataBuilder** - Builds metadata objects from TagLib +- **JTagMap** - Maps between Java and C++ tag structures +- **JInputStream** - Input stream adapter for TagLib + +## Data Flow + +```mermaid +sequenceDiagram + participant User + participant Musikr + participant ExploreStep + participant ExtractStep + participant EvaluateStep + participant Storage + + User->>Musikr: run(locations) + Musikr->>ExploreStep: explore(locations) + ExploreStep->>Storage: Read cache + ExploreStep-->>Musikr: Explored files + Musikr->>ExtractStep: extract(explored) + ExtractStep->>TagLibJNI: Extract metadata + ExtractStep-->>Musikr: Extracted metadata + Musikr->>EvaluateStep: evaluate(extracted) + EvaluateStep->>Storage: Store processed data + EvaluateStep-->>Musikr: Library + Musikr-->>User: LibraryResult +``` + +## Threading Model + +Musikr uses Kotlin Coroutines for concurrent processing: + +- Pipeline stages use `flatMapMerge` and `distributedMap` for parallel processing +- Bounded buffer channels manage backpressure +- IO operations are dispatched to `Dispatchers.IO` + +## Best Practices for Extension + +1. The API is minimized and unstable - be prepared to fork and modify +2. No defaults are provided - carefully consider parameter choices +3. Musikr is stateless except for Storage - manage long-term state yourself +4. When adding functionality, follow the pipeline architecture pattern \ No newline at end of file diff --git a/musikr/src/main/cpp/README.md b/musikr/src/main/cpp/README.md new file mode 100644 index 000000000..dc42457b8 --- /dev/null +++ b/musikr/src/main/cpp/README.md @@ -0,0 +1,90 @@ +# Native Code (C++) Component + +## Overview + +This directory contains the native C++ code that bridges between Java and TagLib. It enables fast and accurate metadata extraction from music files. + +## Key Components + +### JNI Implementation + +**taglib_jni.cpp** +- Main JNI implementation +- Registers native methods +- Handles JNI environment setup + +**JMetadataBuilder** +- Builds metadata objects from TagLib +- Extracts tags and properties +- Maps between TagLib and Java structures + +**JTagMap** +- Maps between Java and C++ tag structures +- Provides bidirectional conversion + +**JInputStream** +- Input stream adapter for TagLib +- Bridges between Java I/O and TagLib I/O + +### Utility Classes + +**JStringRef** +- Manages JNI string references +- Handles UTF conversions + +**JByteArrayRef** +- Manages JNI byte array references +- Provides safe access to Java byte arrays + +**JObjectRef** +- Manages JNI object references +- Provides RAII-style resource management + +**JClassRef** +- Manages JNI class references +- Caches class and method lookups + +**util.h** +- Utility functions for JNI +- Error handling and logging + +### Build Configuration + +**CMakeLists.txt** +- CMake build configuration +- Configures TagLib integration + +**build_taglib.sh** +- Script to build TagLib from source +- Configures platform-specific options + +**android.toolchain.cmake** +- Android-specific CMake toolchain + +## TagLib Integration + +TagLib is included as a subproject and built from source. The `taglib` directory contains the TagLib source code, which is a powerful and feature-rich library for reading and writing audio metadata. + +## Build Process + +1. The build starts with `build_taglib.sh` +2. TagLib is configured and built with CMake +3. The JNI wrapper is built against TagLib +4. The resulting library is packaged into the AAR + +## JNI Interface + +The native methods are exposed through `TagLibJNI.kt` in the Java code. The main functionalities include: + +- Reading metadata from audio files +- Extracting embedded cover art +- Accessing audio properties (bitrate, sample rate, etc.) + +## Extension Points + +When extending the native code: + +1. For new tag formats, update the TagLib integration +2. For new metadata fields, add them to JMetadataBuilder +3. For performance improvements, optimize the JNI bridge +4. For platform-specific optimizations, update the build configuration \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/README.md b/musikr/src/main/java/org/oxycblt/musikr/covers/README.md new file mode 100644 index 000000000..b33e3b209 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/README.md @@ -0,0 +1,74 @@ +# Covers Package + +## Overview + +The covers package provides functionality for discovering, extracting, and managing album cover art. It handles embedded covers in music files, external cover images, and persistent storage. + +## Key Components + +### Core Interfaces + +**Covers** (`Covers.kt`) +- Generic interface for cover art management +- Provides methods to obtain and manage covers + +**Cover** (`Covers.kt`) +- Represents a cover image +- Contains cover metadata and access methods + +### Cover Sources + +**EmbeddedCovers** (`embedded/EmbeddedCovers.kt`) +- Extracts covers embedded in music files +- Uses metadata extraction to access embedded images + +**FSCovers** (`fs/FSCovers.kt`) +- Discovers cover art in the filesystem +- Searches for common cover image filenames + +**ChainedCovers** (`chained/ChainedCovers.kt`) +- Combines multiple cover sources +- Provides fallback mechanisms + +### Storage + +**StoredCovers** (`stored/StoredCovers.kt`) +- Manages persistent storage of covers +- Handles caching and retrieval + +**CoverStorage** (`stored/CoverStorage.kt`) +- Low-level cover storage operations +- Manages the cover storage directory + +**Transcoding** (`stored/Transcoding.kt`) +- Handles image format conversion +- Optimizes covers for storage and display + +### Identification + +**CoverIdentifier** (`embedded/CoverIdentifier.kt`) +- Generates unique identifiers for covers +- Used for caching and referencing + +## Cover Flow + +1. During music indexing, covers are extracted or discovered +2. Covers are identified and stored +3. Songs reference covers by identifier +4. When needed, covers are retrieved from storage + +## Key Features + +- **Multiple sources** - Embedded, filesystem, and custom sources +- **Efficient storage** - Avoids duplicates through identification +- **Format optimization** - Transcodes images for optimal storage +- **Lazy loading** - Loads covers only when needed + +## Extension Points + +When extending the cover functionality: + +1. For new cover sources, implement the Covers interface +2. For custom storage, extend or replace StoredCovers +3. For format-specific handling, update the Transcoding class +4. For performance improvements, optimize the identification and storage mechanisms \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/README.md b/musikr/src/main/java/org/oxycblt/musikr/fs/README.md new file mode 100644 index 000000000..d73231152 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/README.md @@ -0,0 +1,72 @@ +# Filesystem Package + +## Overview + +The filesystem package provides abstraction layers for accessing music files on Android devices. It handles the complexities of the Storage Access Framework (SAF) and provides efficient caching mechanisms. + +## Key Components + +### Core Types + +**MusicLocation** (`MusicLocation.kt`) +- Represents a location to search for music +- Can be a device storage location or content URI + +**Path** (`Path.kt`) +- Abstract representation of a file path +- Handles both traditional file paths and content URIs + +**Format** (`Format.kt`) +- Represents file formats and their properties +- Maps MIME types to file extensions + +### Device Access + +**DeviceFS** (`DeviceFS.kt`) +- Provides access to device storage +- Handles SAF permissions and access +- Performs filesystem traversal + +**DeviceFSEntries** (`DeviceFSEntries.kt`) +- Represents filesystem entries (files and directories) +- Provides metadata about filesystem items + +**DeviceFile** (in `DeviceFSEntries.kt`) +- Represents a music file on the device +- Contains file metadata needed for processing + +### Caching + +**FileTreeCache** (`FileTreeCache.kt`) +- Caches filesystem structure for faster indexing +- Provides incremental updates to avoid full rescans + +### Path Interpretation + +**Path Package** (`path/` directory) +- **DocumentPathFactory** - Creates paths from document URIs +- **MediaStorePathInterpreter** - Interprets MediaStore paths +- **VolumeManager** - Manages storage volumes + +## Usage Flow + +1. User provides `MusicLocation`s to scan +2. `DeviceFS` traverses these locations +3. `FileTreeCache` optimizes subsequent scans +4. Discovered files are passed to the pipeline for processing + +## Key Features + +- **Storage Access Framework** integration for modern Android storage access +- **Incremental scanning** to minimize resource usage +- **Path abstraction** to handle different Android storage mechanisms +- **Volume mapping** to resolve relative paths + +## Extension Points + +When extending the filesystem functionality: + +1. For new storage types, implement appropriate Path implementations +2. For performance improvements, consider optimizing the FileTreeCache +3. For new file formats, update the Format class +4. For custom traversal strategies, extend DeviceFS \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/README.md b/musikr/src/main/java/org/oxycblt/musikr/metadata/README.md new file mode 100644 index 000000000..f52216dd9 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/metadata/README.md @@ -0,0 +1,64 @@ +# Metadata Package + +## Overview + +The metadata package provides the native bridge to TagLib and handles extraction of metadata from music files. This is a critical component that enables accurate and comprehensive tag parsing. + +## Key Components + +### JNI Interface + +**TagLibJNI** (`TagLibJNI.kt`) +- Loads the native library +- Provides JNI methods for interacting with TagLib +- Handles native memory management + +**NativeTagMap** (`NativeTagMap.kt`) +- Maps between native C++ and Java tag structures +- Provides type conversion utilities + +**NativeInputStream** (`NativeInputStream.kt`) +- Provides a stream interface for TagLib to read file data +- Bridges between Java I/O and native code + +### Metadata Extraction + +**MetadataExtractor** (`MetadataExtractor.kt`) +- Extracts metadata from music files using TagLib +- Handles error cases and format-specific extractions +- Manages native resource lifecycle + +**Metadata** (`Metadata.kt`) +- Container for extracted audio metadata +- Includes both tags and audio properties + +**Properties** (part of `Metadata.kt`) +- Audio-specific properties like duration, sample rate, etc. +- Format-specific information + +## Native Implementation + +The C++ side of the metadata extraction is implemented in the `cpp` directory: + +- **taglib_jni.cpp** - Main JNI implementation +- **JMetadataBuilder** - Builds metadata objects from TagLib +- **JTagMap** - Maps between Java and C++ tag structures +- **JInputStream** - Input stream adapter for TagLib + +## Usage Flow + +1. File is discovered in the exploration step +2. MetadataExtractor is called with the file +3. NativeInputStream provides file access to TagLib +4. TagLib parses the file's metadata +5. JMetadataBuilder converts TagLib structures to Java objects +6. Metadata object is returned to the pipeline + +## Extension Points + +When extending the metadata functionality: + +1. For new tag formats, extend the native JNI code in `taglib_jni.cpp` +2. For new metadata fields, add them to both Java and native interfaces +3. For performance improvements, consider caching strategies in MetadataExtractor +4. Always ensure proper resource management with native code \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/model/README.md b/musikr/src/main/java/org/oxycblt/musikr/model/README.md new file mode 100644 index 000000000..8170ad252 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/model/README.md @@ -0,0 +1,79 @@ +# Model Package + +## Overview + +The model package implements the core music entity model for Musikr. It provides the structures that represent songs, albums, artists, genres, and playlists, as well as their relationships. + +## Key Components + +### Core Interfaces + +These interfaces are defined in the parent package (`org.oxycblt.musikr`) and implemented in the model package: + +- **Library** - Read-only representation of the music library +- **MutableLibrary** - Modifiable version of the library +- **Song** - Represents a music track +- **Album** - Represents an album +- **Artist** - Represents an artist +- **Genre** - Represents a music genre +- **Playlist** - Represents a playlist + +### Implementations + +**LibraryImpl** (`LibraryImpl.kt`) +- Implementation of the Library and MutableLibrary interfaces +- Manages collections of songs, albums, artists, genres, and playlists +- Provides search and lookup functionality + +**SongImpl** (`SongImpl.kt`) +- Implementation of the Song interface +- Contains metadata, file information, and relationships + +**AlbumImpl** (`AlbumImpl.kt`) +- Implementation of the Album interface +- Contains songs, artists, and album metadata + +**ArtistImpl** (`ArtistImpl.kt`) +- Implementation of the Artist interface +- Contains songs, albums, and artist metadata + +**GenreImpl** (`GenreImpl.kt`) +- Implementation of the Genre interface +- Contains songs and genre metadata + +**PlaylistImpl** (`PlaylistImpl.kt`) +- Implementation of the Playlist interface +- Contains ordered songs and playlist metadata + +### Factory + +**LibraryFactory** (`LibraryFactory.kt`) +- Creates library instances from pipeline data +- Builds the entity relationships +- Resolves duplicates and conflicts + +## Entity Relationships + +The music model implements a graph structure with these relationships: + +- Songs belong to albums, artists, and genres +- Albums belong to artists +- Artists have songs and albums +- Genres have songs +- Playlists have songs + +## Key Features + +- **Identity resolution** - Properly identifies and merges duplicate entities +- **Relationship building** - Creates the connections between entities +- **Immutable interfaces** - Provides read-only access for safety +- **Mutable implementation** - Allows controlled modifications + +## Extension Points + +When extending the model: + +1. For new entity types, create new interfaces and implementations +2. For new relationships, update the appropriate entities and LibraryFactory +3. For performance improvements, consider optimizing the graph structure +4. For custom sorting or grouping, extend the LibraryImpl functionality \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md b/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md new file mode 100644 index 000000000..ddbf500ce --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md @@ -0,0 +1,64 @@ +# Pipeline Package + +## Overview + +The pipeline package implements a three-stage processing pipeline for music indexing in Musikr. It provides a concurrent, efficient way to discover, extract metadata from, and process music files. + +## Key Components + +### Pipeline Steps + +1. **ExploreStep** (`ExploreStep.kt`) + - Discovers music files on the device + - Interfaces with filesystem caches + - Produces `Explored` items for processing + +2. **ExtractStep** (`ExtractStep.kt`) + - Extracts metadata from discovered files + - Uses TagLib via JNI for metadata extraction + - Produces `Extracted` items with parsed tags + +3. **EvaluateStep** (`EvaluateStep.kt`) + - Processes extracted data to build the music library + - Creates the song/album/artist/genre relationships + - Resolves cover art references + +### Pipeline Items + +The `PipelineItem.kt` defines the data types that flow through the pipeline: + +- **Explored** - Files discovered in the filesystem + - `NewSong` - A newly discovered music file + - `RawPlaylist` - A discovered playlist file + +- **Extracted** - Files with extracted metadata + - `RawSong` - A song with extracted metadata and tags + - `InvalidSong` - A file that couldn't be processed + +### Exception Handling + +`PipelineException.kt` defines exceptions specific to the pipeline process. + +## Flow Utilities + +`FlowUtil.kt` provides utility functions for working with Kotlin Flows in the pipeline context, including: + +- `distributedMap` - Parallel mapping operations +- Flow merging and buffering utilities + +## Pipeline Flow + +``` +MusicLocation → ExploreStep → ExtractStep → EvaluateStep → Library +``` + +Data flows through the pipeline using Kotlin's Flow API, with extensive use of parallel processing and buffering to optimize performance. + +## Extension Points + +When extending the pipeline: + +1. Consider the stage where your functionality belongs +2. Follow the existing pattern of `Flow → Flow` transformations +3. Use the appropriate dispatchers for I/O vs CPU work +4. Buffer appropriately to manage backpressure \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/README.md b/musikr/src/main/java/org/oxycblt/musikr/tag/README.md new file mode 100644 index 000000000..7cdacd0f0 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/README.md @@ -0,0 +1,83 @@ +# Tag Package + +## Overview + +The tag package handles parsing, interpreting, and managing music metadata tags. It provides structures for representing various tag types and interpreting them according to user preferences. + +## Key Components + +### Tag Parsing + +**TagParser** (`parse/TagParser.kt`) +- Parses raw tag data from the metadata extractor +- Handles different tag formats and structures +- Normalizes tags across different formats + +**ParsedTags** (`parse/ParsedTags.kt`) +- Container for parsed metadata tags +- Provides structured access to tag values + +**TagFields** (`parse/TagFields.kt`) +- Defines standard tag fields and their mapping +- Handles format-specific field names + +### Tag Interpretation + +**TagInterpreter** (`interpret/TagInterpreter.kt`) +- Interprets tags based on user preferences +- Resolves ambiguities in tag data +- Creates structured music metadata + +**Naming** (`interpret/Naming.kt`) +- Handles naming conventions for music entities +- Provides fallbacks for missing metadata + +**Separators** (`interpret/Separators.kt`) +- Handles multi-value separators in tags +- Splits tags with multiple artists, genres, etc. + +**PreMusic** (`interpret/PreMusic.kt`) +- Intermediate representation during tag interpretation +- Holds partially processed music data + +### Tag Types + +**Name** (`Name.kt`) +- Represents artist, album, and track names +- Handles normalization and comparison + +**Date** (`Date.kt`) +- Represents release dates +- Handles various date formats and partial dates + +**Disc** (`Disc.kt`) +- Represents disc and track numbers +- Handles various numbering formats + +**ReleaseType** (`ReleaseType.kt`) +- Represents album release types (album, EP, single, etc.) +- Handles format-specific release type tags + +### Format-Specific Handling + +**ID3** (`format/ID3.kt`) +- Handles ID3v1 and ID3v2 tag specifics + +**Vorbis** (`format/Vorbis.kt`) +- Handles Vorbis Comment tag specifics + +## Tag Flow + +1. Raw tags extracted by the metadata extractor +2. TagParser normalizes tags into ParsedTags +3. TagInterpreter interprets tags based on user preferences +4. Interpreted tags are used to build the music library + +## Extension Points + +When extending the tag functionality: + +1. For new tag types, extend the TagParser and relevant format handlers +2. For new interpretation rules, modify the TagInterpreter +3. For format-specific handling, add new format classes +4. For new metadata types, add appropriate structures and update the tag flow \ No newline at end of file From f2b1ba71f2bda6d9c7925e1e08a41a8381b0d928 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 29 May 2025 20:55:52 -0600 Subject: [PATCH 29/38] musikr: add subfolder exclusion prototype --- .../main/java/org/oxycblt/musikr/Musikr.kt | 28 +++++++++++++++ .../org/oxycblt/musikr/fs/MusicLocation.kt | 30 +++++++++++----- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 36 ++++++++++++------- 3 files changed, 73 insertions(+), 21 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 29e5ff67f..580debe92 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -57,6 +57,26 @@ interface Musikr { locations: List, onProgress: suspend (IndexingProgress) -> Unit = {} ): LibraryResult + + /** + * Update a music location with a set of subdirectories to exclude from scanning. + * + * @param context The context to use for loading resources. + * @param uri The URI of the music location to update. + * @param excludedSubdirs The set of subdirectory names to exclude when scanning this location. + * @return The updated [MusicLocation] or null if the location doesn't exist. + */ + fun updateLocationExclusions(context: Context, uri: android.net.Uri, excludedSubdirs: Set): MusicLocation? + + /** + * Create a new music location with a set of subdirectories to exclude from scanning. + * + * @param context The context to use for loading resources. + * @param uri The URI of the music location to create. + * @param excludedSubdirs The set of subdirectory names to exclude when scanning this location. + * @return The new [MusicLocation] or null if the location couldn't be created. + */ + fun newLocationWithExclusions(context: Context, uri: android.net.Uri, excludedSubdirs: Set): MusicLocation? companion object { /** @@ -116,6 +136,14 @@ private class MusikrImpl( private val extractStep: ExtractStep, private val evaluateStep: EvaluateStep ) : Musikr { + override fun updateLocationExclusions(context: Context, uri: android.net.Uri, excludedSubdirs: Set): MusicLocation? { + return MusicLocation.existing(context, uri, excludedSubdirs) + } + + override fun newLocationWithExclusions(context: Context, uri: android.net.Uri, excludedSubdirs: Set): MusicLocation? { + return MusicLocation.new(context, uri, excludedSubdirs) + } + override suspend fun run( locations: List, onProgress: suspend (IndexingProgress) -> Unit diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt index 636d16c61..37baa94b9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt @@ -26,7 +26,7 @@ import org.oxycblt.musikr.fs.device.contentResolverSafe import org.oxycblt.musikr.fs.path.DocumentPathFactory import org.oxycblt.musikr.util.splitEscaped -class MusicLocation private constructor(val uri: Uri, val path: Path) { +class MusicLocation private constructor(val uri: Uri, val path: Path, val excludedSubdirs: Set = emptySet()) { override fun equals(other: Any?) = other is MusicLocation && uri == other.uri override fun hashCode() = 31 * uri.hashCode() @@ -34,7 +34,7 @@ class MusicLocation private constructor(val uri: Uri, val path: Path) { override fun toString(): String = uri.toString() companion object { - fun new(context: Context, uri: Uri): MusicLocation? { + fun new(context: Context, uri: Uri, excludedSubdirs: Set = emptySet()): MusicLocation? { if (!DocumentsContract.isTreeUri(uri)) return null val documentPathFactory = DocumentPathFactory.from(context) val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null @@ -47,10 +47,10 @@ class MusicLocation private constructor(val uri: Uri, val path: Path) { uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) } - return MusicLocation(uri, path) + return MusicLocation(uri, path, excludedSubdirs) } - fun existing(context: Context, uri: Uri): MusicLocation? { + fun existing(context: Context, uri: Uri, excludedSubdirs: Set = emptySet()): MusicLocation? { val documentPathFactory = DocumentPathFactory.from(context) if (!DocumentsContract.isTreeUri(uri)) return null val notPersisted = @@ -59,14 +59,28 @@ class MusicLocation private constructor(val uri: Uri, val path: Path) { } if (notPersisted) return null val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null - return MusicLocation(uri, path) + return MusicLocation(uri, path, excludedSubdirs) } - fun toString(list: List) = - list.joinToString(";") { it.uri.toString().replace(";", "\\;") } + fun toString(list: List): String { + return list.joinToString(";") { location -> + val uriStr = location.uri.toString().replace(";", "\\;") + val excludedSubdirsStr = location.excludedSubdirs.joinToString(",") { it.replace(",", "\\,").replace(";", "\\;") } + if (excludedSubdirsStr.isEmpty()) uriStr else "$uriStr|$excludedSubdirsStr" + } + } fun existing(context: Context, string: String): List { - return string.splitEscaped { it == ';' }.mapNotNull { existing(context, Uri.parse(it)) } + return string.splitEscaped { it == ';' }.mapNotNull { entry -> + val parts = entry.split("|", limit = 2) + val uriStr = parts[0] + val excludedSubdirs = if (parts.size > 1) { + parts[1].splitEscaped { it == ',' }.toSet() + } else { + emptySet() + } + existing(context, Uri.parse(uriStr), excludedSubdirs) + } } } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index c0c27f5ae..346d02132 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -22,7 +22,6 @@ import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract -import android.util.Log import androidx.core.net.toUri import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -40,6 +39,7 @@ import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.takeWhile +import kotlinx.coroutines.flow.transform import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path @@ -76,7 +76,7 @@ private class DeviceFSImpl( if (modifiedMs == null) { return null } - return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree) + return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree, location.excludedSubdirs) } private suspend fun query( @@ -85,13 +85,14 @@ private class DeviceFSImpl( path: Path, modifiedMs: Long, parent: DeviceDirectory?, - fileTree: FileTree + fileTree: FileTree, + excludedSubdirs: Set = emptySet() ): DeviceDirectory = coroutineScope { val uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) val cached = fileTree.queryDirectory(uri) if (cached != null && cached.modifiedMs == modifiedMs) { return@coroutineScope hydrateCached( - cached = cached, parentDir = parent, path = path, fileTree = fileTree) + cached = cached, parentDir = parent, path = path, fileTree = fileTree, excludedSubdirs = excludedSubdirs) } val dir = DeviceDirectoryImpl( @@ -102,7 +103,6 @@ private class DeviceFSImpl( children = emptyFlow()) dir.children = flow { - Log.d("DeviceFS", "Querying $uri") contentResolver.useQuery( DocumentsContract.buildChildDocumentsUriUsingTree( rootUri, @@ -129,8 +129,6 @@ private class DeviceFSImpl( val childSubdirUris = mutableListOf() val childFileUris = mutableListOf() - val subqueries = mutableListOf() - while (cursor.moveToNext()) { val childId = cursor.getString(childUriIndex) val displayName = cursor.getString(displayNameIndex) @@ -145,6 +143,11 @@ private class DeviceFSImpl( val lastModified = cursor.getLong(lastModifiedIndex) if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + // Skip this directory if it's in the excluded list + if (displayName in excludedSubdirs) { + continue + } + val subdir = query( rootUri = rootUri, @@ -152,11 +155,11 @@ private class DeviceFSImpl( path = newPath, modifiedMs = modifiedMs, parent = dir, - fileTree = fileTree) + fileTree = fileTree, + excludedSubdirs = excludedSubdirs) childSubdirUris.add(subdir.uri.toString()) emit(StreamedFile.More(subdir)) } else { - Log.d("DeviceFS", "Querying file $childId") val size = cursor.getLong(sizeIndex) val childUri = DocumentsContract.buildDocumentUriUsingTree( @@ -202,7 +205,8 @@ private class DeviceFSImpl( cached: CachedDirectory, parentDir: DeviceDirectory?, path: Path, - fileTree: FileTree + fileTree: FileTree, + excludedSubdirs: Set = emptySet() ): DeviceDirectory = coroutineScope { val dir = DeviceDirectoryImpl( @@ -215,17 +219,23 @@ private class DeviceFSImpl( flow { emitAll( merge( - cached.subdirUris.asFlow().map { subdirUriString -> + cached.subdirUris.asFlow().transform { subdirUriString -> val subdirUri = subdirUriString.toUri() val cachedSubdir = requireNotNull(fileTree.queryDirectory(subdirUri)) { "No cached subdir for $subdirUri, malformed cache! Rescan needed." } - hydrateCached( + // Skip this directory if it's in the excluded list + if (cachedSubdir.name in excludedSubdirs) { + return@transform + } + + emit(hydrateCached( cachedSubdir, dir, dir.path.file(cachedSubdir.name), - fileTree) + fileTree, + excludedSubdirs)) }, cached.fileUris.asFlow().map { val cachedFile = requireNotNull(fileTree.queryFile(it.toUri())) From d49f719de7e64039d613e8e0028abde195a58f12 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 29 May 2025 20:58:41 -0600 Subject: [PATCH 30/38] Revert "musikr: add subfolder exclusion prototype" This reverts commit f2b1ba71f2bda6d9c7925e1e08a41a8381b0d928. --- .../main/java/org/oxycblt/musikr/Musikr.kt | 28 --------------- .../org/oxycblt/musikr/fs/MusicLocation.kt | 30 +++++----------- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 36 +++++++------------ 3 files changed, 21 insertions(+), 73 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 580debe92..29e5ff67f 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -57,26 +57,6 @@ interface Musikr { locations: List, onProgress: suspend (IndexingProgress) -> Unit = {} ): LibraryResult - - /** - * Update a music location with a set of subdirectories to exclude from scanning. - * - * @param context The context to use for loading resources. - * @param uri The URI of the music location to update. - * @param excludedSubdirs The set of subdirectory names to exclude when scanning this location. - * @return The updated [MusicLocation] or null if the location doesn't exist. - */ - fun updateLocationExclusions(context: Context, uri: android.net.Uri, excludedSubdirs: Set): MusicLocation? - - /** - * Create a new music location with a set of subdirectories to exclude from scanning. - * - * @param context The context to use for loading resources. - * @param uri The URI of the music location to create. - * @param excludedSubdirs The set of subdirectory names to exclude when scanning this location. - * @return The new [MusicLocation] or null if the location couldn't be created. - */ - fun newLocationWithExclusions(context: Context, uri: android.net.Uri, excludedSubdirs: Set): MusicLocation? companion object { /** @@ -136,14 +116,6 @@ private class MusikrImpl( private val extractStep: ExtractStep, private val evaluateStep: EvaluateStep ) : Musikr { - override fun updateLocationExclusions(context: Context, uri: android.net.Uri, excludedSubdirs: Set): MusicLocation? { - return MusicLocation.existing(context, uri, excludedSubdirs) - } - - override fun newLocationWithExclusions(context: Context, uri: android.net.Uri, excludedSubdirs: Set): MusicLocation? { - return MusicLocation.new(context, uri, excludedSubdirs) - } - override suspend fun run( locations: List, onProgress: suspend (IndexingProgress) -> Unit diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt index 37baa94b9..636d16c61 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt @@ -26,7 +26,7 @@ import org.oxycblt.musikr.fs.device.contentResolverSafe import org.oxycblt.musikr.fs.path.DocumentPathFactory import org.oxycblt.musikr.util.splitEscaped -class MusicLocation private constructor(val uri: Uri, val path: Path, val excludedSubdirs: Set = emptySet()) { +class MusicLocation private constructor(val uri: Uri, val path: Path) { override fun equals(other: Any?) = other is MusicLocation && uri == other.uri override fun hashCode() = 31 * uri.hashCode() @@ -34,7 +34,7 @@ class MusicLocation private constructor(val uri: Uri, val path: Path, val exclud override fun toString(): String = uri.toString() companion object { - fun new(context: Context, uri: Uri, excludedSubdirs: Set = emptySet()): MusicLocation? { + fun new(context: Context, uri: Uri): MusicLocation? { if (!DocumentsContract.isTreeUri(uri)) return null val documentPathFactory = DocumentPathFactory.from(context) val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null @@ -47,10 +47,10 @@ class MusicLocation private constructor(val uri: Uri, val path: Path, val exclud uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) } - return MusicLocation(uri, path, excludedSubdirs) + return MusicLocation(uri, path) } - fun existing(context: Context, uri: Uri, excludedSubdirs: Set = emptySet()): MusicLocation? { + fun existing(context: Context, uri: Uri): MusicLocation? { val documentPathFactory = DocumentPathFactory.from(context) if (!DocumentsContract.isTreeUri(uri)) return null val notPersisted = @@ -59,28 +59,14 @@ class MusicLocation private constructor(val uri: Uri, val path: Path, val exclud } if (notPersisted) return null val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null - return MusicLocation(uri, path, excludedSubdirs) + return MusicLocation(uri, path) } - fun toString(list: List): String { - return list.joinToString(";") { location -> - val uriStr = location.uri.toString().replace(";", "\\;") - val excludedSubdirsStr = location.excludedSubdirs.joinToString(",") { it.replace(",", "\\,").replace(";", "\\;") } - if (excludedSubdirsStr.isEmpty()) uriStr else "$uriStr|$excludedSubdirsStr" - } - } + fun toString(list: List) = + list.joinToString(";") { it.uri.toString().replace(";", "\\;") } fun existing(context: Context, string: String): List { - return string.splitEscaped { it == ';' }.mapNotNull { entry -> - val parts = entry.split("|", limit = 2) - val uriStr = parts[0] - val excludedSubdirs = if (parts.size > 1) { - parts[1].splitEscaped { it == ',' }.toSet() - } else { - emptySet() - } - existing(context, Uri.parse(uriStr), excludedSubdirs) - } + return string.splitEscaped { it == ';' }.mapNotNull { existing(context, Uri.parse(it)) } } } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 346d02132..c0c27f5ae 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -22,6 +22,7 @@ import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract +import android.util.Log import androidx.core.net.toUri import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -39,7 +40,6 @@ import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.takeWhile -import kotlinx.coroutines.flow.transform import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path @@ -76,7 +76,7 @@ private class DeviceFSImpl( if (modifiedMs == null) { return null } - return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree, location.excludedSubdirs) + return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree) } private suspend fun query( @@ -85,14 +85,13 @@ private class DeviceFSImpl( path: Path, modifiedMs: Long, parent: DeviceDirectory?, - fileTree: FileTree, - excludedSubdirs: Set = emptySet() + fileTree: FileTree ): DeviceDirectory = coroutineScope { val uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) val cached = fileTree.queryDirectory(uri) if (cached != null && cached.modifiedMs == modifiedMs) { return@coroutineScope hydrateCached( - cached = cached, parentDir = parent, path = path, fileTree = fileTree, excludedSubdirs = excludedSubdirs) + cached = cached, parentDir = parent, path = path, fileTree = fileTree) } val dir = DeviceDirectoryImpl( @@ -103,6 +102,7 @@ private class DeviceFSImpl( children = emptyFlow()) dir.children = flow { + Log.d("DeviceFS", "Querying $uri") contentResolver.useQuery( DocumentsContract.buildChildDocumentsUriUsingTree( rootUri, @@ -129,6 +129,8 @@ private class DeviceFSImpl( val childSubdirUris = mutableListOf() val childFileUris = mutableListOf() + val subqueries = mutableListOf() + while (cursor.moveToNext()) { val childId = cursor.getString(childUriIndex) val displayName = cursor.getString(displayNameIndex) @@ -143,11 +145,6 @@ private class DeviceFSImpl( val lastModified = cursor.getLong(lastModifiedIndex) if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - // Skip this directory if it's in the excluded list - if (displayName in excludedSubdirs) { - continue - } - val subdir = query( rootUri = rootUri, @@ -155,11 +152,11 @@ private class DeviceFSImpl( path = newPath, modifiedMs = modifiedMs, parent = dir, - fileTree = fileTree, - excludedSubdirs = excludedSubdirs) + fileTree = fileTree) childSubdirUris.add(subdir.uri.toString()) emit(StreamedFile.More(subdir)) } else { + Log.d("DeviceFS", "Querying file $childId") val size = cursor.getLong(sizeIndex) val childUri = DocumentsContract.buildDocumentUriUsingTree( @@ -205,8 +202,7 @@ private class DeviceFSImpl( cached: CachedDirectory, parentDir: DeviceDirectory?, path: Path, - fileTree: FileTree, - excludedSubdirs: Set = emptySet() + fileTree: FileTree ): DeviceDirectory = coroutineScope { val dir = DeviceDirectoryImpl( @@ -219,23 +215,17 @@ private class DeviceFSImpl( flow { emitAll( merge( - cached.subdirUris.asFlow().transform { subdirUriString -> + cached.subdirUris.asFlow().map { subdirUriString -> val subdirUri = subdirUriString.toUri() val cachedSubdir = requireNotNull(fileTree.queryDirectory(subdirUri)) { "No cached subdir for $subdirUri, malformed cache! Rescan needed." } - // Skip this directory if it's in the excluded list - if (cachedSubdir.name in excludedSubdirs) { - return@transform - } - - emit(hydrateCached( + hydrateCached( cachedSubdir, dir, dir.path.file(cachedSubdir.name), - fileTree, - excludedSubdirs)) + fileTree) }, cached.fileUris.asFlow().map { val cachedFile = requireNotNull(fileTree.queryFile(it.toUri())) From 94dbe744df8462cf9374c46862e091084983f0d1 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Fri, 30 May 2025 18:16:26 -0600 Subject: [PATCH 31/38] musikr: refactor musiclocation api into location Improves the API surface pretty heavily. Assisted by Claude 4 Sonnet/Claude 3.5 Haiku. --- .../oxycblt/auxio/music/MusicRepository.kt | 4 +- .../org/oxycblt/auxio/music/MusicSettings.kt | 57 +++++++++++-- .../auxio/music/locations/LocationAdapter.kt | 37 ++++----- .../music/locations/MusicSourcesDialog.kt | 13 +-- .../auxio/music/service/IndexingHolder.kt | 4 +- musikr/ARCHITECTURE.md | 2 +- .../main/java/org/oxycblt/musikr/Config.kt | 8 ++ .../main/java/org/oxycblt/musikr/Musikr.kt | 13 +-- .../fs/{MusicLocation.kt => Location.kt} | 64 ++++++++------- .../main/java/org/oxycblt/musikr/fs/README.md | 4 +- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 80 +++++++++++++------ .../oxycblt/musikr/pipeline/ExploreStep.kt | 13 +-- .../org/oxycblt/musikr/pipeline/README.md | 2 +- .../oxycblt/musikr/track/LocationObserver.kt | 4 +- .../org/oxycblt/musikr/track/UpdateTracker.kt | 8 +- 15 files changed, 207 insertions(+), 106 deletions(-) rename musikr/src/main/java/org/oxycblt/musikr/fs/{MusicLocation.kt => Location.kt} (50%) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index 28f5d5fdd..61312fb90 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -38,6 +38,7 @@ import org.oxycblt.musikr.Music import org.oxycblt.musikr.Musikr import org.oxycblt.musikr.MutableLibrary import org.oxycblt.musikr.Playlist +import org.oxycblt.musikr.Query import org.oxycblt.musikr.Song import org.oxycblt.musikr.Storage import org.oxycblt.musikr.cache.MutableCache @@ -396,10 +397,11 @@ constructor( val fileTreeCache = if (withCache) FileTreeCache.from(context) else WriteOnlyFileTreeCache(FileTreeCache.from(context)) + val query = Query(source = locations, exclude = emptyList()) val storage = Storage(cache, covers, storedPlaylists, fileTreeCache) val interpretation = Interpretation(nameFactory, separators, withHidden) val result = - Musikr.new(context, storage, interpretation).run(locations, ::emitIndexingProgress) + Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress) // Music loading completed, update the revision right now so we re-use this work // later. musicSettings.revision = newRevision diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 67b79ae15..b1a1a6d5e 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -20,12 +20,14 @@ package org.oxycblt.auxio.music import android.content.Context import androidx.core.content.edit +import androidx.core.net.toUri import dagger.hilt.android.qualifiers.ApplicationContext import java.util.UUID import javax.inject.Inject import org.oxycblt.auxio.R import org.oxycblt.auxio.settings.Settings -import org.oxycblt.musikr.fs.MusicLocation +import org.oxycblt.musikr.fs.Location +import org.oxycblt.musikr.fs.OpenedLocation import timber.log.Timber as L /** @@ -37,7 +39,7 @@ interface MusicSettings : Settings { /** The current library revision. */ var revision: UUID? /** The locations of music to load. */ - var musicLocations: List + var musicLocations: List /** Whether to exclude non-music audio files from the music library. */ val excludeNonMusic: Boolean /** Whether to ignore hidden files and directories during music loading. */ @@ -74,17 +76,17 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - override var musicLocations: List + override var musicLocations: List get() { val locations = sharedPreferences.getString(getString(R.string.set_key_music_locations), null) ?: return emptyList() - return MusicLocation.existing(context, locations) + return locations.toOpenedLocations() } set(value) { sharedPreferences.edit { putString( - getString(R.string.set_key_music_locations), MusicLocation.toString(value)) + getString(R.string.set_key_music_locations), value.stringify()) commit() // Sometimes changing this setting just won't actually trigger the listener. // Only this one. No idea why. @@ -136,4 +138,49 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } } + + + private fun List.stringify(): String = + joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } + + private fun String.toOpenedLocations(): List = + splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri())?.open(context) } + + private inline fun String.splitEscaped(selector: (Char) -> Boolean): List { + val split = mutableListOf() + var currentString = "" + var i = 0 + + while (i < length) { + val a = get(i) + val b = getOrNull(i + 1) + + if (selector(a)) { + // Non-escaped separator, split the string here, making sure any stray whitespace + // is removed. + split.add(currentString) + currentString = "" + i++ + continue + } + + if (b != null && a == '\\' && selector(b)) { + // Is an escaped character, add the non-escaped variant and skip two + // characters to move on to the next one. + currentString += b + i += 2 + } else { + // Non-escaped, increment normally. + currentString += a + i++ + } + } + + if (currentString.isNotEmpty()) { + // Had an in-progress split string that is now terminated, add it. + split.add(currentString) + } + + return split + } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index 3a6ebe679..1331ac84b 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -25,21 +25,22 @@ import org.oxycblt.auxio.databinding.ItemMusicLocationBinding import org.oxycblt.auxio.list.recycler.DialogRecyclerView import org.oxycblt.auxio.util.context import org.oxycblt.auxio.util.inflater -import org.oxycblt.musikr.fs.MusicLocation +import org.oxycblt.musikr.fs.Location +import org.oxycblt.musikr.fs.OpenedLocation import timber.log.Timber as L /** - * [RecyclerView.Adapter] that manages a list of [MusicLocation] music directory instances. + * [RecyclerView.Adapter] that manages a list of [OpenedLocation] music directory instances. * * @param listener A [LocationAdapter.Listener] to bind interactions to. * @author Alexander Capehart (OxygenCobalt) */ class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { - private val _locations = mutableListOf() + private val _locations = mutableListOf() /** - * The current list of [MusicLocation]s, may not line up with [MusicLocation]s due to removals. + * The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to removals. */ - val locations: List = _locations + val locations: List = _locations override fun getItemCount() = locations.size @@ -50,11 +51,11 @@ class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter) { + fun addAll(locations: List) { L.d("Adding ${locations.size} locations") val oldLastIndex = locations.lastIndex _locations.addAll(locations) @@ -74,11 +75,11 @@ class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter, + val exclude: List +) + /** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ data class Storage( /** diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 29e5ff67f..d6d7ec477 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -26,7 +26,6 @@ import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart -import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.pipeline.EvaluateStep import org.oxycblt.musikr.pipeline.ExploreStep import org.oxycblt.musikr.pipeline.ExtractStep @@ -48,13 +47,13 @@ interface Musikr { /** * Start loading music from the given [locations] and the configuration provided earlier. * - * @param locations The [MusicLocation]s to search for music in. + * @param query The [Query] to load music from. * @param onProgress Optional callback to receive progress on the current status of the music * pipeline. Warning: These events will be rapid-fire. * @return A handle to the newly created library alongside further cleanup. */ suspend fun run( - locations: List, + query: Query, onProgress: suspend (IndexingProgress) -> Unit = {} ): LibraryResult @@ -71,6 +70,7 @@ interface Musikr { */ fun new(context: Context, storage: Storage, interpretation: Interpretation): Musikr = MusikrImpl( + context, storage, ExploreStep.from(context, storage, interpretation), ExtractStep.from(context, storage), @@ -97,7 +97,7 @@ sealed interface IndexingProgress { /** * Currently indexing and extracting tags from device music. * - * @param explored The amount of music currently found from the given [MusicLocation]s. + * @param explored The amount of music currently found from the given [Query]. * @param loaded The amount of music that has had metadata extracted and parsed. */ data class Songs(val loaded: Int, val explored: Int) : IndexingProgress @@ -111,13 +111,14 @@ sealed interface IndexingProgress { } private class MusikrImpl( + private val context: Context, private val storage: Storage, private val exploreStep: ExploreStep, private val extractStep: ExtractStep, private val evaluateStep: EvaluateStep ) : Musikr { override suspend fun run( - locations: List, + query: Query, onProgress: suspend (IndexingProgress) -> Unit ) = coroutineScope { val start = System.currentTimeMillis() @@ -125,7 +126,7 @@ private class MusikrImpl( var extractedCount = 0 val explored = exploreStep - .explore(locations) + .explore(query) .buffer(Channel.UNLIMITED) .onStart { onProgress(IndexingProgress.Songs(0, 0)) } .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt similarity index 50% rename from musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt rename to musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index 636d16c61..072c83890 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2024 Auxio Project - * MusicLocation.kt is part of Auxio. + * Location.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 @@ -24,49 +24,51 @@ import android.net.Uri import android.provider.DocumentsContract import org.oxycblt.musikr.fs.device.contentResolverSafe import org.oxycblt.musikr.fs.path.DocumentPathFactory -import org.oxycblt.musikr.util.splitEscaped -class MusicLocation private constructor(val uri: Uri, val path: Path) { - override fun equals(other: Any?) = other is MusicLocation && uri == other.uri +class Location private constructor(val uri: Uri, val path: Path) { + override fun equals(other: Any?) = other is Location && uri == other.uri override fun hashCode() = 31 * uri.hashCode() override fun toString(): String = uri.toString() - companion object { - fun new(context: Context, uri: Uri): MusicLocation? { - if (!DocumentsContract.isTreeUri(uri)) return null - val documentPathFactory = DocumentPathFactory.from(context) - val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null - val notPersisted = - context.contentResolverSafe.persistedUriPermissions.none { - it.uri == uri && it.isReadPermission && it.isWritePermission - } - if (notPersisted) { + fun open(context: Context): OpenedLocation? { + if (isUnopened(context, uri)) { + try { context.contentResolverSafe.takePersistableUriPermission( uri, - Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + ) + } catch (e: Exception) { + // Not fully sure what happens if I'm disallowed to take the permission, + // check for both circumstances (error or no-op) + return null } - return MusicLocation(uri, path) + + if (isUnopened(context, uri)) { + return null + } + } + return OpenedLocation(uri, path) + } + + private fun isUnopened(context: Context, uri: Uri) = + context.contentResolverSafe.persistedUriPermissions.none { + it.uri == uri && it.isReadPermission && it.isWritePermission } - fun existing(context: Context, uri: Uri): MusicLocation? { - val documentPathFactory = DocumentPathFactory.from(context) + companion object { + fun from(context: Context, uri: Uri): Location? { if (!DocumentsContract.isTreeUri(uri)) return null - val notPersisted = - context.contentResolverSafe.persistedUriPermissions.none { - it.uri == uri && it.isReadPermission && it.isWritePermission - } - if (notPersisted) return null + val documentPathFactory = DocumentPathFactory.from(context) val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null - return MusicLocation(uri, path) - } - - fun toString(list: List) = - list.joinToString(";") { it.uri.toString().replace(";", "\\;") } - - fun existing(context: Context, string: String): List { - return string.splitEscaped { it == ';' }.mapNotNull { existing(context, Uri.parse(it)) } + return Location(uri, path) } } } + +class OpenedLocation internal constructor(val uri: Uri, val path: Path) { + override fun equals(other: Any?) = other is OpenedLocation && uri == other.uri && path == other.path + override fun hashCode() = 31 * uri.hashCode() + path.hashCode() + override fun toString(): String = uri.toString() +} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/README.md b/musikr/src/main/java/org/oxycblt/musikr/fs/README.md index d73231152..b7b659e8d 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/README.md +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/README.md @@ -8,7 +8,7 @@ The filesystem package provides abstraction layers for accessing music files on ### Core Types -**MusicLocation** (`MusicLocation.kt`) +**OpenedLocation** (`OpenedLocation.kt`) - Represents a location to search for music - Can be a device storage location or content URI @@ -50,7 +50,7 @@ The filesystem package provides abstraction layers for accessing music files on ## Usage Flow -1. User provides `MusicLocation`s to scan +1. User provides `OpenedLocation`s to scan 2. `DeviceFS` traverses these locations 3. `FileTreeCache` optimizes subsequent scans 4. Discovered files are passed to the pipeline for processing diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index c0c27f5ae..139ae0078 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -33,6 +33,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map @@ -40,15 +41,20 @@ import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.takeWhile -import org.oxycblt.musikr.fs.MusicLocation +import kotlinx.coroutines.flow.transform +import org.oxycblt.musikr.Query +import org.oxycblt.musikr.fs.Location +import org.oxycblt.musikr.fs.OpenedLocation import org.oxycblt.musikr.fs.Path internal interface DeviceFS { - fun explore(locations: Flow, fileTree: FileTree): Flow + fun explore(query: Query, fileTree: FileTree): Flow companion object { - fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.contentResolverSafe, withHidden) + fun from( + context: Context, + withHidden: Boolean + ): DeviceFS = DeviceFSImpl(context.contentResolverSafe, withHidden) } } @@ -58,10 +64,10 @@ private class DeviceFSImpl( ) : DeviceFS { private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) - override fun explore(locations: Flow, fileTree: FileTree) = - locations.mapNotNull { location -> queryRoot(location, fileTree) } + override fun explore(query: Query, fileTree: FileTree) = + query.source.asFlow().mapNotNull { location -> queryRoot(location, fileTree, query.exclude) } - private suspend fun queryRoot(location: MusicLocation, fileTree: FileTree): DeviceDirectory? { + private suspend fun queryRoot(location: OpenedLocation, fileTree: FileTree, exclude: List): DeviceDirectory? { val treeDocumentId = DocumentsContract.getTreeDocumentId(location.uri) val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId) val modifiedMs = @@ -76,7 +82,7 @@ private class DeviceFSImpl( if (modifiedMs == null) { return null } - return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree) + return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree, exclude) } private suspend fun query( @@ -85,13 +91,14 @@ private class DeviceFSImpl( path: Path, modifiedMs: Long, parent: DeviceDirectory?, - fileTree: FileTree + fileTree: FileTree, + exclude: List ): DeviceDirectory = coroutineScope { val uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) val cached = fileTree.queryDirectory(uri) if (cached != null && cached.modifiedMs == modifiedMs) { return@coroutineScope hydrateCached( - cached = cached, parentDir = parent, path = path, fileTree = fileTree) + cached = cached, parentDir = parent, path = path, fileTree = fileTree, exclude) } val dir = DeviceDirectoryImpl( @@ -145,6 +152,19 @@ private class DeviceFSImpl( val lastModified = cursor.getLong(lastModifiedIndex) if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + // Check if this directory should be excluded + + val shouldExclude = + exclude.any { excluded -> + // Check if the current path matches the excluded path + // exactly + excluded.path.volume == newPath.volume && + excluded.path.components == newPath.components + } + if (shouldExclude) { + continue + } + val subdir = query( rootUri = rootUri, @@ -152,7 +172,8 @@ private class DeviceFSImpl( path = newPath, modifiedMs = modifiedMs, parent = dir, - fileTree = fileTree) + fileTree = fileTree, + exclude = exclude) childSubdirUris.add(subdir.uri.toString()) emit(StreamedFile.More(subdir)) } else { @@ -202,7 +223,8 @@ private class DeviceFSImpl( cached: CachedDirectory, parentDir: DeviceDirectory?, path: Path, - fileTree: FileTree + fileTree: FileTree, + exclude: List ): DeviceDirectory = coroutineScope { val dir = DeviceDirectoryImpl( @@ -215,18 +237,30 @@ private class DeviceFSImpl( flow { emitAll( merge( - cached.subdirUris.asFlow().map { subdirUriString -> - val subdirUri = subdirUriString.toUri() - val cachedSubdir = - requireNotNull(fileTree.queryDirectory(subdirUri)) { - "No cached subdir for $subdirUri, malformed cache! Rescan needed." + cached.subdirUris + .asFlow() + .transform { subdirUriString -> + val subdirUri = subdirUriString.toUri() + val cachedSubdir = + requireNotNull(fileTree.queryDirectory(subdirUri)) { + "No cached subdir for $subdirUri, malformed cache! Rescan needed." + } + val subdirPath = dir.path.file(cachedSubdir.name) + + val shouldExclude = + exclude.any { excluded -> + excluded.path.volume == subdirPath.volume && + excluded.path.components == + subdirPath.components + } + + if (shouldExclude) { + return@transform } - hydrateCached( - cachedSubdir, - dir, - dir.path.file(cachedSubdir.name), - fileTree) - }, + + emit(hydrateCached(cachedSubdir, dir, subdirPath, fileTree, exclude)) + } + .filterNotNull(), cached.fileUris.asFlow().map { val cachedFile = requireNotNull(fileTree.queryFile(it.toUri())) DeviceFile( diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 32caf0747..0874dcdba 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -34,6 +34,7 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onCompletion import org.oxycblt.musikr.Interpretation +import org.oxycblt.musikr.Query import org.oxycblt.musikr.Storage import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.CacheResult @@ -41,7 +42,7 @@ import org.oxycblt.musikr.cache.CachedSong import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.Covers -import org.oxycblt.musikr.fs.MusicLocation +import org.oxycblt.musikr.fs.OpenedLocation import org.oxycblt.musikr.fs.device.DeviceFS import org.oxycblt.musikr.fs.device.FileTreeCache import org.oxycblt.musikr.fs.device.flatten @@ -49,12 +50,14 @@ import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.m3u.M3U internal interface ExploreStep { - fun explore(locations: List): Flow + fun explore(query: Query): Flow companion object { fun from(context: Context, storage: Storage, interpretation: Interpretation): ExploreStep = ExploreStepImpl( - DeviceFS.from(context, interpretation.withHidden), + DeviceFS.from( + context = context, + withHidden = interpretation.withHidden), storage.cache, storage.covers, storage.fileTreeCache, @@ -70,12 +73,12 @@ private class ExploreStepImpl( private val storedPlaylists: StoredPlaylists ) : ExploreStep { @OptIn(ExperimentalCoroutinesApi::class) - override fun explore(locations: List): Flow { + override fun explore(query: Query): Flow { val addingMs = System.currentTimeMillis() val fileTree = fileTreeCache.read() return merge( deviceFS - .explore(locations.asFlow(), fileTree) + .explore(query, fileTree) .flatMapMerge { it.flatten() } .onCompletion { fileTree.write() } .filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md b/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md index ddbf500ce..3b2e09389 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md @@ -49,7 +49,7 @@ The `PipelineItem.kt` defines the data types that flow through the pipeline: ## Pipeline Flow ``` -MusicLocation → ExploreStep → ExtractStep → EvaluateStep → Library +OpenedLocation → ExploreStep → ExtractStep → EvaluateStep → Library ``` Data flows through the pipeline using Kotlin's Flow API, with extensive use of parallel processing and buffering to optimize performance. diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt index f5e9cbda8..a3b4a0e00 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt @@ -22,11 +22,11 @@ import android.content.Context import android.database.ContentObserver import android.os.Handler import android.os.Looper -import org.oxycblt.musikr.fs.MusicLocation +import org.oxycblt.musikr.fs.OpenedLocation internal class LocationObserver( private val context: Context, - private val location: MusicLocation, + private val location: OpenedLocation, private val listener: UpdateTracker.Callback ) : ContentObserver(Handler(Looper.getMainLooper())), Runnable { private val handler = Handler(Looper.getMainLooper()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt index 88a9dec98..a3e4f2b69 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt @@ -19,15 +19,15 @@ package org.oxycblt.musikr.track import android.content.Context -import org.oxycblt.musikr.fs.MusicLocation +import org.oxycblt.musikr.fs.OpenedLocation interface UpdateTracker { - fun track(locations: List) + fun track(locations: List) fun release() interface Callback { - fun onUpdate(location: MusicLocation) + fun onUpdate(location: OpenedLocation) } companion object { @@ -42,7 +42,7 @@ private class UpdateTrackerImpl( ) : UpdateTracker { private val observers = mutableListOf() - override fun track(locations: List) { + override fun track(locations: List) { release() observers.addAll(locations.map { LocationObserver(context, it, callback) }) } From 06127727943796c42051acc306d6fc92d7a6a3ed Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Fri, 30 May 2025 18:17:52 -0600 Subject: [PATCH 32/38] all: reformat --- .../oxycblt/auxio/music/MusicRepository.kt | 3 +- .../org/oxycblt/auxio/music/MusicSettings.kt | 4 +- .../auxio/music/locations/LocationAdapter.kt | 4 +- .../res/layout/dialog_music_locations.xml | 3 +- .../main/java/org/oxycblt/musikr/Config.kt | 6 +-- .../main/java/org/oxycblt/musikr/Musikr.kt | 48 +++++++++---------- .../java/org/oxycblt/musikr/fs/Location.kt | 8 ++-- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 27 +++++++---- .../oxycblt/musikr/pipeline/ExploreStep.kt | 5 +- 9 files changed, 53 insertions(+), 55 deletions(-) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index 61312fb90..7e774749b 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -400,8 +400,7 @@ constructor( val query = Query(source = locations, exclude = emptyList()) val storage = Storage(cache, covers, storedPlaylists, fileTreeCache) val interpretation = Interpretation(nameFactory, separators, withHidden) - val result = - Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress) + val result = Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress) // Music loading completed, update the revision right now so we re-use this work // later. musicSettings.revision = newRevision diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index b1a1a6d5e..d96c72624 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -85,8 +85,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } set(value) { sharedPreferences.edit { - putString( - getString(R.string.set_key_music_locations), value.stringify()) + putString(getString(R.string.set_key_music_locations), value.stringify()) commit() // Sometimes changing this setting just won't actually trigger the listener. // Only this one. No idea why. @@ -139,7 +138,6 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - private fun List.stringify(): String = joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index 1331ac84b..ee4b8d97b 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -25,7 +25,6 @@ import org.oxycblt.auxio.databinding.ItemMusicLocationBinding import org.oxycblt.auxio.list.recycler.DialogRecyclerView import org.oxycblt.auxio.util.context import org.oxycblt.auxio.util.inflater -import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.OpenedLocation import timber.log.Timber as L @@ -38,7 +37,8 @@ import timber.log.Timber as L class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { private val _locations = mutableListOf() /** - * The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to removals. + * The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to + * removals. */ val locations: List = _locations diff --git a/app/src/main/res/layout/dialog_music_locations.xml b/app/src/main/res/layout/dialog_music_locations.xml index 8f015dec3..10035eec0 100644 --- a/app/src/main/res/layout/dialog_music_locations.xml +++ b/app/src/main/res/layout/dialog_music_locations.xml @@ -16,4 +16,5 @@ app:layout_constraintTop_toBottomOf="@+id/locations_list_header" tools:listitem="@layout/item_music_location" /> - \ No newline at end of file + + diff --git a/musikr/src/main/java/org/oxycblt/musikr/Config.kt b/musikr/src/main/java/org/oxycblt/musikr/Config.kt index ec1092b68..1f8addbd5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Config.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Config.kt @@ -23,16 +23,12 @@ import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.MutableCovers import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.OpenedLocation -import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.device.FileTreeCache import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.tag.interpret.Naming import org.oxycblt.musikr.tag.interpret.Separators -data class Query( - val source: List, - val exclude: List -) +data class Query(val source: List, val exclude: List) /** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ data class Storage( diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index d6d7ec477..8c56bbc69 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -117,31 +117,29 @@ private class MusikrImpl( private val extractStep: ExtractStep, private val evaluateStep: EvaluateStep ) : Musikr { - override suspend fun run( - query: Query, - onProgress: suspend (IndexingProgress) -> Unit - ) = coroutineScope { - val start = System.currentTimeMillis() - var exploredCount = 0 - var extractedCount = 0 - val explored = - exploreStep - .explore(query) - .buffer(Channel.UNLIMITED) - .onStart { onProgress(IndexingProgress.Songs(0, 0)) } - .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } - val extracted = - extractStep - .extract(explored) - .buffer(Channel.UNLIMITED) - .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } - .onCompletion { onProgress(IndexingProgress.Indeterminate) } - val library = evaluateStep.evaluate(extracted) - Log.d( - "Musikr", - "Loaded ${library.songs.size} songs in ${System.currentTimeMillis() - start}ms") - LibraryResultImpl(storage, library) - } + override suspend fun run(query: Query, onProgress: suspend (IndexingProgress) -> Unit) = + coroutineScope { + val start = System.currentTimeMillis() + var exploredCount = 0 + var extractedCount = 0 + val explored = + exploreStep + .explore(query) + .buffer(Channel.UNLIMITED) + .onStart { onProgress(IndexingProgress.Songs(0, 0)) } + .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } + val extracted = + extractStep + .extract(explored) + .buffer(Channel.UNLIMITED) + .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } + .onCompletion { onProgress(IndexingProgress.Indeterminate) } + val library = evaluateStep.evaluate(extracted) + Log.d( + "Musikr", + "Loaded ${library.songs.size} songs in ${System.currentTimeMillis() - start}ms") + LibraryResultImpl(storage, library) + } } private class LibraryResultImpl( diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index 072c83890..dd4b56474 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -37,8 +37,7 @@ class Location private constructor(val uri: Uri, val path: Path) { try { context.contentResolverSafe.takePersistableUriPermission( uri, - Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION - ) + Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) } catch (e: Exception) { // Not fully sure what happens if I'm disallowed to take the permission, // check for both circumstances (error or no-op) @@ -68,7 +67,10 @@ class Location private constructor(val uri: Uri, val path: Path) { } class OpenedLocation internal constructor(val uri: Uri, val path: Path) { - override fun equals(other: Any?) = other is OpenedLocation && uri == other.uri && path == other.path + override fun equals(other: Any?) = + other is OpenedLocation && uri == other.uri && path == other.path + override fun hashCode() = 31 * uri.hashCode() + path.hashCode() + override fun toString(): String = uri.toString() } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 139ae0078..98498fc3e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -51,10 +51,8 @@ internal interface DeviceFS { fun explore(query: Query, fileTree: FileTree): Flow companion object { - fun from( - context: Context, - withHidden: Boolean - ): DeviceFS = DeviceFSImpl(context.contentResolverSafe, withHidden) + fun from(context: Context, withHidden: Boolean): DeviceFS = + DeviceFSImpl(context.contentResolverSafe, withHidden) } } @@ -65,9 +63,15 @@ private class DeviceFSImpl( private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) override fun explore(query: Query, fileTree: FileTree) = - query.source.asFlow().mapNotNull { location -> queryRoot(location, fileTree, query.exclude) } + query.source.asFlow().mapNotNull { location -> + queryRoot(location, fileTree, query.exclude) + } - private suspend fun queryRoot(location: OpenedLocation, fileTree: FileTree, exclude: List): DeviceDirectory? { + private suspend fun queryRoot( + location: OpenedLocation, + fileTree: FileTree, + exclude: List + ): DeviceDirectory? { val treeDocumentId = DocumentsContract.getTreeDocumentId(location.uri) val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId) val modifiedMs = @@ -82,7 +86,8 @@ private class DeviceFSImpl( if (modifiedMs == null) { return null } - return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree, exclude) + return query( + location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree, exclude) } private suspend fun query( @@ -159,7 +164,7 @@ private class DeviceFSImpl( // Check if the current path matches the excluded path // exactly excluded.path.volume == newPath.volume && - excluded.path.components == newPath.components + excluded.path.components == newPath.components } if (shouldExclude) { continue @@ -250,7 +255,7 @@ private class DeviceFSImpl( val shouldExclude = exclude.any { excluded -> excluded.path.volume == subdirPath.volume && - excluded.path.components == + excluded.path.components == subdirPath.components } @@ -258,7 +263,9 @@ private class DeviceFSImpl( return@transform } - emit(hydrateCached(cachedSubdir, dir, subdirPath, fileTree, exclude)) + emit( + hydrateCached( + cachedSubdir, dir, subdirPath, fileTree, exclude)) } .filterNotNull(), cached.fileUris.asFlow().map { diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 0874dcdba..9707ed14b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -42,7 +42,6 @@ import org.oxycblt.musikr.cache.CachedSong import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.Covers -import org.oxycblt.musikr.fs.OpenedLocation import org.oxycblt.musikr.fs.device.DeviceFS import org.oxycblt.musikr.fs.device.FileTreeCache import org.oxycblt.musikr.fs.device.flatten @@ -55,9 +54,7 @@ internal interface ExploreStep { companion object { fun from(context: Context, storage: Storage, interpretation: Interpretation): ExploreStep = ExploreStepImpl( - DeviceFS.from( - context = context, - withHidden = interpretation.withHidden), + DeviceFS.from(context = context, withHidden = interpretation.withHidden), storage.cache, storage.covers, storage.fileTreeCache, From a05460d54cd8bd9d6462bbdc56c835fccc068af6 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Fri, 30 May 2025 18:31:03 -0600 Subject: [PATCH 33/38] music: implement excluded dirs settings fields Authored by Claude Code. --- .../oxycblt/auxio/music/MusicRepository.kt | 3 ++- .../org/oxycblt/auxio/music/MusicSettings.kt | 26 ++++++++++++++++++- app/src/main/res/values/settings.xml | 1 + 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index 7e774749b..f83f202e9 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -388,6 +388,7 @@ constructor( Naming.simple() } val locations = musicSettings.musicLocations + val excludedLocations = musicSettings.excludedLocations val withHidden = musicSettings.withHidden val currentRevision = musicSettings.revision @@ -397,7 +398,7 @@ constructor( val fileTreeCache = if (withCache) FileTreeCache.from(context) else WriteOnlyFileTreeCache(FileTreeCache.from(context)) - val query = Query(source = locations, exclude = emptyList()) + val query = Query(source = locations, exclude = excludedLocations) val storage = Storage(cache, covers, storedPlaylists, fileTreeCache) val interpretation = Interpretation(nameFactory, separators, withHidden) val result = Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index d96c72624..8571f2681 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -40,6 +40,8 @@ interface MusicSettings : Settings { var revision: UUID? /** The locations of music to load. */ var musicLocations: List + /** The locations to exclude from music loading. */ + var excludedLocations: List /** Whether to exclude non-music audio files from the music library. */ val excludeNonMusic: Boolean /** Whether to ignore hidden files and directories during music loading. */ @@ -93,6 +95,21 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } + override var excludedLocations: List + get() { + val locations = + sharedPreferences.getString(getString(R.string.set_key_excluded_locations), null) + ?: return emptyList() + return locations.toLocations() + } + set(value) { + sharedPreferences.edit { + putString(getString(R.string.set_key_excluded_locations), value.stringifyLocations()) + commit() + listener?.onMusicLocationsChanged() + } + } + override val excludeNonMusic: Boolean get() = sharedPreferences.getBoolean(getString(R.string.set_key_exclude_non_music), true) @@ -120,7 +137,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont // TODO: Differentiate "hard reloads" (Need the cache) and "Soft reloads" // (just need to manipulate data) when (key) { - getString(R.string.set_key_music_locations) -> { + getString(R.string.set_key_music_locations), + getString(R.string.set_key_excluded_locations) -> { L.d("Dispatching music locations change") listener.onMusicLocationsChanged() } @@ -144,6 +162,12 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont private fun String.toOpenedLocations(): List = splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri())?.open(context) } + private fun List.stringifyLocations(): String = + joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } + + private fun String.toLocations(): List = + splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri()) } + private inline fun String.splitEscaped(selector: (Char) -> Boolean): List { val split = mutableListOf() var currentString = "" diff --git a/app/src/main/res/values/settings.xml b/app/src/main/res/values/settings.xml index 78cbeca29..5d334f7db 100644 --- a/app/src/main/res/values/settings.xml +++ b/app/src/main/res/values/settings.xml @@ -19,6 +19,7 @@ auxio_exclude_non_music auxio_with_hidden auxio_music_locations2 + auxio_excluded_locations auxio_separators auxio_auto_sort_names From 15c1c23b5c57a97a9275b5efa29c6766b4586055 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 31 May 2025 12:02:53 -0600 Subject: [PATCH 34/38] music: add excluded folders configuration Co-authored by Claude. --- .../org/oxycblt/auxio/music/MusicSettings.kt | 3 +- .../locations/ExcludedLocationAdapter.kt | 124 +++++++++++++++ .../locations/ExcludedLocationsDialog.kt | 144 ++++++++++++++++++ .../auxio/settings/RootPreferenceFragment.kt | 12 +- app/src/main/res/navigation/outer.xml | 8 + app/src/main/res/values/settings.xml | 1 + app/src/main/res/values/strings.xml | 2 + app/src/main/res/xml/preferences_root.xml | 5 + 8 files changed, 295 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 8571f2681..d1c57b8cf 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -104,7 +104,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } set(value) { sharedPreferences.edit { - putString(getString(R.string.set_key_excluded_locations), value.stringifyLocations()) + putString( + getString(R.string.set_key_excluded_locations), value.stringifyLocations()) commit() listener?.onMusicLocationsChanged() } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt new file mode 100644 index 000000000..754ce915a --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 Auxio Project + * ExcludedLocationAdapter.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.auxio.music.locations + +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import org.oxycblt.auxio.databinding.ItemMusicLocationBinding +import org.oxycblt.auxio.list.recycler.DialogRecyclerView +import org.oxycblt.auxio.util.context +import org.oxycblt.auxio.util.inflater +import org.oxycblt.musikr.fs.Location +import timber.log.Timber as L + +/** + * [RecyclerView.Adapter] that manages a list of [Location] excluded directory instances. + * + * @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. + * @author Alexander Capehart (OxygenCobalt) + */ +class ExcludedLocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { + private val _locations = mutableListOf() + /** + * The current list of [Location]s, may not line up with [Location]s due to + * removals. + */ + val locations: List = _locations + + override fun getItemCount() = locations.size + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = + ExcludedDirViewHolder.from(parent) + + override fun onBindViewHolder(holder: ExcludedDirViewHolder, position: Int) = + holder.bind(locations[position], listener) + + /** + * Add a [Location] to the end of the list. + * + * @param location The [Location] to add. + */ + fun add(location: Location) { + if (_locations.contains(location)) return + L.d("Adding $location") + _locations.add(location) + notifyItemInserted(_locations.lastIndex) + } + + /** + * Add a list of [Location] instances to the end of the list. + * + * @param locations The [Location] instances to add. + */ + fun addAll(locations: List) { + L.d("Adding ${locations.size} locations") + val oldLastIndex = _locations.size + _locations.addAll(locations) + notifyItemRangeInserted(oldLastIndex, locations.size) + } + + /** + * Remove a [Location] from the list. + * + * @param location The [Location] to remove. Must exist in the list. + */ + fun remove(location: Location) { + L.d("Removing $location") + val idx = _locations.indexOf(location) + _locations.removeAt(idx) + notifyItemRemoved(idx) + } + + /** A Listener for [ExcludedLocationAdapter] interactions. */ + interface Listener { + /** Called when the delete button on a directory item is clicked. */ + fun onRemoveLocation(location: Location) + } +} + +/** + * A [RecyclerView.Recycler] that displays a [Location]. Use [from] to create an instance. + * + * @author Alexander Capehart (OxygenCobalt) + */ +class ExcludedDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) : + DialogRecyclerView.ViewHolder(binding.root) { + /** + * Bind new data to this instance. + * + * @param location The new [Location] to bind. + * @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. + */ + fun bind(location: Location, listener: ExcludedLocationAdapter.Listener) { + binding.locationPath.text = location.path.resolve(binding.context) + binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } + } + + companion object { + /** + * Create a new instance. + * + * @param parent The parent to inflate this instance from. + * @return A new instance. + */ + fun from(parent: ViewGroup) = + ExcludedDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt new file mode 100644 index 000000000..16eb9b4e3 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2021 Auxio Project + * ExcludedLocationsDialog.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.auxio.music.locations + +import android.content.ActivityNotFoundException +import android.net.Uri +import android.os.Bundle +import android.view.LayoutInflater +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AlertDialog +import androidx.core.net.toUri +import androidx.recyclerview.widget.ConcatAdapter +import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject +import org.oxycblt.auxio.BuildConfig +import org.oxycblt.auxio.R +import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding +import org.oxycblt.auxio.music.MusicSettings +import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment +import org.oxycblt.auxio.util.showToast +import org.oxycblt.musikr.fs.Location +import timber.log.Timber as L + +/** + * Dialog that manages the excluded locations setting. + * + * @author Alexander Capehart (OxygenCobalt) + */ +@AndroidEntryPoint +class ExcludedLocationsDialog : + ViewBindingMaterialDialogFragment(), + ExcludedLocationAdapter.Listener, + NewLocationFooterAdapter.Listener { + private val locationAdapter = ExcludedLocationAdapter(this) + private val locationFooterAdapter = NewLocationFooterAdapter(this) + private var openDocumentTreeLauncher: ActivityResultLauncher? = null + @Inject lateinit var musicSettings: MusicSettings + + override fun onCreateBinding(inflater: LayoutInflater) = + DialogMusicLocationsBinding.inflate(inflater) + + override fun onConfigDialog(builder: AlertDialog.Builder) { + builder + .setTitle(R.string.set_excluded_locations) + .setNegativeButton(R.string.lbl_cancel, null) + .setPositiveButton(R.string.lbl_save) { _, _ -> + val newDirs = locationAdapter.locations + musicSettings.excludedLocations = newDirs + } + } + + override fun onBindingCreated( + binding: DialogMusicLocationsBinding, + savedInstanceState: Bundle? + ) { + openDocumentTreeLauncher = + registerForActivityResult( + ActivityResultContracts.OpenDocumentTree(), ::addDocumentTreeUriToDirs) + + binding.locationsRecycler.apply { + adapter = ConcatAdapter(locationAdapter, locationFooterAdapter) + itemAnimator = null + } + + val locations = + savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull { + Location.from(requireContext(), it.toUri()) + } ?: musicSettings.excludedLocations + + locationAdapter.addAll(locations) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putStringArrayList( + KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() })) + } + + override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { + super.onDestroyBinding(binding) + openDocumentTreeLauncher = null + binding.locationsRecycler.adapter = null + } + + override fun onRemoveLocation(location: Location) { + locationAdapter.remove(location) + } + + override fun onNewLocation() { + L.d("Opening launcher") + val launcher = + requireNotNull(openDocumentTreeLauncher) { "Document tree launcher was not available" } + + try { + launcher.launch(null) + } catch (e: ActivityNotFoundException) { + // User doesn't have a capable file manager. + requireContext().showToast(R.string.err_no_app) + } + } + + /** + * Add a Document Tree [Uri] chosen by the user to the current [Location]s. + * + * @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri] + * is null or not valid. + */ + private fun addDocumentTreeUriToDirs(uri: Uri?) { + if (uri == null) { + // A null URI means that the user left the file picker without picking a directory + L.d("No URI given (user closed the dialog)") + return + } + val context = requireContext() + val location = Location.from(context, uri) + + if (location != null) { + locationAdapter.add(location) + } else { + requireContext().showToast(R.string.err_bad_location) + } + } + + private companion object { + const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" + } +} \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt b/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt index 39a523c0c..791ba5b53 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt @@ -51,9 +51,15 @@ class RootPreferenceFragment : BasePreferenceFragment(R.xml.preferences_root) { } override fun onOpenDialogPreference(preference: WrappedDialogPreference) { - if (preference.key == getString(R.string.set_key_music_dirs)) { - findNavController() - .navigateSafe(RootPreferenceFragmentDirections.musicLocationsSettings()) + when (preference.key) { + getString(R.string.set_key_music_dirs) -> { + findNavController() + .navigateSafe(RootPreferenceFragmentDirections.musicLocationsSettings()) + } + getString(R.string.set_key_excluded_dirs) -> { + findNavController() + .navigateSafe(RootPreferenceFragmentDirections.excludedLocationsSettings()) + } } } diff --git a/app/src/main/res/navigation/outer.xml b/app/src/main/res/navigation/outer.xml index 0d15cbc8a..4f75640ec 100644 --- a/app/src/main/res/navigation/outer.xml +++ b/app/src/main/res/navigation/outer.xml @@ -36,6 +36,9 @@ + + auxio_rescan auxio_observing auxio_music_dirs + auxio_excluded_dirs auxio_cover_mode2 auxio_square_covers auxio_exclude_non_music diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0b5830db5..26d456242 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -315,6 +315,8 @@ Music folders Manage where music should be loaded from New folder + Excluded folders + Manage folders to exclude from music loading Refresh music Reload the music library, using cached tags when possible diff --git a/app/src/main/res/xml/preferences_root.xml b/app/src/main/res/xml/preferences_root.xml index 5c004cb4c..12f8fb94b 100644 --- a/app/src/main/res/xml/preferences_root.xml +++ b/app/src/main/res/xml/preferences_root.xml @@ -33,6 +33,11 @@ app:summary="@string/set_locations_desc" app:title="@string/set_locations" /> + + Date: Sat, 31 May 2025 13:36:49 -0600 Subject: [PATCH 35/38] music: share code between music/excluded locations Co-authored by Claude. --- .../org/oxycblt/auxio/music/MusicSettings.kt | 21 ++-- .../locations/ExcludedLocationAdapter.kt | 87 ++----------- .../locations/ExcludedLocationsDialog.kt | 117 +++--------------- .../auxio/music/locations/LocationAdapter.kt | 90 ++++---------- ...sicSourcesDialog.kt => LocationsDialog.kt} | 62 ++++------ .../music/locations/MusicLocationAdapter.kt | 55 ++++++++ .../music/locations/MusicLocationsDialog.kt | 64 ++++++++++ .../auxio/music/service/IndexingHolder.kt | 4 +- app/src/main/res/navigation/inner.xml | 2 +- app/src/main/res/navigation/outer.xml | 2 +- musikr/ARCHITECTURE.md | 2 +- .../main/java/org/oxycblt/musikr/Config.kt | 4 +- .../java/org/oxycblt/musikr/fs/Location.kt | 70 +++++------ .../main/java/org/oxycblt/musikr/fs/README.md | 4 +- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 4 +- .../org/oxycblt/musikr/pipeline/README.md | 2 +- .../oxycblt/musikr/track/LocationObserver.kt | 4 +- .../org/oxycblt/musikr/track/UpdateTracker.kt | 8 +- 18 files changed, 253 insertions(+), 349 deletions(-) rename app/src/main/java/org/oxycblt/auxio/music/locations/{MusicSourcesDialog.kt => LocationsDialog.kt} (69%) create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index d1c57b8cf..ac08842ce 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -27,7 +27,6 @@ import javax.inject.Inject import org.oxycblt.auxio.R import org.oxycblt.auxio.settings.Settings import org.oxycblt.musikr.fs.Location -import org.oxycblt.musikr.fs.OpenedLocation import timber.log.Timber as L /** @@ -39,9 +38,9 @@ interface MusicSettings : Settings { /** The current library revision. */ var revision: UUID? /** The locations of music to load. */ - var musicLocations: List + var musicLocations: List /** The locations to exclude from music loading. */ - var excludedLocations: List + var excludedLocations: List /** Whether to exclude non-music audio files from the music library. */ val excludeNonMusic: Boolean /** Whether to ignore hidden files and directories during music loading. */ @@ -78,7 +77,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - override var musicLocations: List + override var musicLocations: List get() { val locations = sharedPreferences.getString(getString(R.string.set_key_music_locations), null) @@ -95,12 +94,12 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - override var excludedLocations: List + override var excludedLocations: List get() { val locations = sharedPreferences.getString(getString(R.string.set_key_excluded_locations), null) ?: return emptyList() - return locations.toLocations() + return locations.toUnopenedLocations() } set(value) { sharedPreferences.edit { @@ -157,17 +156,17 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - private fun List.stringify(): String = + private fun List.stringify(): String = joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } - private fun String.toOpenedLocations(): List = - splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri())?.open(context) } + private fun String.toOpenedLocations(): List = + splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) } private fun List.stringifyLocations(): String = joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } - private fun String.toLocations(): List = - splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri()) } + private fun String.toUnopenedLocations(): List = + splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri()) } private inline fun String.splitEscaped(selector: (Char) -> Boolean): List { val split = mutableListOf() diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt index 754ce915a..4ad1f384f 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt @@ -18,98 +18,29 @@ package org.oxycblt.auxio.music.locations -import android.view.View import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView import org.oxycblt.auxio.databinding.ItemMusicLocationBinding -import org.oxycblt.auxio.list.recycler.DialogRecyclerView -import org.oxycblt.auxio.util.context import org.oxycblt.auxio.util.inflater import org.oxycblt.musikr.fs.Location -import timber.log.Timber as L /** - * [RecyclerView.Adapter] that manages a list of [Location] excluded directory instances. + * [LocationAdapter] that manages a list of [Location.Unopened] excluded directory instances. * - * @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. + * @param listener A [LocationAdapter.Listener] to bind interactions to. * @author Alexander Capehart (OxygenCobalt) */ -class ExcludedLocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { - private val _locations = mutableListOf() - /** - * The current list of [Location]s, may not line up with [Location]s due to - * removals. - */ - val locations: List = _locations - - override fun getItemCount() = locations.size - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - ExcludedDirViewHolder.from(parent) - - override fun onBindViewHolder(holder: ExcludedDirViewHolder, position: Int) = - holder.bind(locations[position], listener) - - /** - * Add a [Location] to the end of the list. - * - * @param location The [Location] to add. - */ - fun add(location: Location) { - if (_locations.contains(location)) return - L.d("Adding $location") - _locations.add(location) - notifyItemInserted(_locations.lastIndex) - } - - /** - * Add a list of [Location] instances to the end of the list. - * - * @param locations The [Location] instances to add. - */ - fun addAll(locations: List) { - L.d("Adding ${locations.size} locations") - val oldLastIndex = _locations.size - _locations.addAll(locations) - notifyItemRangeInserted(oldLastIndex, locations.size) - } - - /** - * Remove a [Location] from the list. - * - * @param location The [Location] to remove. Must exist in the list. - */ - fun remove(location: Location) { - L.d("Removing $location") - val idx = _locations.indexOf(location) - _locations.removeAt(idx) - notifyItemRemoved(idx) - } - - /** A Listener for [ExcludedLocationAdapter] interactions. */ - interface Listener { - /** Called when the delete button on a directory item is clicked. */ - fun onRemoveLocation(location: Location) - } +class ExcludedLocationAdapter(listener: LocationAdapter.Listener) : LocationAdapter(listener) { + override fun createViewHolder(parent: ViewGroup): LocationViewHolder = + ExcludedLocationViewHolder.from(parent) } /** - * A [RecyclerView.Recycler] that displays a [Location]. Use [from] to create an instance. + * A [LocationViewHolder] that displays a [Location.Unopened]. Use [from] to create an instance. * * @author Alexander Capehart (OxygenCobalt) */ -class ExcludedDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) : - DialogRecyclerView.ViewHolder(binding.root) { - /** - * Bind new data to this instance. - * - * @param location The new [Location] to bind. - * @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. - */ - fun bind(location: Location, listener: ExcludedLocationAdapter.Listener) { - binding.locationPath.text = location.path.resolve(binding.context) - binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } - } +class ExcludedLocationViewHolder private constructor(binding: ItemMusicLocationBinding) : + LocationViewHolder(binding) { companion object { /** @@ -119,6 +50,6 @@ class ExcludedDirViewHolder private constructor(private val binding: ItemMusicLo * @return A new instance. */ fun from(parent: ViewGroup) = - ExcludedDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + ExcludedLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) } } \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt index 16eb9b4e3..7c031b236 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt @@ -18,25 +18,14 @@ package org.oxycblt.auxio.music.locations -import android.content.ActivityNotFoundException +import android.content.Context import android.net.Uri -import android.os.Bundle -import android.view.LayoutInflater -import androidx.activity.result.ActivityResultLauncher -import androidx.activity.result.contract.ActivityResultContracts -import androidx.appcompat.app.AlertDialog -import androidx.core.net.toUri -import androidx.recyclerview.widget.ConcatAdapter import dagger.hilt.android.AndroidEntryPoint -import javax.inject.Inject import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R -import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding import org.oxycblt.auxio.music.MusicSettings -import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment -import org.oxycblt.auxio.util.showToast import org.oxycblt.musikr.fs.Location -import timber.log.Timber as L +import javax.inject.Inject /** * Dialog that manages the excluded locations setting. @@ -44,101 +33,31 @@ import timber.log.Timber as L * @author Alexander Capehart (OxygenCobalt) */ @AndroidEntryPoint -class ExcludedLocationsDialog : - ViewBindingMaterialDialogFragment(), - ExcludedLocationAdapter.Listener, - NewLocationFooterAdapter.Listener { - private val locationAdapter = ExcludedLocationAdapter(this) - private val locationFooterAdapter = NewLocationFooterAdapter(this) - private var openDocumentTreeLauncher: ActivityResultLauncher? = null - @Inject lateinit var musicSettings: MusicSettings +class ExcludedLocationsDialog : LocationsDialog() { + override val locationAdapter = ExcludedLocationAdapter(this) - override fun onCreateBinding(inflater: LayoutInflater) = - DialogMusicLocationsBinding.inflate(inflater) + @Inject + override lateinit var musicSettings: MusicSettings - override fun onConfigDialog(builder: AlertDialog.Builder) { - builder - .setTitle(R.string.set_excluded_locations) - .setNegativeButton(R.string.lbl_cancel, null) - .setPositiveButton(R.string.lbl_save) { _, _ -> - val newDirs = locationAdapter.locations - musicSettings.excludedLocations = newDirs - } + override fun getDialogTitle(): Int = R.string.set_excluded_locations + + override fun getCurrentLocations(): List = musicSettings.excludedLocations + + override fun saveLocations(locations: List) { + musicSettings.excludedLocations = locations } - override fun onBindingCreated( - binding: DialogMusicLocationsBinding, - savedInstanceState: Bundle? - ) { - openDocumentTreeLauncher = - registerForActivityResult( - ActivityResultContracts.OpenDocumentTree(), ::addDocumentTreeUriToDirs) + override fun getPendingLocationsKey(): String = KEY_PENDING_EXCLUDED_LOCATIONS - binding.locationsRecycler.apply { - adapter = ConcatAdapter(locationAdapter, locationFooterAdapter) - itemAnimator = null - } - - val locations = - savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull { - Location.from(requireContext(), it.toUri()) - } ?: musicSettings.excludedLocations - - locationAdapter.addAll(locations) + override fun convertUriToLocation(uri: Uri): Location.Unopened? { + return Location.Unopened.from(requireContext(), uri) } - override fun onSaveInstanceState(outState: Bundle) { - super.onSaveInstanceState(outState) - outState.putStringArrayList( - KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() })) - } - - override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { - super.onDestroyBinding(binding) - openDocumentTreeLauncher = null - binding.locationsRecycler.adapter = null - } - - override fun onRemoveLocation(location: Location) { - locationAdapter.remove(location) - } - - override fun onNewLocation() { - L.d("Opening launcher") - val launcher = - requireNotNull(openDocumentTreeLauncher) { "Document tree launcher was not available" } - - try { - launcher.launch(null) - } catch (e: ActivityNotFoundException) { - // User doesn't have a capable file manager. - requireContext().showToast(R.string.err_no_app) - } - } - - /** - * Add a Document Tree [Uri] chosen by the user to the current [Location]s. - * - * @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri] - * is null or not valid. - */ - private fun addDocumentTreeUriToDirs(uri: Uri?) { - if (uri == null) { - // A null URI means that the user left the file picker without picking a directory - L.d("No URI given (user closed the dialog)") - return - } - val context = requireContext() - val location = Location.from(context, uri) - - if (location != null) { - locationAdapter.add(location) - } else { - requireContext().showToast(R.string.err_bad_location) - } + override fun createLocationFromUri(context: Context, uri: Uri): Location.Unopened? { + return Location.Unopened.from(context, uri) } private companion object { - const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" + const val KEY_PENDING_EXCLUDED_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" } } \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index ee4b8d97b..37e0abe48 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -1,6 +1,6 @@ /* - * Copyright (c) 2021 Auxio Project - * LocationAdapter.kt is part of Auxio. + * Copyright (c) 2024 Auxio Project + * BaseLocationAdapter.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 @@ -18,107 +18,59 @@ package org.oxycblt.auxio.music.locations -import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import org.oxycblt.auxio.databinding.ItemMusicLocationBinding import org.oxycblt.auxio.list.recycler.DialogRecyclerView import org.oxycblt.auxio.util.context -import org.oxycblt.auxio.util.inflater -import org.oxycblt.musikr.fs.OpenedLocation +import org.oxycblt.musikr.fs.Location import timber.log.Timber as L -/** - * [RecyclerView.Adapter] that manages a list of [OpenedLocation] music directory instances. - * - * @param listener A [LocationAdapter.Listener] to bind interactions to. - * @author Alexander Capehart (OxygenCobalt) - */ -class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { - private val _locations = mutableListOf() - /** - * The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to - * removals. - */ - val locations: List = _locations +abstract class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter>() { + private val _locations = mutableListOf() + val locations: List = _locations override fun getItemCount() = locations.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - MusicDirViewHolder.from(parent) + createViewHolder(parent) - override fun onBindViewHolder(holder: MusicDirViewHolder, position: Int) = + override fun onBindViewHolder(holder: LocationViewHolder, position: Int) = holder.bind(locations[position], listener) - /** - * Add a [OpenedLocation] to the end of the list. - * - * @param location The [OpenedLocation] to add. - */ - fun add(location: OpenedLocation) { + fun add(location: T) { if (_locations.contains(location)) return L.d("Adding $location") _locations.add(location) notifyItemInserted(_locations.lastIndex) } - /** - * Add a list of [OpenedLocation] instances to the end of the list. - * - * @param locations The [OpenedLocation] instances to add. - */ - fun addAll(locations: List) { + fun addAll(locations: List) { L.d("Adding ${locations.size} locations") - val oldLastIndex = locations.lastIndex + val oldSize = _locations.size _locations.addAll(locations) - notifyItemRangeInserted(oldLastIndex, locations.size) + notifyItemRangeInserted(oldSize, locations.size) } - /** - * Remove a [OpenedLocation] from the list. - * - * @param location The [OpenedLocation] to remove. Must exist in the list. - */ - fun remove(location: OpenedLocation) { + fun remove(location: T) { L.d("Removing $location") val idx = _locations.indexOf(location) _locations.removeAt(idx) notifyItemRemoved(idx) } - /** A Listener for [LocationAdapter] interactions. */ - interface Listener { - /** Called when the delete button on a directory item is clicked. */ - fun onRemoveLocation(location: OpenedLocation) + protected abstract fun createViewHolder(parent: ViewGroup): LocationViewHolder + + interface Listener { + fun onRemoveLocation(location: T) } } -/** - * A [RecyclerView.Recycler] that displays a [OpenedLocation]. Use [from] to create an instance. - * - * @author Alexander Capehart (OxygenCobalt) - */ -class MusicDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) : +abstract class LocationViewHolder(protected val binding: ItemMusicLocationBinding) : DialogRecyclerView.ViewHolder(binding.root) { - /** - * Bind new data to this instance. - * - * @param location The new [OpenedLocation] to bind. - * @param listener A [LocationAdapter.Listener] to bind interactions to. - */ - fun bind(location: OpenedLocation, listener: LocationAdapter.Listener) { + + fun bind(location: T, listener: LocationAdapter.Listener) { binding.locationPath.text = location.path.resolve(binding.context) binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } } - - companion object { - /** - * Create a new instance. - * - * @param parent The parent to inflate this instance from. - * @return A new instance. - */ - fun from(parent: View) = - MusicDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater)) - } -} +} \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt similarity index 69% rename from app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt rename to app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt index b506f84ae..c5847338d 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt @@ -1,6 +1,6 @@ /* - * Copyright (c) 2021 Auxio Project - * MusicSourcesDialog.kt is part of Auxio. + * Copyright (c) 2024 Auxio Project + * BaseLocationsDialog.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 @@ -27,43 +27,33 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.core.net.toUri import androidx.recyclerview.widget.ConcatAdapter -import dagger.hilt.android.AndroidEntryPoint -import javax.inject.Inject -import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding import org.oxycblt.auxio.music.MusicSettings import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment import org.oxycblt.auxio.util.showToast import org.oxycblt.musikr.fs.Location -import org.oxycblt.musikr.fs.OpenedLocation import timber.log.Timber as L -/** - * Dialog that manages the music locations setting. - * - * @author Alexander Capehart (OxygenCobalt) - */ -@AndroidEntryPoint -class MusicSourcesDialog : +abstract class LocationsDialog : ViewBindingMaterialDialogFragment(), - LocationAdapter.Listener, + LocationAdapter.Listener, NewLocationFooterAdapter.Listener { - private val locationAdapter = LocationAdapter(this) + protected abstract val locationAdapter: LocationAdapter private val locationFooterAdapter = NewLocationFooterAdapter(this) private var openDocumentTreeLauncher: ActivityResultLauncher? = null - @Inject lateinit var musicSettings: MusicSettings + abstract val musicSettings: MusicSettings override fun onCreateBinding(inflater: LayoutInflater) = DialogMusicLocationsBinding.inflate(inflater) override fun onConfigDialog(builder: AlertDialog.Builder) { builder - .setTitle(R.string.set_locations) + .setTitle(getDialogTitle()) .setNegativeButton(R.string.lbl_cancel, null) .setPositiveButton(R.string.lbl_save) { _, _ -> val newDirs = locationAdapter.locations - musicSettings.musicLocations = newDirs + saveLocations(newDirs) } } @@ -81,10 +71,9 @@ class MusicSourcesDialog : } val locations = - savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull { - val context = requireContext() - Location.from(context, it.toUri())?.open(context) - } ?: musicSettings.musicLocations + savedInstanceState?.getStringArrayList(getPendingLocationsKey())?.mapNotNull { + convertUriToLocation(it.toUri()) + } ?: getCurrentLocations() locationAdapter.addAll(locations) } @@ -92,7 +81,7 @@ class MusicSourcesDialog : override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putStringArrayList( - KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() })) + getPendingLocationsKey(), ArrayList(locationAdapter.locations.map { it.uri.toString() })) } override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { @@ -101,10 +90,6 @@ class MusicSourcesDialog : binding.locationsRecycler.adapter = null } - override fun onRemoveLocation(location: OpenedLocation) { - locationAdapter.remove(location) - } - override fun onNewLocation() { L.d("Opening launcher") val launcher = @@ -113,25 +98,17 @@ class MusicSourcesDialog : try { launcher.launch(null) } catch (e: ActivityNotFoundException) { - // User doesn't have a capable file manager. requireContext().showToast(R.string.err_no_app) } } - /** - * Add a Document Tree [Uri] chosen by the user to the current [OpenedLocation]s. - * - * @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri] - * is null or not valid. - */ private fun addDocumentTreeUriToDirs(uri: Uri?) { if (uri == null) { - // A null URI means that the user left the file picker without picking a locationectory L.d("No URI given (user closed the dialog)") return } val context = requireContext() - val location = Location.from(context, uri)?.open(context) + val location = createLocationFromUri(context, uri) if (location != null) { locationAdapter.add(location) @@ -140,7 +117,14 @@ class MusicSourcesDialog : } } - private companion object { - const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS" + override fun onRemoveLocation(location: T) { + locationAdapter.remove(location) } -} + + protected abstract fun getDialogTitle(): Int + protected abstract fun getCurrentLocations(): List + protected abstract fun saveLocations(locations: List) + protected abstract fun getPendingLocationsKey(): String + protected abstract fun convertUriToLocation(uri: Uri): T? + protected abstract fun createLocationFromUri(context: android.content.Context, uri: Uri): T? +} \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt new file mode 100644 index 000000000..af89cd172 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Auxio Project + * LocationAdapter.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.auxio.music.locations + +import android.view.ViewGroup +import org.oxycblt.auxio.databinding.ItemMusicLocationBinding +import org.oxycblt.auxio.util.inflater +import org.oxycblt.musikr.fs.Location + +/** + * [LocationAdapter] that manages a list of [Location.Opened] music directory instances. + * + * @param listener A [LocationAdapter.Listener] to bind interactions to. + * @author Alexander Capehart (OxygenCobalt) + */ +class MusicLocationAdapter(listener: LocationAdapter.Listener) : LocationAdapter(listener) { + override fun createViewHolder(parent: ViewGroup): LocationViewHolder = + MusicLocationViewHolder.from(parent) +} + +/** + * A [LocationViewHolder] that displays a [Location.Opened]. Use [from] to create an instance. + * + * @author Alexander Capehart (OxygenCobalt) + */ +class MusicLocationViewHolder private constructor(binding: ItemMusicLocationBinding) : + LocationViewHolder(binding) { + + companion object { + /** + * Create a new instance. + * + * @param parent The parent to inflate this instance from. + * @return A new instance. + */ + fun from(parent: ViewGroup) = + MusicLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt new file mode 100644 index 000000000..90bb054c4 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Auxio Project + * MusicSourcesDialog.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.auxio.music.locations + +import android.content.Context +import android.net.Uri +import dagger.hilt.android.AndroidEntryPoint +import org.oxycblt.auxio.BuildConfig +import org.oxycblt.auxio.R +import org.oxycblt.auxio.music.MusicSettings +import org.oxycblt.musikr.fs.Location +import javax.inject.Inject + +/** + * Dialog that manages the music locations setting. + * + * @author Alexander Capehart (OxygenCobalt) + */ +@AndroidEntryPoint +class MusicLocationsDialog : LocationsDialog() { + override val locationAdapter = MusicLocationAdapter(this) + + @Inject + override lateinit var musicSettings: MusicSettings + + override fun getDialogTitle(): Int = R.string.set_locations + + override fun getCurrentLocations(): List = musicSettings.musicLocations + + override fun saveLocations(locations: List) { + musicSettings.musicLocations = locations + } + + override fun getPendingLocationsKey(): String = KEY_PENDING_LOCATIONS + + override fun convertUriToLocation(uri: Uri): Location.Opened? { + val context = requireContext() + return Location.Unopened.from(context, uri)?.open(context) + } + + override fun createLocationFromUri(context: Context, uri: Uri): Location.Opened? { + return Location.Unopened.from(context, uri)?.open(context) + } + + private companion object { + const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS" + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt b/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt index 7d5226067..7788e10e8 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt @@ -36,7 +36,7 @@ import org.oxycblt.auxio.music.shim.UpdateTrackerFactory import org.oxycblt.auxio.playback.state.PlaybackStateManager import org.oxycblt.auxio.util.getSystemServiceCompat import org.oxycblt.musikr.MusicParent -import org.oxycblt.musikr.fs.OpenedLocation +import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.track.UpdateTracker import timber.log.Timber as L @@ -168,7 +168,7 @@ private constructor( } } - override fun onUpdate(location: OpenedLocation) { + override fun onUpdate(location: Location.Opened) { if (musicSettings.shouldBeObserving) { musicRepository.requestIndex(true) } diff --git a/app/src/main/res/navigation/inner.xml b/app/src/main/res/navigation/inner.xml index aa10ee2f9..61fcfd3a5 100644 --- a/app/src/main/res/navigation/inner.xml +++ b/app/src/main/res/navigation/inner.xml @@ -570,7 +570,7 @@ \ No newline at end of file diff --git a/app/src/main/res/navigation/outer.xml b/app/src/main/res/navigation/outer.xml index 4f75640ec..60d81d6b2 100644 --- a/app/src/main/res/navigation/outer.xml +++ b/app/src/main/res/navigation/outer.xml @@ -94,7 +94,7 @@ tools:layout="@layout/dialog_pre_amp" /> , val exclude: List) +data class Query(val source: List, val exclude: List) /** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ data class Storage( diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index dd4b56474..df25b2adc 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -25,52 +25,52 @@ import android.provider.DocumentsContract import org.oxycblt.musikr.fs.device.contentResolverSafe import org.oxycblt.musikr.fs.path.DocumentPathFactory -class Location private constructor(val uri: Uri, val path: Path) { +sealed class Location(val uri: Uri, val path: Path) { override fun equals(other: Any?) = other is Location && uri == other.uri override fun hashCode() = 31 * uri.hashCode() override fun toString(): String = uri.toString() - fun open(context: Context): OpenedLocation? { - if (isUnopened(context, uri)) { - try { - context.contentResolverSafe.takePersistableUriPermission( - uri, - Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) - } catch (e: Exception) { - // Not fully sure what happens if I'm disallowed to take the permission, - // check for both circumstances (error or no-op) - return null - } - + class Unopened private constructor(uri: Uri, path: Path) : Location(uri, path) { + fun open(context: Context): Opened? { if (isUnopened(context, uri)) { - return null + try { + context.contentResolverSafe.takePersistableUriPermission( + uri, + Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + } catch (e: Exception) { + // Not fully sure what happens if I'm disallowed to take the permission, + // check for both circumstances (error or no-op) + return null + } + + if (isUnopened(context, uri)) { + return null + } + } + return Opened(uri, path) + } + + private fun isUnopened(context: Context, uri: Uri) = + context.contentResolverSafe.persistedUriPermissions.none { + it.uri == uri && it.isReadPermission && it.isWritePermission + } + + companion object { + fun from(context: Context, uri: Uri): Unopened? { + if (!DocumentsContract.isTreeUri(uri)) return null + val documentPathFactory = DocumentPathFactory.from(context) + val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null + return Unopened(uri, path) } } - return OpenedLocation(uri, path) } - private fun isUnopened(context: Context, uri: Uri) = - context.contentResolverSafe.persistedUriPermissions.none { - it.uri == uri && it.isReadPermission && it.isWritePermission - } + class Opened internal constructor(uri: Uri, path: Path) : Location(uri, path) { + override fun equals(other: Any?) = + other is Opened && uri == other.uri && path == other.path - companion object { - fun from(context: Context, uri: Uri): Location? { - if (!DocumentsContract.isTreeUri(uri)) return null - val documentPathFactory = DocumentPathFactory.from(context) - val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null - return Location(uri, path) - } + override fun hashCode() = 31 * uri.hashCode() + path.hashCode() } } - -class OpenedLocation internal constructor(val uri: Uri, val path: Path) { - override fun equals(other: Any?) = - other is OpenedLocation && uri == other.uri && path == other.path - - override fun hashCode() = 31 * uri.hashCode() + path.hashCode() - - override fun toString(): String = uri.toString() -} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/README.md b/musikr/src/main/java/org/oxycblt/musikr/fs/README.md index b7b659e8d..6e0579566 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/README.md +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/README.md @@ -8,7 +8,7 @@ The filesystem package provides abstraction layers for accessing music files on ### Core Types -**OpenedLocation** (`OpenedLocation.kt`) +**Location.Opened** (`Location.Opened.kt`) - Represents a location to search for music - Can be a device storage location or content URI @@ -50,7 +50,7 @@ The filesystem package provides abstraction layers for accessing music files on ## Usage Flow -1. User provides `OpenedLocation`s to scan +1. User provides `Location.Opened`s to scan 2. `DeviceFS` traverses these locations 3. `FileTreeCache` optimizes subsequent scans 4. Discovered files are passed to the pipeline for processing diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 98498fc3e..55e36ecce 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -44,7 +44,7 @@ import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.flow.transform import org.oxycblt.musikr.Query import org.oxycblt.musikr.fs.Location -import org.oxycblt.musikr.fs.OpenedLocation +import org.oxycblt.musikr.fs.Location.Opened import org.oxycblt.musikr.fs.Path internal interface DeviceFS { @@ -68,7 +68,7 @@ private class DeviceFSImpl( } private suspend fun queryRoot( - location: OpenedLocation, + location: Location.Opened, fileTree: FileTree, exclude: List ): DeviceDirectory? { diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md b/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md index 3b2e09389..a03fa61f2 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md @@ -49,7 +49,7 @@ The `PipelineItem.kt` defines the data types that flow through the pipeline: ## Pipeline Flow ``` -OpenedLocation → ExploreStep → ExtractStep → EvaluateStep → Library +Location.Opened → ExploreStep → ExtractStep → EvaluateStep → Library ``` Data flows through the pipeline using Kotlin's Flow API, with extensive use of parallel processing and buffering to optimize performance. diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt index a3b4a0e00..29ae53bbf 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt @@ -22,11 +22,11 @@ import android.content.Context import android.database.ContentObserver import android.os.Handler import android.os.Looper -import org.oxycblt.musikr.fs.OpenedLocation +import org.oxycblt.musikr.fs.Location internal class LocationObserver( private val context: Context, - private val location: OpenedLocation, + private val location: Location.Opened, private val listener: UpdateTracker.Callback ) : ContentObserver(Handler(Looper.getMainLooper())), Runnable { private val handler = Handler(Looper.getMainLooper()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt index a3e4f2b69..48f22a1fb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt @@ -19,15 +19,15 @@ package org.oxycblt.musikr.track import android.content.Context -import org.oxycblt.musikr.fs.OpenedLocation +import org.oxycblt.musikr.fs.Location interface UpdateTracker { - fun track(locations: List) + fun track(locations: List) fun release() interface Callback { - fun onUpdate(location: OpenedLocation) + fun onUpdate(location: Location.Opened) } companion object { @@ -42,7 +42,7 @@ private class UpdateTrackerImpl( ) : UpdateTracker { private val observers = mutableListOf() - override fun track(locations: List) { + override fun track(locations: List) { release() observers.addAll(locations.map { LocationObserver(context, it, callback) }) } From 2c659523c1b0c638bee607e38637efc584d577cc Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 1 Jun 2025 06:19:04 -0600 Subject: [PATCH 36/38] all: reformat --- .../java/org/oxycblt/auxio/music/MusicSettings.kt | 3 ++- .../auxio/music/locations/ExcludedLocationAdapter.kt | 8 +++++--- .../auxio/music/locations/ExcludedLocationsDialog.kt | 10 +++++----- .../oxycblt/auxio/music/locations/LocationAdapter.kt | 10 +++++----- .../oxycblt/auxio/music/locations/LocationsDialog.kt | 12 +++++++++--- .../auxio/music/locations/MusicLocationAdapter.kt | 8 +++++--- .../auxio/music/locations/MusicLocationsDialog.kt | 7 +++---- .../src/main/java/org/oxycblt/musikr/fs/Location.kt | 6 +++--- 8 files changed, 37 insertions(+), 27 deletions(-) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index ac08842ce..8317f67d8 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -160,7 +160,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } private fun String.toOpenedLocations(): List = - splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) } + splitEscaped { it == ';' } + .mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) } private fun List.stringifyLocations(): String = joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt index 4ad1f384f..20e4a4be2 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt @@ -29,7 +29,8 @@ import org.oxycblt.musikr.fs.Location * @param listener A [LocationAdapter.Listener] to bind interactions to. * @author Alexander Capehart (OxygenCobalt) */ -class ExcludedLocationAdapter(listener: LocationAdapter.Listener) : LocationAdapter(listener) { +class ExcludedLocationAdapter(listener: LocationAdapter.Listener) : + LocationAdapter(listener) { override fun createViewHolder(parent: ViewGroup): LocationViewHolder = ExcludedLocationViewHolder.from(parent) } @@ -50,6 +51,7 @@ class ExcludedLocationViewHolder private constructor(binding: ItemMusicLocationB * @return A new instance. */ fun from(parent: ViewGroup) = - ExcludedLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + ExcludedLocationViewHolder( + ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt index 7c031b236..be70285d0 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt @@ -21,11 +21,11 @@ package org.oxycblt.auxio.music.locations import android.content.Context import android.net.Uri import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R import org.oxycblt.auxio.music.MusicSettings import org.oxycblt.musikr.fs.Location -import javax.inject.Inject /** * Dialog that manages the excluded locations setting. @@ -36,8 +36,7 @@ import javax.inject.Inject class ExcludedLocationsDialog : LocationsDialog() { override val locationAdapter = ExcludedLocationAdapter(this) - @Inject - override lateinit var musicSettings: MusicSettings + @Inject override lateinit var musicSettings: MusicSettings override fun getDialogTitle(): Int = R.string.set_excluded_locations @@ -58,6 +57,7 @@ class ExcludedLocationsDialog : LocationsDialog() { } private companion object { - const val KEY_PENDING_EXCLUDED_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" + const val KEY_PENDING_EXCLUDED_LOCATIONS = + BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index 37e0abe48..12614dcd3 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2024 Auxio Project - * BaseLocationAdapter.kt is part of Auxio. + * LocationAdapter.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 @@ -26,14 +26,14 @@ import org.oxycblt.auxio.util.context import org.oxycblt.musikr.fs.Location import timber.log.Timber as L -abstract class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter>() { +abstract class LocationAdapter(private val listener: Listener) : + RecyclerView.Adapter>() { private val _locations = mutableListOf() val locations: List = _locations override fun getItemCount() = locations.size - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - createViewHolder(parent) + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(parent) override fun onBindViewHolder(holder: LocationViewHolder, position: Int) = holder.bind(locations[position], listener) @@ -73,4 +73,4 @@ abstract class LocationViewHolder(protected val binding: ItemMusic binding.locationPath.text = location.path.resolve(binding.context) binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt index c5847338d..daeceb95f 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2024 Auxio Project - * BaseLocationsDialog.kt is part of Auxio. + * LocationsDialog.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 @@ -81,7 +81,8 @@ abstract class LocationsDialog : override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putStringArrayList( - getPendingLocationsKey(), ArrayList(locationAdapter.locations.map { it.uri.toString() })) + getPendingLocationsKey(), + ArrayList(locationAdapter.locations.map { it.uri.toString() })) } override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { @@ -122,9 +123,14 @@ abstract class LocationsDialog : } protected abstract fun getDialogTitle(): Int + protected abstract fun getCurrentLocations(): List + protected abstract fun saveLocations(locations: List) + protected abstract fun getPendingLocationsKey(): String + protected abstract fun convertUriToLocation(uri: Uri): T? + protected abstract fun createLocationFromUri(context: android.content.Context, uri: Uri): T? -} \ No newline at end of file +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt index af89cd172..cf950f963 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2021 Auxio Project - * LocationAdapter.kt is part of Auxio. + * MusicLocationAdapter.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 @@ -29,7 +29,8 @@ import org.oxycblt.musikr.fs.Location * @param listener A [LocationAdapter.Listener] to bind interactions to. * @author Alexander Capehart (OxygenCobalt) */ -class MusicLocationAdapter(listener: LocationAdapter.Listener) : LocationAdapter(listener) { +class MusicLocationAdapter(listener: LocationAdapter.Listener) : + LocationAdapter(listener) { override fun createViewHolder(parent: ViewGroup): LocationViewHolder = MusicLocationViewHolder.from(parent) } @@ -50,6 +51,7 @@ class MusicLocationViewHolder private constructor(binding: ItemMusicLocationBind * @return A new instance. */ fun from(parent: ViewGroup) = - MusicLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + MusicLocationViewHolder( + ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt index 90bb054c4..cca6e1778 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2021 Auxio Project - * MusicSourcesDialog.kt is part of Auxio. + * MusicLocationsDialog.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 @@ -21,11 +21,11 @@ package org.oxycblt.auxio.music.locations import android.content.Context import android.net.Uri import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R import org.oxycblt.auxio.music.MusicSettings import org.oxycblt.musikr.fs.Location -import javax.inject.Inject /** * Dialog that manages the music locations setting. @@ -36,8 +36,7 @@ import javax.inject.Inject class MusicLocationsDialog : LocationsDialog() { override val locationAdapter = MusicLocationAdapter(this) - @Inject - override lateinit var musicSettings: MusicSettings + @Inject override lateinit var musicSettings: MusicSettings override fun getDialogTitle(): Int = R.string.set_locations diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index df25b2adc..e27cbb9b9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -38,7 +38,8 @@ sealed class Location(val uri: Uri, val path: Path) { try { context.contentResolverSafe.takePersistableUriPermission( uri, - Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + Intent.FLAG_GRANT_READ_URI_PERMISSION or + Intent.FLAG_GRANT_WRITE_URI_PERMISSION) } catch (e: Exception) { // Not fully sure what happens if I'm disallowed to take the permission, // check for both circumstances (error or no-op) @@ -68,8 +69,7 @@ sealed class Location(val uri: Uri, val path: Path) { } class Opened internal constructor(uri: Uri, path: Path) : Location(uri, path) { - override fun equals(other: Any?) = - other is Opened && uri == other.uri && path == other.path + override fun equals(other: Any?) = other is Opened && uri == other.uri && path == other.path override fun hashCode() = 31 * uri.hashCode() + path.hashCode() } From 5d5d1b6af1245a42e879a60b3d7c21215187afdb Mon Sep 17 00:00:00 2001 From: "Weblate (bot)" Date: Sun, 1 Jun 2025 14:21:44 +0200 Subject: [PATCH 37/38] Translations update from Hosted Weblate (#1054) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Translated using Weblate (Arabic) Currently translated at 100.0% (316 of 316 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/ar/ * Translated using Weblate (Japanese) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/ja/ * Translated using Weblate (Japanese) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/ja/ * Translated using Weblate (Japanese) Currently translated at 100.0% (57 of 57 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/ja/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 47.2% (145 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/zh_Hant/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 49.1% (151 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/zh_Hant/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 49.1% (151 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/zh_Hant/ * Translated using Weblate (French) Currently translated at 99.3% (305 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/fr/ * Translated using Weblate (Bulgarian) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/bg/ * Translated using Weblate (Bulgarian) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/bg/ * Translated using Weblate (Georgian) Currently translated at 36.4% (112 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/ka/ * Translated using Weblate (Hebrew) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/he/ * Translated using Weblate (Hebrew) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/he/ * Translated using Weblate (Georgian) Currently translated at 36.4% (112 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/ka/ * Translated using Weblate (Portuguese) Currently translated at 99.6% (306 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/pt/ * Translated using Weblate (Turkish) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/tr/ * Translated using Weblate (Portuguese (Portugal)) Currently translated at 99.6% (306 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/pt_PT/ * Translated using Weblate (Lithuanian) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/lt/ * Translated using Weblate (Dutch) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/nl/ * Translated using Weblate (Dutch) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/nl/ * Translated using Weblate (Lithuanian) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/lt/ * Translated using Weblate (Hungarian) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/hu/ * Translated using Weblate (Hungarian) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/hu/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 52.1% (160 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/zh_Hant/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/zh_Hant/ * Translated using Weblate (Indonesian) Currently translated at 95.7% (294 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/id/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/zh_Hant/ * Translated using Weblate (Indonesian) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/id/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/zh_Hant/ * Translated using Weblate (Russian) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/ru/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/zh_Hant/ * Added translation using Weblate (Luri (Bakhtiari)) * Translated using Weblate (French) Currently translated at 99.6% (306 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/fr/ * Translated using Weblate (Azerbaijani) Currently translated at 42.0% (129 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/az/ * Translated using Weblate (Ukrainian) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/uk/ * Translated using Weblate (Luri (Bakhtiari)) Currently translated at 13.0% (40 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/bqi/ * Translated using Weblate (Luri (Bakhtiari)) Currently translated at 30.9% (95 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/bqi/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/zh_Hant/ * Translated using Weblate (Chinese (Traditional Han script)) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/zh_Hant/ * Translated using Weblate (Portuguese (Brazil)) Currently translated at 100.0% (59 of 59 strings) Translation: Auxio/Metadata Translate-URL: https://hosted.weblate.org/projects/auxio/metadata/pt_BR/ * Translated using Weblate (Finnish) Currently translated at 100.0% (307 of 307 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/fi/ * Translated using Weblate (German) Currently translated at 99.6% (308 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/de/ * Translated using Weblate (Spanish) Currently translated at 100.0% (309 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/es/ * Translated using Weblate (Portuguese (Brazil)) Currently translated at 100.0% (309 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/pt_BR/ * Translated using Weblate (Czech) Currently translated at 100.0% (309 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/cs/ * Translated using Weblate (German) Currently translated at 100.0% (309 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/de/ * Translated using Weblate (Italian) Currently translated at 100.0% (309 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/it/ * Translated using Weblate (Ukrainian) Currently translated at 100.0% (309 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/uk/ * Translated using Weblate (Chinese (Simplified Han script)) Currently translated at 100.0% (309 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/zh_Hans/ * Translated using Weblate (Finnish) Currently translated at 100.0% (309 of 309 strings) Translation: Auxio/Strings Translate-URL: https://hosted.weblate.org/projects/auxio/strings/fi/ --------- Co-authored-by: jonnysemon Co-authored-by: orasan Co-authored-by: Meteor2 Co-authored-by: Jinzhou Huang <2314662431@qq.com> Co-authored-by: Alban MARTINEZ Co-authored-by: trunars Co-authored-by: Demetre Ph Co-authored-by: elid Co-authored-by: Temuri Doghonadze Co-authored-by: ssantos Co-authored-by: polarwood Co-authored-by: Vaclovas Intas Co-authored-by: Baby Benefactor Co-authored-by: Zoltán Rózsa Co-authored-by: Unknownman820 Co-authored-by: kharrr69 Co-authored-by: Evgeniy Khramov <65224669+thejenja@users.noreply.github.com> Co-authored-by: Languages add-on Co-authored-by: TinAD17tin Co-authored-by: NecRaul Co-authored-by: Максим Горпиніч Co-authored-by: hosêyň abāspanā Co-authored-by: santiago046 Co-authored-by: Joonas Reinholm Co-authored-by: Ettore Atalan Co-authored-by: Eskuero <3skuero@gmail.com> Co-authored-by: Fjuro Co-authored-by: qwerty287 Co-authored-by: lorenzoch02 Co-authored-by: 大王叫我来巡山 --- app/src/main/res/values-ar/strings.xml | 5 +- app/src/main/res/values-az/strings.xml | 58 +-- app/src/main/res/values-bg/strings.xml | 21 +- app/src/main/res/values-bqi/strings.xml | 98 +++++ app/src/main/res/values-cs/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fi/strings.xml | 7 +- app/src/main/res/values-fr/strings.xml | 14 + app/src/main/res/values-hu/strings.xml | 25 +- app/src/main/res/values-in/strings.xml | 10 +- app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values-iw/strings.xml | 11 +- app/src/main/res/values-ja/strings.xml | 38 +- app/src/main/res/values-ka/strings.xml | 11 + app/src/main/res/values-lt/strings.xml | 48 +-- app/src/main/res/values-nl/strings.xml | 23 +- app/src/main/res/values-pt-rBR/strings.xml | 8 +- app/src/main/res/values-pt-rPT/strings.xml | 22 +- app/src/main/res/values-pt/strings.xml | 2 + app/src/main/res/values-ru/strings.xml | 5 +- app/src/main/res/values-tr/strings.xml | 5 +- app/src/main/res/values-uk/strings.xml | 4 +- app/src/main/res/values-zh-rCN/strings.xml | 2 + app/src/main/res/values-zh-rTW/strings.xml | 351 +++++++++++++----- .../metadata/android/bg/full_description.txt | 5 +- .../metadata/android/he/full_description.txt | 2 +- .../metadata/android/hu/full_description.txt | 35 +- .../metadata/android/in/full_description.txt | 24 ++ .../metadata/android/ja/full_description.txt | 4 +- .../android/nl-NL/full_description.txt | 2 +- .../android/pt-BR/full_description.txt | 36 +- .../android/zh-Hant/full_description.txt | 36 +- 33 files changed, 691 insertions(+), 229 deletions(-) create mode 100644 app/src/main/res/values-bqi/strings.xml create mode 100644 fastlane/metadata/android/in/full_description.txt diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index e703b6610..20860c540 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -205,7 +205,7 @@ فواصل القيم المتعددة أعد تحميل مكتبة الموسيقى عندما تتغير (يتطلب إشعار دائم) استثناء غير الموسيقى - الرمز التّعجبي (&) + امبارساند (&) الفاصلة (،) شرطة مائلة (/) أغطية الألبومات @@ -325,4 +325,7 @@ MPEG-4 تحتوي على %s Apple Lossless Audio Codec (ALAC) + كما هي + ضمّن ملفات الصوت المخفية (مثال: ذاكرة التخزين المؤقت) + ضمّن الملفات المخفية diff --git a/app/src/main/res/values-az/strings.xml b/app/src/main/res/values-az/strings.xml index 0bb44f396..2910f1354 100644 --- a/app/src/main/res/values-az/strings.xml +++ b/app/src/main/res/values-az/strings.xml @@ -8,41 +8,41 @@ Albomlar Albom Canlı albom - Qarışıq albom - Ep-lər - Seçmə - Seçmə - Canlı seçmə - Qarışıq seçmə + Remiks albom + EP-lər + Sinqlər + Sinql + Canlı sinql + Remiks sinql Kompilyasiya Kompilyasiyalar - Səs axını + Saundtrek Android üçün asan, səmərəli musiqi səsləndirici. Musiqi kitabxanası yoxlanılır Canlı EP EP Remiks EP - Səs axınları + Saundtreklər Yeni pleylist Remiks kompilyasiyası DJ Mikslər Canlı kompilyasiya Demo - Demos + Demolar Canlı Remikslər - Sənətkar - Sənətkarlar + İfaçı + İfaçılar Janr Mahnı - Qarışıq lentlər - Qarışıq lent + Miksteyplər + Miksteyp DJ Miks Janrlar Pleylist Pleylistlər Boş pleylist - Üzərində Görünür + Çıxış edir İdxal edilən pleylist Sil Axtarış @@ -54,15 +54,15 @@ Filtr Tarix Pleylisti idxal et - Pleylisti yenidən adlandır + Pleylistin adını dəyişdir Pleylist silinsin? Ad Mahnı sayı İdxal et İxrac et - Pleylist ixrac et + Pleylisti ixrac et Pleylistə əlavə et - Xüsusiyyətlərə bax + Detallara bax Nümunə sürəti Daha çox Səsləndirməni başlat @@ -70,39 +70,39 @@ Sıfırla Növbə Qarışdır - Sənətkara bax - Alboma keç + İfaçıya bax + Alboma bax Baxış Paylaş Səsləndir Çeşidləmə üsulu Göstəriş Azalan - Axın + Trek Əlavə edilən tarix Artan İndi səslənir Format Həcm - ReplayGain Axın Nizamlanması + ReplayGain Trek Nizamlanması ReplayGain Albom Nizamlanması Oldu Saxla Çeşidlə Tarazlayıcı Qarışdır - Növbəti səsləndirmə + Növbəti olaraq səsləndir Növbəyə əlavə et Mahnı detalları Yol - Hamısın Qarışdır + Hamısını qarışdır Bit sürəti Haqqında - Köçürüldü - Hesabat + Kopyalandı + Bildiriş et Xəta məlumatı Yaradıcı - Alexander Capehart + Aleksandr Keyphart Versiya Mənbə kodu Viki @@ -118,7 +118,7 @@ Dəstəkçilər Musiqi kitabxananız yüklənir… Musiqi kitabxananız dəyişikliklər üçün yoxlanılır… - Əks Əlaqə + Rəy bildir E-poçt göndər GitHub-da problem yarat Qovluqları seç @@ -127,6 +127,6 @@ Pleylist adı dəyişdirildi Pleylist idxal edildi Pleylist silindi - Səsləndirmə siyahısı yaradıldı + Pleylist yaradıldı Növbəyə əlavə edildi - \ No newline at end of file + diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index a3f06d667..b84e074b9 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -102,7 +102,7 @@ EP Версия Програмен код - Wiki + Уики Лицензи Библиотечна статистика Избор @@ -299,6 +299,21 @@ Стартирай възпроизвеждане Още Обратна връзка - Направете проблем в GitHub + Създайте проблем в GitHub Изпратете имейл - \ No newline at end of file + Изберете папки + MPEG-4, съдържащ %s + Вашите песни ще се показват тук. + Вашите албуми ще се показват тук. + Вашите плейлисти ще се показват тук. + Вашите артисти ще се показват тук. + Вашите жанрове ще се показват тук. + Apple Lossless Audio Codec (ALAC) + Неизвестен албум + Неизвестен + Включете скрити файлове + Включете аудио файлове, които са скрити (напр. .cache) + Спестете място + Както е + Нова папка + diff --git a/app/src/main/res/values-bqi/strings.xml b/app/src/main/res/values-bqi/strings.xml new file mode 100644 index 000000000..dd742de5d --- /dev/null +++ b/app/src/main/res/values-bqi/strings.xml @@ -0,0 +1,98 @@ + + + واجۊری کۊلیکسیون آرنگ + قپ ریت دوواره + دوبلگه یل ن پسند کۊنین + آرنگا + آرنگ + پوی آرنگا + آلبوما + آلبوم + آلبوم زنده + آلبوما کۊتال + آلبوم کۊتال + آلبوم کۊتال زنده + تک آرنگا + ریمیکس زنده + آرنگا هؽل + دمو + دمو یل + زنده + ریمیکسا + دیاری ابۊ + هونرمند + ژانر + نومگه پشک نۊ + نومگه پشک پتی + و من ٱووردن + و من ٱووردن نومگه پشک + دیجی میکس + آرنگ هونی بار ونی ابۊ + ی پشک کوننده آرنگ ساڌه وو منتقی سی ٱندروید + بار ونی آرنگ + آلبوم ریمیکس + آلبوم کۊتال ریمیکس + تک آرنگ زنده + دیجی میکسا + نومگه پشک و من ٱووڌه + هونرمندۉݩ + آرنگ هؽل + نومگه پشک + تک آرنگ + ژانرا + ویرگار + مودت زمووݩ + تئداڌ آرنگا + دیسک + ویرگار ٱوورده وابی + کتن کردن + کتن و ری + جهت + ری و روء + ری و لم + هیم سکو هونی پشک ابۊ + پشک + ٱووردن و نومگه پشک + راو و هونرمند + راو و آلبوم + نیشتن دووسمندیا + نیشتن + یک رسۊوی + دووسمندیا آرنگ + تور + فورمت + هندا + بیت ریت + نرخ نمووه بورداری + سامووݩ آرنگ ReplayGain + سامووݩ آلبوم ReplayGain + ناهاڌن پا پشک + خا + رڌ کردن + زفت کردن + سامووݩ دوواره + زبار + نوسخه + کود بونچک + پسند + دووسمندیا ختا + لف گیری وابی + هؽل کوݩ + لادراری + پوی + آرنگ + گوزارش + قلوه + نوم + ٱووردن و سف + تساڌۊفی + پشک نیایی + سف + اکولایزر + آمار کتاو هووه + ویکی + شیونیڌن پوی + تساڌۊفی + لایسنس + هؽزگرووݩ + diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index abd9a21c8..048660ceb 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -335,4 +335,6 @@ Zahrnout skryté soubory Zahrnout skryté zvukové soubory (např. .cache) Původní + Spravovat složky, ze kterých ze hudba nemá načítat + Vyloučené složky diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 1f05d2b5a..9dcfa5cc5 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -326,4 +326,6 @@ Unverändert Audio-Dateien einbeziehen, die versteckt sind (z. B. .cache) Versteckte Dateien einbeziehen + Ausgeschlossene Ordner + Ordner verwalten, aus denen keine Musik geladen wird diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index eec11937a..e93bbb83f 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -330,4 +330,6 @@ Original Incluir ficheros de audio ocultos (ej. .cache) Incluir ficheros ocultos + Directorios excluidos + Administrar exclusión de directorios diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 5a5993dc7..2ca7996e0 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -68,7 +68,7 @@ Toista tyylilajista Moniarvoerottimet Ohita äänitiedostot, jotka eivät ole musiikkia, kuten podcastit - Ampersand & + Ja-merkki (&) Pilkku (,) Plus (+) Puolipiste (;) @@ -313,4 +313,9 @@ Tyylilajisi tulevat näkymään tässä. Apple Lossless Audio Codec (ALAC) Säätä tilaa + Sisällytä piilotetut äänitiedostot (esim. .cache) + Sisällytä piilotetut tiedostot + Sellaisenaan + Poissuljetut kansiot + Hallinnoi kansioita, joista ei ladata musiikkia diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index fe5d67b14..1d452678b 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -312,4 +312,18 @@ Faire un ticket sur GitHub Envoyer un courriel Choisir des dossiers + Inconnu + MPEG-4 contenant %s + Vos chansons s\'afficheront ici. + Vos playlists vont s\'afficher ici. + Les genres musicaux vont s\'afficher ici. + Inclure les fichiers audios qui sont cachés (ex. .cache) + Vos albums vont s\'afficher ici. + Vos artistes vont s\'afficher ici. + Inclure les fichiers cachés + Nouveau dossier + Économiser de l\'espace + Album inconnu + Codec audio sans perte Apple (ALAC) + Telle quelle diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index b179042d2..09eabacee 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -200,7 +200,7 @@ Zene betöltése Zene könyvtár figyelése Lejátszás megállítása - Egyszerű, praktikus zenelejátszó androidra. + Egyszerű, praktikus zenelejátszó Androidra. Album Kislemezek Kislemez @@ -302,4 +302,25 @@ Lejátszási lista importálva Nem sikerült importálni a lejátszási listát ebből a fájlból Nem sikerült exportálni a lejátszási listát ebbe a fájlba - \ No newline at end of file + Válassz mappákat + Új mappa + Ismeretlen album + Itt fognak megjelenni a számaid. + Rejtett fájlok megjelenítése + Rejtett audió fájlok megjelenítése (pl. .cache) + Több + Küldj egy e-mailt + Itt fognak megjelenni az albumaid. + Itt fognak megjelenni az előadóid. + Itt fognak megjelenni a műfajaid. + Ahogy van + MPEG-4, amely tartalmazza a %s-t + Indítsd el a lejátszást + Elindítja az Auxio-t a korábban mentett állapot használatával. Ha nincs mentett állapot, akkor minden szám véletlenszerűen lejátszásra kerül. A lejátszás azonnal elindul.\n\nFIGYELEM: Légy óvatos a szolgáltatás vezérlésével, mert ha bezárod, majd újra próbálod használni, valószínűleg összeomlik az alkalmazás. + Itt fognak megjelenni a lejátszási listáid. + Helytakarékos + Apple veszteségmentes audió kodek (ALAC) + Ismeretlen + Visszajelzés + Hozz létre egy hibajegyet a GitHubon + diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index a62eee844..7838f51cf 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -298,4 +298,12 @@ Relatif Informasi kesalahan Sortir nama yang dimulai dengan nomor atau kata seperti \"the\" dengan benar (bekerja paling baik dengan lagu berbahasa Inggris) - \ No newline at end of file + Pilih folder + Lebih banyak + Lagu-lagu Anda akan muncul di sini. + Mulai pemutaran + Umpan balik + Buat masalah di GitHub + Kirim email + Memulai Auxio menggunakan status yang disimpan sebelumnya. Jika tidak ada status yang disimpan, semua lagu akan diputar secara acak. Pemutaran akan dimulai segera.\n\nPERINGATAN: Hati-hati saat mengontrol layanan ini, jika Anda menutupnya dan kemudian mencoba menggunakannya lagi, aplikasi kemungkinan besar akan mengalami kegagalan. + diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 223158f1a..46fc76520 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -328,4 +328,6 @@ Qualità originale Include file audio nascosti (per esempio in .cache) Includi file nascosti + Cartelle da escludere + Seleziona le cartelle da escludere dal caricamento della musica diff --git a/app/src/main/res/values-iw/strings.xml b/app/src/main/res/values-iw/strings.xml index 5bac78150..fddc6a372 100644 --- a/app/src/main/res/values-iw/strings.xml +++ b/app/src/main/res/values-iw/strings.xml @@ -310,4 +310,13 @@ תומכים יצירת דוח ב-GitHub שליחת מייל - \ No newline at end of file + השירים שלך יופיעו כאן. + האלבומים שלך יופיעו כאן. + האמנים שלך יופיעו כאן. + הפלייליסטים שלך יופיעו כאן. + כלול קבצים מוסתרים + הז\'אנרים שלך יופיעו כאן. + כלול קובצי אודיו מוסתרים (לדוגמה .cache) + כפי שהוא + חיסכון מקום + diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index b8e67554a..05b04f63c 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -134,7 +134,7 @@ バージョン ヘッドセット接続時に常時再生開始 (動作しない機種あり) ヘッドセット自動再生 - リプレイゲイン + 音量の均一化 すべての曲から再生 アルバムから再生 アーティストから再生 @@ -279,4 +279,38 @@ オフ このファイルからプレイリストをインポートできません このファイルにプレイリストをエクスポートできません - \ No newline at end of file + フォルダを選択 + そのまま + 新しいフォルダー + 不明なアルバム + %sを含むMPEG-4 + 曲を単独で再生 + 報告 + 順列 + 表示 + あなたの曲はここに表示されます + あなたのアルバムはここに表示されます + あなたのアーティストはここに表示されます + あなたのジャンルはここに表示されます + 選択 + 著者 + 空のブレイリスト + 画像の選択 + インポートされたプレイリスト + ReplayGainアルバム調整 + ReplayGainトラック調整 + GitHubで問題を報告する + プレイリストはここに表示されます + 非表示のファイルを含む + 非表示のオーディオファイルを含める(例:.cache) + 再開時に一時停止を記憶 + キューをスキップまたは編集しても、再生/一時停止を維持する + 不明 + スペースの節約 + アップルロスレスオーディオコーデック(ALAC) + さらに + 事前に保存した状態でAuxioを起動します。保存状態がない場合は、すべての曲がシャッフルされます。再生はすぐに開始されます\n\n警告: このサービスの操作には注意してください。このサービスを終了してから再度使用しようとすると、アプリがクラッシュする可能性があります + 並べ替える + 絶対的 + 相対的 + diff --git a/app/src/main/res/values-ka/strings.xml b/app/src/main/res/values-ka/strings.xml index 1e94b12ef..b0db011df 100644 --- a/app/src/main/res/values-ka/strings.xml +++ b/app/src/main/res/values-ka/strings.xml @@ -101,4 +101,15 @@ მუსიკის საქაღალდე ახალი საქაღალდე ბოლო სიმღერაზე გადასვლა + სტატისტიკა + ლიცენზიები + თქვენი დასაკრავი სიები გამოჩნდება აქ. + სიმღერების რაოდენობა: %d + ალბომების რაოდენობა: %d + არტისტების რაოდენობა: %d + დაამატე რიგში + გულშემატკივრები + თქვენი ჟანრები აქ გამოჩნდება. + სრული ხანგრძლივობა: %s + ჟანრების რაოდენობა: %d diff --git a/app/src/main/res/values-lt/strings.xml b/app/src/main/res/values-lt/strings.xml index f834bc17f..a87719701 100644 --- a/app/src/main/res/values-lt/strings.xml +++ b/app/src/main/res/values-lt/strings.xml @@ -44,11 +44,11 @@ Nustatymai Tema Naudok grynai juodą tamsią temą. - Paprastas, racionalus „Android“ muzikos leistuvė. + Paprasta, racionali „Android“ muzikos leistuvė. Muzikos įkėlimas Peržiūrėk ir valdyk muzikos įrašo perklausą Žanrai - Pakartoti + Kartoti Įkeliama muzika Įkeliamas tavo muzikos biblioteka… Bibliotekos statistika @@ -98,14 +98,14 @@ Arbatžolė Geltona Išplėstinis garso kodavimas (AAC) - Nemokamas be nuostolių garso kodekas (FLAC) + Nemokamas nenuostolingas garso kodekas (FLAC) %d daina %d dainos %d albumų %d dainų - Dinaminis + Dinaminė Pilka Oranžinė Ruda @@ -118,21 +118,21 @@ Visada pradėk leisti, kai ausinės yra prijungtos (gali neveikti visuose įrenginiuose). Ogg garsas Aleksandras Keiphartas (angl. Alexander Capehart) - Pageidauti takeliui + Pageidauti takelį Šis aplankas nepalaikomas. Leisti arba pristabdyti - Praleisti į kitą dainą + Praleisti į sekančią dainą Praleisti į paskutinę dainą Mikso juosta Misko juostos Bibliotekos skirtukai Keisk bibliotekos skirtukų matomumą ir tvarką. - Pageidauti albumui - Pageidauti albumui, jei vienas groja + Pageidauti albumą + Pageidauti albumą, jei vienas leidžiamas Programėlę nerasta, kuri galėtų atlikti šią užduotį. „Auxio“ piktograma Perkelti šią dainą - Perkelti šį skirtuką + Perkelti šią kortelę Nepavyko įkelti muzikos. %d diskas +%.1f dB @@ -149,7 +149,7 @@ Pauzė ant kartojimo Kai leidžiant iš bibliotekos Kai leidžiant iš elemento informacijos - Pašalinti aplanką + Šalinti aplanką Žanras Ieškok savo bibliotekoje… Ekvalaizeris @@ -159,9 +159,9 @@ Praleisti į kitą Automatinis ausinių leidimas Kartojimo režimas - Atidaryti eilę - Išvalyti paieškos užklausą - Pašalinti šią dainą + Atverti eilę + Valyti paieškos užklausą + Šalinti šią dainą Leisti iš visų dainų Leisti iš parodyto elemento Leisti iš albumo @@ -175,18 +175,18 @@ Įkėliamas tavo muzikos biblioteka… (%1$d/%2$d) Suasmeninti Įspėjimas: keičiant išankstinį stiprintuvą į didelę teigiamą reikšmę, kai kuriuose garso takeliuose gali atsirasti tarpų. - Albumo viršelis %s - Atlikėjo vaizdas %s + Albumo viršelis, skirtas „%s“ + Atlikėjo vaizdas, skirtas „%s“ Nėra leidžiamos muzikos Sustabdyk, kai daina kartojasi. Turinys Muzikos aplankai Atnaujinti muziką - Perkrauk muzikos biblioteką, naudojant podėlio žymes, kai įmanoma. + Įkelkite iš naujo muzikos biblioteką, naudojant podėlio žymes, kai įmanoma. Pasirinktinis įrašo perklausos juostos veiksmas „ReplayGain“ išankstinis stiprintuvas - Tvarkyk, kur muzika turėtų būti įkeliama iš. - Žanro vaizdas %s + Tvarkykite, kur muzika turėtų būti įkeliama iš. + Žanro vaizdas, skirtas „%s“ Įjungti arba išjungti maišymą %d takelis Keisti kartojimo režimą @@ -222,7 +222,7 @@ %d atlikėjų Perskenuoti muziką - Išvalyk žymių podėlį ir pilnai perkrauk muzikos biblioteką (lėčiau, bet labiau užbaigta). + Išvalykite žymių podėlį ir pilnai įkelkite iš naujo muzikos biblioteką (lėčiau, bet labiau užbaigta). %d pasirinkta Leisti iš žanro Viki @@ -237,13 +237,13 @@ Muzika Vaizdai Įrašo perklausa - Garso normalizavimas + Garsumo normalizavimas Mažėjantis Teisingai surūšiuok pavadinimus, kurie prasideda skaičiais arba žodžiais, tokiais kaip „the“ (geriausiai veikia su anglų kalbos muzika). Išmanusis rūšiavimas Grojaraštis Grojaraščiai - Grojaraščio vaizdas %s + Grojaraščio vaizdas, skirtas „%s“ Naujas grojaraštis Pridėti į grojaraštį Pridėta į grojaraštį @@ -299,7 +299,7 @@ Santykinis Naudoti „Windows“ suderinamus kelius Prisiminti pauzę - Išlaikyk leidimą / pristabdymą, kai praleidžiama arba redaguojama eilė. + Išlaikykite leidžiamą / pristabdymą praleidžiant arba redaguojant eilę. Išjungta Paleidžia „Auxio“ naudojant anksčiau išsaugotą būseną. Jei nėra išsaugotos būsenos, visos dainos bus išmaišytos. Įrašo perklausa bus pradėta iš karto. \n @@ -308,7 +308,7 @@ Daugiau Atsiliepimai Sukurti problemą svetainėje „GitHub“ - MPEG-4, kuriame yra %s + MPEG-4, turintis %s Nežinomas albumas Čia bus rodomos jūsų dainos. Čia bus rodomi jūsų albumai. @@ -318,7 +318,7 @@ Pasirinkti aplankus Siųsti el. laišką Naujas aplankas - „Apple“ be nuostolių garso kodekas (ALAC) + „Apple“ nenuostolingas garso kodekas (ALAC) Nežinomas Išsaugoti vietos Kaip yra diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index f61018fd3..516284fd1 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -304,4 +304,25 @@ Gebruik Windows-compatibele paden Rapporteer Afspeellijst geëxporteerd - \ No newline at end of file + Kies mappen + Zoals + Meer + Begint Auxio met de vorige redde staat. Als er geen gerede staat beschikbaar is, worden alle liedjes geschud. Playback zal onmiddellijk beginnen.\n\nWees voorzichtig met het controleren van deze dienst, als je het sluit en het weer probeert te gebruiken, zal je waarschijnlijk de app crashen. + Appel Lossless Audio Codec (ALAC) + Onbekend + Je nummers zullen hier worden weergegeven. + Je afspeellijsten zullen hier worden weergegeven. + Inclusief verborgen bestanden + Meld een probleem met GitHub + Stuur een e-mail + Je albums zullen hier worden weergegeven. + Je artiesten zullen hier worden weergegeven. + Je genres zullen hier worden weergegeven. + Onbekend album + MPEG-4 bevat %s + Ruimte besparen + Nieuwe map + Feedback + Afspelen + Inclusief audiobestanden die verborgen zijn (excl. .cache) + diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 4ce195e83..a63c687db 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -78,13 +78,13 @@ A pré-amplificação é aplicada em cima da normalização de volume Aviso: Alterar a pré-amplificação para um valor positivo muito alto pode resultar em picos de volume em algumas faixas. Pastas de música - Gerencia de onde as músicas devem ser carregadas + Gerencie de onde as músicas devem ser carregadas Falha ao carregar músicas Nenhum aplicativo encontrado que possa lidar com esta tarefa Esta pasta não é compatível Recarrega a biblioteca de músicas usando metadados salvos em cache quando possível Retroceder antes de voltar - Recarregar música + Recarregar músicas Retroceder a música antes de voltar para a anterior Um reprodutor de música simples e racional para Android. Carregando a sua biblioteca de músicas… @@ -223,7 +223,7 @@ %d artistas %d artistas - Re-escanear músicas + Reescanear músicas Limpa os metadados em cache e recarrega totalmente a biblioteca de música (lento, porém mais completo) Ocultar artistas colaboradores Mostrar apenas artistas que foram creditados diretamente no álbum (funciona melhor em músicas com metadados completos) @@ -328,4 +328,6 @@ Qualidade original Ignorar arquivos e pastas que estão ocultos (por exemplo, .cache) Ignorar arquivos ocultos + Gerencie as pastas a serem ignoradas no carregamento de músicas + Pastas ignoradas diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index b05e66b38..72392e852 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -305,6 +305,24 @@ Ajuste de ReplayGain do álbum Relativo Usar caminhos compatíveis com Windows - Inicia o Auxio utilizando o estado anteriormente guardado. Se não existir nenhum estado guardado, todas as músicas serão reproduzidas aleatoriamente. A reprodução começará imediatamente.\n\nAVISO: Tenha cuidado ao controlar este serviço. Se o fechar e tentar utilizá-lo novamente, provavelmente irá causar uma falha na aplicação. + Inicia o Auxio usando o estado gravado anteriormente. Se nenhum estado gravado estiver disponível, todas as músicas serão baralhadas. A reprodução começará imediatamente.\n\nAVISO: Tenha cuidado ao controlar este serviço, se fechá-lo e tentar usá-lo novamente, provavelmente irá travar a app. Iniciar reprodução - \ No newline at end of file + Escolha pastas + Álbum desconhecido + Nova pasta + Opinião + Ignorar ficheiros ocultos + Apple Lossless Audio Codec (ALAC) + Gravar espaço + MPEG-4 contendo %s + Desconhecido + Mais + As suas músicas aparecerão aqui. + Os seus álbuns aparecerão aqui. + Os seus artistas aparecerão aqui. + Os seus gêneros aparecerão aqui. + As suas listas de reprodução aparecerão aqui. + Ignorar ficheiros e pastas que estão ocultos (por exemplo, .cache) + Envie um e-mail + Crie um problema no GitHub + diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 2f95536f9..c411e4686 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -316,4 +316,6 @@ MPEG-4 contendo %s Apple Lossless Audio Codec (ALAC) Desconhecido + Ignorar ficheiros e pastas que estão ocultos (por exemplo, .cache) + Ignorar ficheiros ocultos diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 38f466406..66bc5b43c 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -330,4 +330,7 @@ Здесь будут отображаться ваши жанры. Экономия места Сообщить о проблеме на GitHub - \ No newline at end of file + Со скрытыми файлами + Показывать скрытые аудио (например, те, что в .cache) + Как есть + diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 5ea90a82e..e471b33a8 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -319,4 +319,7 @@ E-posta yolla Github\'da rapor aç Bu dosyaya bir oynatma listesi aktarılamıyor - \ No newline at end of file + Gizli dosyaları içer + Gizli olan ses dosyalarını içer (örn. .cache) + Olduğu gibi + diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index b9fafd43d..14aa79712 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -175,7 +175,7 @@ Ця папка не підтримується Невідомий виконавець Лаймовий - Амперсанд & + Амперсанд (&) Перейти до наступної пісні Ввімкніть або вимкніть перемішування Зупинити відтворення @@ -330,4 +330,6 @@ Як є Включати приховані файли Включати приховані аудіофайли (наприклад, .cache) + Виключені папки + Керування папками, які потрібно виключити із завантаження музики diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 27523b88e..92c1650ee 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -324,4 +324,6 @@ 保持原样 包括隐藏的文件 包括隐藏的音频文件(排除 .cache) + 管理要排除在音乐加载以外的文件夹 + 排除的文件夹 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index e52ff3e75..632e42f3a 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -6,158 +6,317 @@ 演出者 專輯 歌曲 - 所有歌曲 + 所有曲目 搜尋 - 篩選器 + 篩選 全部 排序 - 升序排列 + 升序 播放 隨機播放 - 播放面板 - 隊列 - 下一首播放 - 添加到隊列 - 已加入隊列 - 前往該歌手頁面 - 專輯 + 現正播放 + 佇列 + 播放下一首 + 新增至佇列 + 已新增至佇列 + 前往演出者 + 前往專輯 關於 版本 - 在 GitHub 上檢視 - 授權條款 + 原始碼 + 授權 設定 外觀 - 主題色調 - 強調色 + 主題 + 自動 淺色 深色 - 色彩樣式 + 主色調 音訊 - 行為 - 記住隨機播放 + 個人化 + 記憶隨機播放 音軌 %d - 播放/暫停 + 播放 / 暫停 - 搜尋音樂庫… + 正在搜尋媒體… - %d 歌曲 + %d 首歌曲 - %d 專輯 + %d 張專輯 載入音樂 - 檢測音樂庫 + 正在檢查媒體 格式 - 黑色主題 - 時長 + 黑色 + 長度 大小 - 位元率 - 取樣頻率 - 使用純黑暗色主題 + 位元速率 + 取樣率 + 使用純黑色主題 顯示 重設 - 正在載入你的音樂庫… - 流派 - 專輯封面 + 正在載入媒體… + 類型 + 專輯封面顯示 儲存 - 載入音樂中 - 一款為 android 打造的簡潔、理性的音樂播放器。 + 正在載入音樂 + 一個簡潔、理性的 Android 音樂播放器。 專輯 單曲 單曲 - 在更多的用戶界面元素上啟用圓角(需要專輯封面也要設定圓角) + 更多介面元素套用圓角(專輯封面需另外啟用) 演出者 - 新播放隊列 - 匯入播放隊列 + 新的播放清單 + 匯入播放清單 路徑 - 路徑樣式 - 支援者 - 已匯入播放隊列 - 已匯出播放隊列 + 路徑形式 + 協力 + 已匯入播放清單 + 已匯出播放清單 絕對 更多 - 錯誤信息 + 錯誤訊息 已複製 - 查看和控制音樂回放 - 歌曲屬性 + 檢視與控制音樂播放 + 歌曲資訊 隨機 歌曲 - 實況單曲 - 重新混音單曲 - 使用與Windows相容的路徑 - 已匯入的播放隊列 - 查看屬性 - 添加到播放隊列 - 播放隊列 - 播放隊列 + 現場單曲 + 混音單曲 + 使用與 Windows 相容的路徑 + 已匯入播放清單 + 檢視資訊 + 新增至播放清單 + 播放清單 + 播放清單 刪除 - 歌曲計數器 - Dj混音 - 刪除播放隊列? - 降序排列 - 報告 - 實況專輯 - 重新混音專輯 - 實況 - 重新混音 + 歌曲計數 + DJ 混音 + 刪除播放清單? + 降序 + 回報 + 現場專輯 + 混音專輯 + 現場 + 混音 日期 - 已重新命名播放隊列 - 已刪除播放隊列 + 已編輯播放清單 + 已刪除播放清單 重新命名 - 重新命名播放隊列 + 重新命名播放清單 編輯 名稱 - 碟片 + 唱片 音軌 - 添加日期 + 建立日期 排序依據 等化器 分享 - 隨機全部 + 全部隨機播放 取消 - 已建立播放隊列 - 開始回放 + 已建立播放清單 + 開始播放 匯入 匯出 - 匯出播放隊列 - 空播放隊列 - 查看 - 回報 - 正在監視你的音樂資料庫更改… - 自定義回放條動作 - 自定義通知動作 - 行為 - 控制如何載入音樂和圖片 - 圖片 + 匯出播放清單 + 空的播放清單 + 檢視 + 傳送意見 + 正在檢查媒體變更… + 自訂播放工具列動作 + 自訂通知動作 + 動作 + 設定載入音樂和影像方式 + 影像 關閉 - 配置聲音和回放行為 - 回放 + 配置音訊與播放動作 + 播放 關閉 - 偏好的音軌 - 捐贈此專案以將你的名字添加到此處! + 偏好音軌 + 贊助計畫並在此留下您的大名! 耳機自動播放 智慧排序 - 你的專輯將顯示在這裡. - 強制使用方形專輯封面 + 您的專輯將會顯示在這裡。 + 強制使用方形封面 自動重新載入 多參數分隔符 - 你的歌曲將顯示在這裡. - 你的演出者將顯示在這裡. - 你的類型將顯示在這裡. - 你的播放隊列將顯示在這裡. - 忽略不是音訊的檔案比如博客 - 已添加到播放隊列 + 您的歌曲將會顯示在這裡。 + 您的演出者將會顯示在這裡。 + 您的類型將會顯示在這裡。 + 您的播放清單將會顯示在這裡。 + 略過非音訊檔案,例如廣播服務 + 已新增至播放清單 圓角模式 - 排除非音樂 + 僅掃描音樂 音樂 - 自定義使用者介面控制和行為 - 更改媒體庫標籤的可見性和排序 - 儲存空間 - 記住暫停 - 媒體庫標籤 - 更改應用程式的主題和顏色 + 自訂介面控制與動作 + 變更媒體頁面顯示與排序 + 節省空間 + 記憶暫停 + 管理分頁 + 變更主題與色彩 + 選擇資料夾 + 循環模式 + 移至下一首 + 播放所有曲目 + 載入歌曲:%d + 正在載入您的媒體… (%1$d / %2$d) + 傳送電子郵件 + 相對 + 迷你專輯 + 迷你專輯 + 現場迷你專輯 + 混音迷你專輯 + 方向 + 重播增益音軌調整 + 現場合輯 + 移至上一首曲目前倒帶 + 音樂資料夾 + 無法將播放清單匯出至檔案 + 不支援這個資料夾 + 移動歌曲 + 移動分頁 + 清除搜尋紀錄 + %s 的播放清單相片 + 沒有專輯 + 深紫色 + 藍色 + 深藍色 + 青色 + 藍綠色 + + %d 位演出者 + + 媒體資料統計 + 從媒體庫播放時 + 從項目資訊播放時 + 播放顯示項目 + 播放新曲目時保留隨機播放 + 內容 + 配置符號時表示多個標籤數值 + 隨時掃描媒體資料變化(需要啟用持續性通知) + 分號 (;) + 逗號 (,) + 斜線號 (/) + 專輯封面僅顯示單一演出者(對標籤完善的媒體庫效果最佳) + 將所有專輯封面裁剪為 1:1 + 連接耳機時立即播放音樂 (可能不適用所有裝置) + 編輯或略過清單時保留播放狀態 + 重播增益模式 + 偏好專輯 + 重播增益前級擴大 + 播放期間為現有調整套用前級擴大 + 調整標籤 + 清除所有標籤快取並重新載入媒體 (完整但速度較慢) + 找不到可處理這項操作的應用程式 + 刪除歌曲 + Auxio 圖示 + 沒有音軌 + 沒有正在播放的音樂 + 粉色 + 黃色 + %1$s,%2$s + 載入演出者:%d + 載入類型:%d + 長度總計:%s + 音量標準化 + 正在編輯 %s + 沒有歌曲 + 加號 (+) + 重新整理音樂 + 停止播放 + 僅單曲播放時偏向專輯 + 綠色 + 深綠色 + 草綠色 + 合輯 + %d kbps + 未知專輯 + 進階音訊編碼 (AAC) + 橘色 + 動態 + 靛青色 + 試聽帶 + 混音 + 移至下一首 + 開啟佇列 + 灰色 + 重播增益專輯調整 + %s 的類型相片 + 載入專輯:%d + 移至上一首 + 專輯封面 + 載入音樂失敗 + %d Hz + 要刪除 %s 嗎?這項動作無法復原。 + MPEG-4 + 紫色 + 變更循環播放模式 + 準確排序以單字或數字為首的名稱(例如 The,對英文效果最佳) + 登場 + 播放專輯 + 與號 (&) + 播放單曲 + 新資料夾 + 刪除資料夾 + 合輯 + 確定 + 維基百科 + 選取項目 + 在 GitHub 張貼問題 + 贊助 + 隱藏項目 + 隱藏合作夥伴 + 以先前儲存的狀態啟動 Auxio。\n如果沒有可用存檔,將會立即隨機播放所有曲目。\n\n警告:請謹慎使用這項服務,停用後再次啟用可能會導致應用程式崩潰。 + 返回前倒帶 + 重播暫停 + 平衡 + 高畫質 + 啟用 / 停用隨機播放 + 沒有日期 + 選取影像 + 警告:啟用可能會誤判某些符號具有多重數值。您可在不需要的分隔符號前插入後斜線 (\\)。 + 混音合輯 + 原聲帶 + 原聲帶 + 混音帶 + 混音帶 + 試聽帶 + 作者 + 由 Alexander Capehart 開發 + 播放演出者 + 播放類型 + 讀取隱藏音訊檔案 (例如 .cache) + 原始 + 重播單曲時暫停 + 不調整標籤 + 警告:變更前級擴大可能會導致某些音軌達到上限. + 媒體庫 + 管理讀取音樂位置 + 盡可能透過標籤快取更新媒體 + 重新掃描音樂 + 無法從檔案匯入播放清單 + %s 的專輯封面 + %s 的演出者相片 + 未知演出者 + 未知類型 + 沒有唱片 + MPEG-1 + MPEG-4 封裝 %s + Ogg + 未知 + 紅色 + 棕色 + 已選取 %d + 唱片 %d + 播放清單 %d + +%.1f dB + -%.1f dB + 自由無損音訊編碼 (FLAC) + Apple 無損音訊編碼 (ALAC) diff --git a/fastlane/metadata/android/bg/full_description.txt b/fastlane/metadata/android/bg/full_description.txt index b959b6bc8..5369fc7f8 100644 --- a/fastlane/metadata/android/bg/full_description.txt +++ b/fastlane/metadata/android/bg/full_description.txt @@ -6,8 +6,7 @@ Auxio е локален музикален плейър с бърз, надеж - Snappy UI, извлечен от най-новите указания за Material Design - Убеден UX, който дава приоритет на лекотата на използване пред крайните случаи - Персонализирано поведение -- Поддръжка за номера на дискове, множество изпълнители, типове издания, -точни/оригинални дати, етикети за сортиране и др +- Поддръжка за номера на дискове, множество изпълнители, типове издания, точни/оригинални дати, етикети за сортиране и други - Усъвършенствана система за изпълнители, която обединява изпълнители и изпълнители на албуми - Управление на папки с SD карта - Надеждна функционалност за плейлисти @@ -22,4 +21,4 @@ Auxio е локален музикален плейър с бърз, надеж - Автоматично пускане на слушалки - Стилни джаджи, които автоматично се адаптират към техния размер - Напълно частно и офлайн -- Без заоблени корици на албуми (по подразбиране) +- Без заоблени корици на албуми (ако ги искате) diff --git a/fastlane/metadata/android/he/full_description.txt b/fastlane/metadata/android/he/full_description.txt index f36d22df6..d6900d037 100644 --- a/fastlane/metadata/android/he/full_description.txt +++ b/fastlane/metadata/android/he/full_description.txt @@ -1,4 +1,4 @@ -אוקסיו הוא נגן מוזיקה מקומי עם ממשק וחוויית משתמש מהיר ואמין, ובלי כל הפיצ'רים חסרי התועלת הרבים שנמצאים בנגני מוזיקה אחרים. בנוי על ספריות ניגון מדיה מודרניות, לאוקסיו יש תמיכה מיטבית בספריות ואיכות שמע נעלית בהשוואה ליישומים אחרים שמשתמשים בפונקציונליות אנדרואיד מיושנת. בקיצור, הוא פשוט מנגן מוזיקה. +אוקסיו הוא נגן מוזיקה מקומי עם ממשק וחוויית משתמש מהיר ואמין, ובלי כל הפיצ'רים חסרי התועלת הרבים שנמצאים בנגני מוזיקה אחרים. בנוי על ספריות ניגון מדיה מודרניות, לאוקסיו יש תמיכה מיטבית בספריות ואיכות שמע מקצועית בהשוואה ליישומים אחרים שמשתמשים בפונקציונליות אנדרואיד מיושנת. בקיצור, הוא פשוט מנגן מוזיקה. פיצ'רים diff --git a/fastlane/metadata/android/hu/full_description.txt b/fastlane/metadata/android/hu/full_description.txt index 3cb5b16cd..baf165f52 100644 --- a/fastlane/metadata/android/hu/full_description.txt +++ b/fastlane/metadata/android/hu/full_description.txt @@ -1,25 +1,24 @@ -Az Auxio egy helyi zenelejátszó gyors, megbízható felhasználói felülettel/UX-szel, anélkül, hogy a többi zenelejátszóban jelen lévő sok haszontalan funkciót tartalmazna. A modern médialejátszó könyvtárakra épülő Auxio kiváló könyvtártámogatással és zenehallgatási minőséggel rendelkezik, mint más, elavult Android-funkciókat használó alkalmazások. Röviden: Zenét játszik. +Az Auxio egy helyi zenelejátszó gyors, megbízható UI/UX felülettel, anélkül, hogy a többi zenelejátszóban előforduló sok felesleges funkcióval rendelkezne. Modern média lejátszó könyvtárakra építve, az Auxio kiváló könyvtámtámogatással és hallgatási minőséggel rendelkezik, összehasonlítva az elavult androidos funkciókat használó egyéb alkalmazásokkal. Röviden: Zenét játszik le. Funkciók -- Lejátszás Media3 ExoPlayer alapú -- A legfrissebb anyagtervezési irányelvekből származó, lendületes felhasználói felület -- Véleményes UX, amely előnyben részesíti a könnyű használatot a szélső esetekben +- Lejátszás a Media3 ExoPlayer alapjain +- Gyors UI, amely a legújabb Material Design irányelvekből származik +- Szubjektív UX, amely a használhatóságot helyezi előtérbe a szélsőséges esetekkel szemben - Testreszabható viselkedés -- Lemezszámok, több előadó, kiadástípusok támogatása, -pontos/eredeti dátumok, címkék rendezése stb -- Fejlett előadói rendszer, amely egyesíti az előadókat és az album előadókat -- SD-kártya-tudatos mappakezelés +- Támogatás a lemezszámokhoz, több előadóhoz, kiadási típusokhoz, pontos/eredeti dátumokhoz, rendezési címkékhez és még sok máshoz +- Fejlett előadói rendszer, amely egyesíti az előadókat és az albumelőadókat +- SD kártya-érzékeny mappa kezelés - Megbízható lejátszási lista funkció -- Lejátszási állapot fennmaradása -- Android automatikus támogatás -- Automatikus hézagmentes lejátszás -- Teljes ReplayGain támogatás (MP3, FLAC, OGG, OPUS és MP4 fájlokon) -- Külső hangszínszabályzó támogatás (pl. Wavelet) -- Éltől szélig +- Lejátszási állapot megőrzése +- Android Auto támogatás +- Automatikus gapless lejátszás +- Teljes ReplayGain támogatás (MP3, FLAC, OGG, OPUS és MP4 fájlokhoz) +- Külső ekvalizátor támogatás (pl. Wavelet) +- Szélről-szélre - Beágyazott borítók támogatása -- Keresés funkció -- Headset automatikus lejátszása -- Stílusos kütyük, amelyek automatikusan alkalmazkodnak a méretükhöz +- Keresési funkció +- Fejhallgató automatikus lejátszása +- Stílusos widgetek, amelyek automatikusan alkalmazkodnak a méretükhöz - Teljesen privát és offline -- Nincsenek lekerekített albumborítók (alapértelmezés szerint) +- Nincsenek lekerekített albumborítók (ha nem szeretnél) diff --git a/fastlane/metadata/android/in/full_description.txt b/fastlane/metadata/android/in/full_description.txt new file mode 100644 index 000000000..db1e6a3ca --- /dev/null +++ b/fastlane/metadata/android/in/full_description.txt @@ -0,0 +1,24 @@ +Auxio adalah pemutar musik lokal dengan antarmuka pengguna (UI/UX) yang cepat dan andal, tanpa fitur-fitur tidak berguna yang ada pada pemutar musik lainnya. Dibangun menggunakan pustaka pemutaran media modern, Auxio memiliki dukungan perpustakaan dan kualitas mendengarkan yang lebih unggul dibandingkan aplikasi lain yang menggunakan fungsionalitas Android yang sudah ketinggalan zaman. Singkatnya, Ini memutar musik. + +Fitur + +- Pemutaran berbasis Media3 ExoPlayer +- UI responsif yang mengikuti pedoman Material Design terbaru +- UX yang jelas dengan prioritas pada kemudahan penggunaan dibandingkan kasus-kasus ekstrim +- Perilaku yang dapat disesuaikan +- Dukungan untuk nomor disk, banyak artis, jenis rilisan, tanggal pasti/original, tag urut, dan lainnya +- Sistem artis canggih yang menyatukan artis dan artis album +- Manajemen folder yang peka terhadap kartu SD +- Fungsionalitas pemutaran daftar putar yang dapat diandalkan +- Persistensi status pemutaran +- Dukungan Android Auto +- Pemutaran tanpa jeda otomatis +- Dukungan penuh untuk ReplayGain (Pada file MP3, FLAC, OGG, OPUS, dan MP4) +- Dukungan equalizer eksternal (mis. Wavelet) +- Tampilan edge-to-edge +- Dukungan sampul yang tertanam +- Fungsionalitas pencarian +- Pemutaran otomatis dengan headset +- Widget bergaya yang secara otomatis menyesuaikan dengan ukuran mereka +- Sepenuhnya privat dan offline +- Tanpa sampul album bulat (jika Anda menginginkannya) diff --git a/fastlane/metadata/android/ja/full_description.txt b/fastlane/metadata/android/ja/full_description.txt index 62fa1451b..f657d3bef 100644 --- a/fastlane/metadata/android/ja/full_description.txt +++ b/fastlane/metadata/android/ja/full_description.txt @@ -3,7 +3,7 @@ Auxio は、高速で信頼性の高い UI/UX を備えたローカル ミュー 特徴 - ExoPlayer ベースの再生 -- 最新のマテリアル デザイン ガイドラインから派生したスナッピーな UI +- 最新のマテリアル・デザイン・ガイドラインに基づいたスマートなUI - 特殊なケースよりも使いやすさを優先する独自の UX - カスタマイズ可能な動作 - ディスク番号、複数のアーティスト、リリース タイプ、 @@ -19,4 +19,4 @@ Auxio は、高速で信頼性の高い UI/UX を備えたローカル ミュー - ヘッドセットの自動再生 - サイズに自動的に適応するスタイリッシュなウィジェット - 完全にプライベートでオフライン -- 丸みを帯びたアルバム カバーはありません (必要な場合を除きます。それならできます) +- 丸みを帯びたアルバム カバーはありません (お望みであれば) diff --git a/fastlane/metadata/android/nl-NL/full_description.txt b/fastlane/metadata/android/nl-NL/full_description.txt index 895806109..011c57cbc 100644 --- a/fastlane/metadata/android/nl-NL/full_description.txt +++ b/fastlane/metadata/android/nl-NL/full_description.txt @@ -21,4 +21,4 @@ exacte/originele data, sorteertags en meer - Automatisch afspelen voor koptelefoon - Stijlvolle widgets die zich automatisch aanpassen aan hun grootte - Volledig privé en offline -- Geen afgeronde albumhoezen (standaard) +- Geen afgeronde albumhoezen (als u wilt) diff --git a/fastlane/metadata/android/pt-BR/full_description.txt b/fastlane/metadata/android/pt-BR/full_description.txt index 162bca762..57b9dfe08 100644 --- a/fastlane/metadata/android/pt-BR/full_description.txt +++ b/fastlane/metadata/android/pt-BR/full_description.txt @@ -2,23 +2,23 @@ Auxio é um reprodutor de música local com uma interface/experiência de usuár Recursos: -- Reprodução baseada no Media3 ExoPlayer. -- Interface de usuário rápida derivada das últimas diretrizes do Material Design. -- Experiência de usuário opinativa que prioriza a facilidade de uso ao invés de priorizar situações incomuns. -- Comportamento customizável. -- Suporte a números de disco, vários artistas, tipos de lançamento, datas precisas/originais, metadados organizados e mais. +- Reprodução baseada no Media3 ExoPlayer +- Interface de usuário rápida derivada das últimas diretrizes do Material Design +- Experiência de usuário opinativa que prioriza a facilidade de uso ao invés de priorizar situações incomuns +- Comportamento customizável +- Suporte a números de disco, vários artistas, tipos de lançamento, datas precisas/originais, metadados organizados e mais - Sistema de artistas avançado que unifica artistas e artistas de álbum. -- Gerenciamento de pastas com suporte a cartão SD. -- Funcionalidade confiável de criação de playlists. -- Persistência do estado de reprodução. -- Suporte ao Android Auto. -- Reprodução automática sem interrupções. -- Suporte completo a ReplayGain (nos arquivos FLAC, MP3, MP4, OGG e OPUS). -- Suporte externo a equalizador (por exemplo, Wavelet). -- De ponta a ponta. -- Suporte a capas embutidas. -- Função de pesquisa. -- Reprodução automática em fones de ouvido. +- Gerenciamento de pastas com suporte a cartão SD +- Funcionalidade confiável de criação de playlists +- Persistência do estado de reprodução +- Suporte ao Android Auto +- Reprodução automática sem interrupções +- Suporte completo a ReplayGain (nos arquivos FLAC, MP3, MP4, OGG e OPUS) +- Suporte externo a equalizador (por exemplo, Wavelet) +- De ponta a ponta +- Suporte a capas embutidas +- Função de pesquisa +- Reprodução automática em fones de ouvido - Widgets elegantes que se adaptam automaticamente ao tamanho. -- Completamente privado e off-line. -- Sem capas de álbuns arredondadas (caso queira). +- Completamente privado e off-line +- Sem capas de álbuns arredondadas (caso queira) diff --git a/fastlane/metadata/android/zh-Hant/full_description.txt b/fastlane/metadata/android/zh-Hant/full_description.txt index efd745793..db4e9a15a 100644 --- a/fastlane/metadata/android/zh-Hant/full_description.txt +++ b/fastlane/metadata/android/zh-Hant/full_description.txt @@ -1,23 +1,25 @@ -Auxio 是一款本機音樂播放器,擁有快速且可靠的 UI/UX,不含其他音樂播放器中許多無用的功能。Auxio 基於現代媒體播放庫構建,與使用過時 Android 功能的其他應用相比,擁有更優越的庫支援和聆聽品質。簡而言之,它播放音樂。 +Auxio 是一款本機音樂播放器,擁有快速穩定的 UI / UX,不含其他音樂播放器中許多無用的功能。 +以現代媒體庫開發,和使用過時 Android 功能的其他播放器相比,擁有絕佳聆聽品質與核心支援。 +總之,它只專注播放音樂。 -功能 +特色 -- 基於 Media3 ExoPlayer 的播放功能 -- 源自最新 Material Design 指南的靈敏 UI -- 優化 UX,重視易用性高於邊緣情況 -- 可自訂的行為 -- 支援碟數、多位藝術家、發行類型、精確/原始日期、排序標籤等等 -- 進階藝術家系統,統一藝術家與專輯藝術家 -- 支援 SD 卡的資料夾管理 -- 可靠的播放列表功能 +- Media3 ExoPlayer 為基礎的播放功能 +- 遵循最新 Material Design 規範,時髦活潑的 UI +- 優化 UX,重視易用性而非極端需求 +- 自訂動作 +- 支援唱片編號、多位演出者、發行類型、精確 / 原始日期、標籤排序等 +- 統一演出者與專輯演出者的進階系統 +- SD 卡資料夾管理 +- 可靠的播放清單功能 - 支援 Android Auto -- 播放狀態持久性 -- 完整的 ReplayGain 支援(適用於 MP3、FLAC、OGG、OPUS 和 MP4 檔案) -- 外部均衡器支援(例如 Wavelet) +- 持續性播放狀態 +- 完整 ReplayGain(適用 MP3、FLAC、OGG、OPUS 和 MP4 檔案) +- 外部等化器(例如 Wavelet) - 無邊界設計 -- 內嵌封面支援 +- 內嵌專輯封面 - 搜尋功能 - 耳機自動播放 -- 時尚的小工具,自動適應大小 -- 完全私密且離線 -- 默認不使用圓角專輯封面 +- 時尚小工具,自動符合大小 +- 完全離線隱密 +- 預設無圓角專輯封面 From 7d2a060835b1307c4112f032b4e54324b1acdab2 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 1 Jun 2025 06:25:37 -0600 Subject: [PATCH 38/38] build: bump to v4.0.5 --- CHANGELOG.md | 8 ++++++++ README.md | 4 ++-- app/build.gradle | 4 ++-- fastlane/metadata/android/en-US/changelogs/64.txt | 4 ++++ 4 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 fastlane/metadata/android/en-US/changelogs/64.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a9aeb40a..439efa33e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 4.0.5 + +#### What's Improved +- Re-added folder exclusion + +#### What's Fixed +- Fixed slow loading on large libraries + ## 4.0.3 #### What's Improved diff --git a/README.md b/README.md index 168a2d16c..b99e6d825 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@

Auxio

A simple, rational music player for android.

- - Latest Version + + Latest Version Releases diff --git a/app/build.gradle b/app/build.gradle index 7249f29ba..713ae9f14 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -18,8 +18,8 @@ android { defaultConfig { applicationId namespace - versionName "4.0.4" - versionCode 63 + versionName "4.0.5" + versionCode 64 minSdk min_sdk targetSdk target_sdk diff --git a/fastlane/metadata/android/en-US/changelogs/64.txt b/fastlane/metadata/android/en-US/changelogs/64.txt new file mode 100644 index 000000000..69bf3244e --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/64.txt @@ -0,0 +1,4 @@ +Auxio 4.0.0 completely overhauls the user experience, with a refreshed design based on the latest Material Design specs +and a brand new music loader with signifigant improvements to device and tag support. +This patch fixes slower music loading and re-adds folder exclusion. Deep apologies for how long this took to fix. +For more information, see https://github.com/OxygenCobalt/Auxio/releases/tag/v4.0.5.