all: break off musikr
This commit is contained in:
@@ -54,7 +54,6 @@ import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.MusicParent
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.metadata.AudioProperties
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
@@ -69,7 +68,6 @@ class DetailViewModel
|
||||
constructor(
|
||||
private val listSettings: ListSettings,
|
||||
private val musicRepository: MusicRepository,
|
||||
private val audioPropertiesFactory: AudioProperties.Factory,
|
||||
private val playbackSettings: PlaybackSettings,
|
||||
detailGeneratorFactory: DetailGenerator.Factory
|
||||
) : ViewModel(), DetailGenerator.Invalidator {
|
||||
@@ -89,10 +87,6 @@ constructor(
|
||||
val currentSong: StateFlow<Song?>
|
||||
get() = _currentSong
|
||||
|
||||
private val _songAudioProperties = MutableStateFlow<AudioProperties?>(null)
|
||||
/** The [AudioProperties] of the currently shown [Song]. Null if not loaded yet. */
|
||||
val songAudioProperties: StateFlow<AudioProperties?> = _songAudioProperties
|
||||
|
||||
// --- ALBUM ---
|
||||
|
||||
private val _currentAlbum = MutableStateFlow<Album?>(null)
|
||||
@@ -308,7 +302,7 @@ constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new [currentSong] from it's [Music.UID]. [currentSong] and [songAudioProperties] will
|
||||
* Set a new [currentSong] from it's [Music.UID]. [currentSong] will
|
||||
* be updated to align with the new [Song].
|
||||
*
|
||||
* @param uid The UID of the [Song] to load. Must be valid.
|
||||
@@ -511,17 +505,7 @@ constructor(
|
||||
}
|
||||
|
||||
private fun refreshAudioInfo(song: Song) {
|
||||
L.d("Refreshing audio info")
|
||||
// Clear any previous job in order to avoid stale data from appearing in the UI.
|
||||
currentSongJob?.cancel()
|
||||
_songAudioProperties.value = null
|
||||
currentSongJob =
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val info = audioPropertiesFactory.extract(song)
|
||||
yield()
|
||||
L.d("Updating audio info to $info")
|
||||
_songAudioProperties.value = info
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private inline fun <T : MusicParent> refreshDetail(
|
||||
|
||||
@@ -41,7 +41,6 @@ import org.oxycblt.auxio.util.collectImmediately
|
||||
import org.oxycblt.auxio.util.concatLocalized
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.metadata.AudioProperties
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import timber.log.Timber as L
|
||||
|
||||
@@ -72,63 +71,63 @@ class SongDetailDialog : ViewBindingMaterialDialogFragment<DialogSongDetailBindi
|
||||
// DetailViewModel handles most initialization from the navigation argument.
|
||||
detailModel.setSong(args.songUid)
|
||||
detailModel.toShow.consume()
|
||||
collectImmediately(detailModel.currentSong, detailModel.songAudioProperties, ::updateSong)
|
||||
collectImmediately(detailModel.currentSong, ::updateSong)
|
||||
}
|
||||
|
||||
private fun updateSong(song: Song?, info: AudioProperties?) {
|
||||
if (song == null) {
|
||||
private fun updateSong(song: Song?) {
|
||||
// if (song == null) {
|
||||
L.d("No song to show, navigating away")
|
||||
findNavController().navigateUp()
|
||||
return
|
||||
}
|
||||
|
||||
if (info != null) {
|
||||
val context = requireContext()
|
||||
detailAdapter.update(
|
||||
buildList {
|
||||
add(SongProperty(R.string.lbl_name, song.zipName(context)))
|
||||
add(SongProperty(R.string.lbl_album, song.album.zipName(context)))
|
||||
add(SongProperty(R.string.lbl_artists, song.artists.zipNames(context)))
|
||||
add(SongProperty(R.string.lbl_genres, song.genres.resolveNames(context)))
|
||||
song.date?.let { add(SongProperty(R.string.lbl_date, it.resolve(context))) }
|
||||
song.track?.let {
|
||||
add(SongProperty(R.string.lbl_track, getString(R.string.fmt_number, it)))
|
||||
}
|
||||
song.disc?.let {
|
||||
val formattedNumber = getString(R.string.fmt_number, it.number)
|
||||
val zipped =
|
||||
if (it.name != null) {
|
||||
getString(R.string.fmt_zipped_names, formattedNumber, it.name)
|
||||
} else {
|
||||
formattedNumber
|
||||
}
|
||||
add(SongProperty(R.string.lbl_disc, zipped))
|
||||
}
|
||||
add(SongProperty(R.string.lbl_path, song.path.resolve(context)))
|
||||
// info.format.resolveName(context)?.let {
|
||||
// add(SongProperty(R.string.lbl_format, it))
|
||||
// }
|
||||
add(
|
||||
SongProperty(
|
||||
R.string.lbl_size, Formatter.formatFileSize(context, song.size)))
|
||||
add(SongProperty(R.string.lbl_duration, song.durationMs.formatDurationMs(true)))
|
||||
info.bitrateKbps?.let {
|
||||
add(SongProperty(R.string.lbl_bitrate, getString(R.string.fmt_bitrate, it)))
|
||||
}
|
||||
info.sampleRateHz?.let {
|
||||
add(
|
||||
SongProperty(
|
||||
R.string.lbl_sample_rate, getString(R.string.fmt_sample_rate, it)))
|
||||
}
|
||||
song.replayGainAdjustment.track?.let {
|
||||
add(SongProperty(R.string.lbl_replaygain_track, it.formatDb(context)))
|
||||
}
|
||||
song.replayGainAdjustment.album?.let {
|
||||
add(SongProperty(R.string.lbl_replaygain_album, it.formatDb(context)))
|
||||
}
|
||||
},
|
||||
UpdateInstructions.Replace(0))
|
||||
}
|
||||
// }
|
||||
//
|
||||
// if (info != null) {
|
||||
// val context = requireContext()
|
||||
// detailAdapter.update(
|
||||
// buildList {
|
||||
// add(SongProperty(R.string.lbl_name, song.zipName(context)))
|
||||
// add(SongProperty(R.string.lbl_album, song.album.zipName(context)))
|
||||
// add(SongProperty(R.string.lbl_artists, song.artists.zipNames(context)))
|
||||
// add(SongProperty(R.string.lbl_genres, song.genres.resolveNames(context)))
|
||||
// song.date?.let { add(SongProperty(R.string.lbl_date, it.resolve(context))) }
|
||||
// song.track?.let {
|
||||
// add(SongProperty(R.string.lbl_track, getString(R.string.fmt_number, it)))
|
||||
// }
|
||||
// song.disc?.let {
|
||||
// val formattedNumber = getString(R.string.fmt_number, it.number)
|
||||
// val zipped =
|
||||
// if (it.name != null) {
|
||||
// getString(R.string.fmt_zipped_names, formattedNumber, it.name)
|
||||
// } else {
|
||||
// formattedNumber
|
||||
// }
|
||||
// add(SongProperty(R.string.lbl_disc, zipped))
|
||||
// }
|
||||
// add(SongProperty(R.string.lbl_path, song.path.resolve(context)))
|
||||
// // info.format.resolveName(context)?.let {
|
||||
// // add(SongProperty(R.string.lbl_format, it))
|
||||
// // }
|
||||
// add(
|
||||
// SongProperty(
|
||||
// R.string.lbl_size, Formatter.formatFileSize(context, song.size)))
|
||||
// add(SongProperty(R.string.lbl_duration, song.durationMs.formatDurationMs(true)))
|
||||
// info.bitrateKbps?.let {
|
||||
// add(SongProperty(R.string.lbl_bitrate, getString(R.string.fmt_bitrate, it)))
|
||||
// }
|
||||
// info.sampleRateHz?.let {
|
||||
// add(
|
||||
// SongProperty(
|
||||
// R.string.lbl_sample_rate, getString(R.string.fmt_sample_rate, it)))
|
||||
// }
|
||||
// song.replayGainAdjustment.track?.let {
|
||||
// add(SongProperty(R.string.lbl_replaygain_track, it.formatDb(context)))
|
||||
// }
|
||||
// song.replayGainAdjustment.album?.let {
|
||||
// add(SongProperty(R.string.lbl_replaygain_album, it.formatDb(context)))
|
||||
// }
|
||||
// },
|
||||
// UpdateInstructions.Replace(0))
|
||||
// }
|
||||
}
|
||||
|
||||
private fun <T : Music> T.zipName(context: Context): String {
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Config.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr
|
||||
|
||||
import org.oxycblt.musikr.cache.Cache
|
||||
import org.oxycblt.musikr.cover.StoredCovers
|
||||
import org.oxycblt.musikr.tag.interpret.Naming
|
||||
import org.oxycblt.musikr.tag.interpret.Separators
|
||||
|
||||
data class Storage(val cache: Cache, val storedCovers: StoredCovers)
|
||||
|
||||
data class Interpretation(val naming: Naming, val separators: Separators)
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Library.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr
|
||||
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
|
||||
interface Library {
|
||||
val songs: Collection<Song>
|
||||
val albums: Collection<Album>
|
||||
val artists: Collection<Artist>
|
||||
val genres: Collection<Genre>
|
||||
val playlists: Collection<Playlist>
|
||||
|
||||
fun findSong(uid: Music.UID): Song?
|
||||
|
||||
fun findSongByPath(path: Path): Song?
|
||||
|
||||
fun findAlbum(uid: Music.UID): Album?
|
||||
|
||||
fun findArtist(uid: Music.UID): Artist?
|
||||
|
||||
fun findGenre(uid: Music.UID): Genre?
|
||||
|
||||
fun findPlaylist(uid: Music.UID): Playlist?
|
||||
|
||||
fun findPlaylistByName(name: String): Playlist?
|
||||
}
|
||||
|
||||
interface MutableLibrary : Library {
|
||||
suspend fun createPlaylist(name: String, songs: List<Song>): MutableLibrary
|
||||
|
||||
suspend fun renamePlaylist(playlist: Playlist, name: String): MutableLibrary
|
||||
|
||||
suspend fun addToPlaylist(playlist: Playlist, songs: List<Song>): MutableLibrary
|
||||
|
||||
suspend fun rewritePlaylist(playlist: Playlist, songs: List<Song>): MutableLibrary
|
||||
|
||||
suspend fun deletePlaylist(playlist: Playlist): MutableLibrary
|
||||
}
|
||||
@@ -1,370 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* Music.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr
|
||||
|
||||
import android.net.Uri
|
||||
import android.os.Parcelable
|
||||
import androidx.room.TypeConverter
|
||||
import java.security.MessageDigest
|
||||
import java.util.UUID
|
||||
import kotlinx.parcelize.IgnoredOnParcel
|
||||
import kotlinx.parcelize.Parcelize
|
||||
import org.oxycblt.musikr.cover.Cover
|
||||
import org.oxycblt.musikr.fs.Format
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.tag.Date
|
||||
import org.oxycblt.musikr.tag.Disc
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import org.oxycblt.musikr.tag.ReleaseType
|
||||
import org.oxycblt.musikr.tag.ReplayGainAdjustment
|
||||
import org.oxycblt.musikr.util.toUuidOrNull
|
||||
|
||||
/**
|
||||
* Abstract music data. This contains universal information about all concrete music
|
||||
* implementations, such as identification information and names.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
sealed interface Music {
|
||||
/**
|
||||
* A unique identifier for this music item.
|
||||
*
|
||||
* @see UID
|
||||
*/
|
||||
val uid: UID
|
||||
|
||||
/** The [Name] of the music item. */
|
||||
val name: Name
|
||||
|
||||
/**
|
||||
* A unique identifier for a piece of music.
|
||||
*
|
||||
* [UID] enables a much cheaper and more reliable form of differentiating music, derived from
|
||||
* either internal app information or the MusicBrainz ID spec. Using this enables several
|
||||
* improvements to music management in this app, including:
|
||||
* - Proper differentiation of identical music. It's common for large, well-tagged libraries to
|
||||
* have functionally duplicate items that are differentiated with MusicBrainz IDs, and so
|
||||
* [UID] allows us to properly differentiate between these in the app.
|
||||
* - Better music persistence between restarts. Whereas directly storing song names would be
|
||||
* prone to collisions, and storing MediaStore IDs would drift rapidly as the music library
|
||||
* changes, [UID] enables a much stronger form of persistence given it's unique link to a
|
||||
* specific files metadata configuration, which is unlikely to collide with another item or
|
||||
* drift as the music library changes.
|
||||
*
|
||||
* Note: Generally try to use [UID] as a black box that can only be read, written, and compared.
|
||||
* It will not be fun if you try to manipulate it in any other manner.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@Parcelize
|
||||
class UID
|
||||
private constructor(
|
||||
private val format: Format,
|
||||
private val item: Item,
|
||||
private val uuid: UUID
|
||||
) : Parcelable {
|
||||
// Cache the hashCode for HashMap efficiency.
|
||||
@IgnoredOnParcel private var hashCode = format.hashCode()
|
||||
|
||||
init {
|
||||
hashCode = 31 * hashCode + item.hashCode()
|
||||
hashCode = 31 * hashCode + uuid.hashCode()
|
||||
}
|
||||
|
||||
override fun hashCode() = hashCode
|
||||
|
||||
override fun equals(other: Any?) =
|
||||
other is UID && format == other.format && item == other.item && uuid == other.uuid
|
||||
|
||||
override fun toString() = "${format.namespace}:${item.intCode.toString(16)}-$uuid"
|
||||
|
||||
enum class Item(val intCode: Int) {
|
||||
// Item used to be MusicType back when the music module was
|
||||
// part of Auxio, so these old integer codes remain.
|
||||
// TODO: Introduce new UID format that removes these.
|
||||
SONG(0xA10B),
|
||||
ALBUM(0xA10A),
|
||||
ARTIST(0xA109),
|
||||
GENRE(0xA108),
|
||||
PLAYLIST(0xA107)
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal marker of [Music.UID] format type.
|
||||
*
|
||||
* @param namespace Namespace to use in the [Music.UID]'s string representation.
|
||||
*/
|
||||
private enum class Format(val namespace: String) {
|
||||
/** @see auxio */
|
||||
AUXIO("org.oxycblt.auxio"),
|
||||
|
||||
/** @see musicBrainz */
|
||||
MUSICBRAINZ("org.musicbrainz")
|
||||
}
|
||||
|
||||
object TypeConverters {
|
||||
/** @see [Music.UID.toString] */
|
||||
@TypeConverter fun fromMusicUID(uid: UID?) = uid?.toString()
|
||||
|
||||
/** @see [Music.UID.fromString] */
|
||||
@TypeConverter fun toMusicUid(string: String?) = string?.let(Companion::fromString)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Creates an Auxio-style [UID] of random composition. Used if there is no
|
||||
* non-subjective, unlikely-to-change metadata of the music.
|
||||
*
|
||||
* @param item The type of [Item] that created this [UID].
|
||||
*/
|
||||
fun auxio(item: Item): UID {
|
||||
return UID(Format.AUXIO, item, UUID.randomUUID())
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an Auxio-style [UID] with a [UUID] composed of a hash of the non-subjective,
|
||||
* unlikely-to-change metadata of the music.
|
||||
*
|
||||
* @param item The type of [Item] that created this [UID].
|
||||
* @param updates Block to update the [MessageDigest] hash with the metadata of the
|
||||
* item. Make sure the metadata hashed semantically aligns with the format
|
||||
* specification.
|
||||
* @return A new auxio-style [UID].
|
||||
*/
|
||||
fun auxio(item: Item, updates: MessageDigest.() -> Unit): UID {
|
||||
val digest =
|
||||
MessageDigest.getInstance("SHA-256").run {
|
||||
updates()
|
||||
digest()
|
||||
}
|
||||
// Convert the digest to a UUID. This does cleave off some of the hash, but this
|
||||
// is considered okay.
|
||||
val uuid =
|
||||
UUID(
|
||||
digest[0]
|
||||
.toLong()
|
||||
.shl(56)
|
||||
.or(digest[1].toLong().and(0xFF).shl(48))
|
||||
.or(digest[2].toLong().and(0xFF).shl(40))
|
||||
.or(digest[3].toLong().and(0xFF).shl(32))
|
||||
.or(digest[4].toLong().and(0xFF).shl(24))
|
||||
.or(digest[5].toLong().and(0xFF).shl(16))
|
||||
.or(digest[6].toLong().and(0xFF).shl(8))
|
||||
.or(digest[7].toLong().and(0xFF)),
|
||||
digest[8]
|
||||
.toLong()
|
||||
.shl(56)
|
||||
.or(digest[9].toLong().and(0xFF).shl(48))
|
||||
.or(digest[10].toLong().and(0xFF).shl(40))
|
||||
.or(digest[11].toLong().and(0xFF).shl(32))
|
||||
.or(digest[12].toLong().and(0xFF).shl(24))
|
||||
.or(digest[13].toLong().and(0xFF).shl(16))
|
||||
.or(digest[14].toLong().and(0xFF).shl(8))
|
||||
.or(digest[15].toLong().and(0xFF)))
|
||||
return UID(Format.AUXIO, item, uuid)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a MusicBrainz-style [UID] with a [UUID] derived from the MusicBrainz ID
|
||||
* extracted from a file.
|
||||
*
|
||||
* @param item The [Item] that created this [UID].
|
||||
* @param mbid The analogous MusicBrainz ID for this item that was extracted from a
|
||||
* file.
|
||||
* @return A new MusicBrainz-style [UID].
|
||||
*/
|
||||
fun musicBrainz(item: Item, mbid: UUID) = UID(Format.MUSICBRAINZ, item, mbid)
|
||||
|
||||
/**
|
||||
* Convert a [UID]'s string representation back into a concrete [UID] instance.
|
||||
*
|
||||
* @param uid The [UID]'s string representation, formatted as
|
||||
* `format_namespace:music_mode_int-uuid`.
|
||||
* @return A [UID] converted from the string representation, or null if the string
|
||||
* representation was invalid.
|
||||
*/
|
||||
fun fromString(uid: String): UID? {
|
||||
val split = uid.split(':', limit = 2)
|
||||
if (split.size != 2) {
|
||||
return null
|
||||
}
|
||||
|
||||
val format =
|
||||
when (split[0]) {
|
||||
Format.AUXIO.namespace -> Format.AUXIO
|
||||
Format.MUSICBRAINZ.namespace -> Format.MUSICBRAINZ
|
||||
else -> return null
|
||||
}
|
||||
|
||||
val ids = split[1].split('-', limit = 2)
|
||||
if (ids.size != 2) {
|
||||
return null
|
||||
}
|
||||
|
||||
val intCode = ids[0].toIntOrNull(16) ?: return null
|
||||
val type = Item.entries.firstOrNull { it.intCode == intCode } ?: return null
|
||||
val uuid = ids[1].toUuidOrNull() ?: return null
|
||||
return UID(format, type, uuid)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An abstract grouping of [Song]s and other [Music] data.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
sealed interface MusicParent : Music {
|
||||
/** The child [Song]s of this [MusicParent]. */
|
||||
val songs: Collection<Song>
|
||||
}
|
||||
|
||||
/**
|
||||
* A song.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface Song : Music {
|
||||
override val name: Name.Known
|
||||
/** The track number. Will be null if no valid track number was present in the metadata. */
|
||||
val track: Int?
|
||||
/** The [Disc] number. Will be null if no valid disc number was present in the metadata. */
|
||||
val disc: Disc?
|
||||
/** The release [Date]. Will be null if no valid date was present in the metadata. */
|
||||
val date: Date?
|
||||
/**
|
||||
* The URI to the audio file that this instance was created from. This can be used to access the
|
||||
* audio file in a way that is scoped-storage-safe.
|
||||
*/
|
||||
val uri: Uri
|
||||
/**
|
||||
* The [Path] to this audio file. This is only intended for display, [uri] should be favored
|
||||
* instead for accessing the audio file.
|
||||
*/
|
||||
val path: Path
|
||||
/** The [Format] of the audio file. Only intended for display. */
|
||||
val format: Format
|
||||
/** The size of the audio file, in bytes. */
|
||||
val size: Long
|
||||
/** The duration of the audio file, in milliseconds. */
|
||||
val durationMs: Long
|
||||
/** The ReplayGain adjustment to apply during playback. */
|
||||
val replayGainAdjustment: ReplayGainAdjustment
|
||||
/** The date last modified the audio file was last modified, as a unix epoch timestamp. */
|
||||
val lastModified: Long
|
||||
/** The date the audio file was added to the device, as a unix epoch timestamp. */
|
||||
val dateAdded: Long
|
||||
/** Useful information to quickly obtain the album cover. */
|
||||
val cover: Cover.Single?
|
||||
/**
|
||||
* The parent [Album]. If the metadata did not specify an album, it's parent directory is used
|
||||
* instead.
|
||||
*/
|
||||
val album: Album
|
||||
/**
|
||||
* The parent [Artist]s of this [Song]. Is often one, but there can be multiple if more than one
|
||||
* [Artist] name was specified in the metadata. Unliked [Album], artists are prioritized for
|
||||
* this field.
|
||||
*/
|
||||
val artists: List<Artist>
|
||||
/**
|
||||
* The parent [Genre]s of this [Song]. Is often one, but there can be multiple if more than one
|
||||
* [Genre] name was specified in the metadata.
|
||||
*/
|
||||
val genres: List<Genre>
|
||||
}
|
||||
|
||||
/**
|
||||
* An abstract release group. While it may be called an album, it encompasses other types of
|
||||
* releases like singles, EPs, and compilations.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface Album : MusicParent {
|
||||
/** The [Date.Range] that [Song]s in the [Album] were released. */
|
||||
val dates: Date.Range?
|
||||
/**
|
||||
* The [ReleaseType] of this album, signifying the type of release it actually is. Defaults to
|
||||
* [ReleaseType.Album].
|
||||
*/
|
||||
val releaseType: ReleaseType
|
||||
/** Cover information from album's songs. */
|
||||
val cover: Cover
|
||||
/** The duration of all songs in the album, in milliseconds. */
|
||||
val durationMs: Long
|
||||
/** The earliest date a song in this album was added, as a unix epoch timestamp. */
|
||||
val dateAdded: Long
|
||||
/**
|
||||
* The parent [Artist]s of this [Album]. Is often one, but there can be multiple if more than
|
||||
* one [Artist] name was specified in the metadata of the [Song]'s. Unlike [Song], album artists
|
||||
* are prioritized for this field.
|
||||
*/
|
||||
val artists: List<Artist>
|
||||
}
|
||||
|
||||
/**
|
||||
* An abstract artist. These are actually a combination of the artist and album artist tags from
|
||||
* within the library, derived from [Song]s and [Album]s respectively.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface Artist : MusicParent {
|
||||
/** Albums directly credited to this [Artist] via a "Album Artist" tag. */
|
||||
val explicitAlbums: Collection<Album>
|
||||
/** Albums indirectly credited to this [Artist] via an "Artist" tag. */
|
||||
val implicitAlbums: Collection<Album>
|
||||
/**
|
||||
* The duration of all [Song]s in the artist, in milliseconds. Will be null if there are no
|
||||
* songs.
|
||||
*/
|
||||
val durationMs: Long?
|
||||
/** Useful information to quickly obtain a (single) cover for a Genre. */
|
||||
val cover: Cover
|
||||
/** The [Genre]s of this artist. */
|
||||
val genres: List<Genre>
|
||||
}
|
||||
|
||||
/**
|
||||
* A genre.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface Genre : MusicParent {
|
||||
/** The artists indirectly linked to by the [Artist]s of this [Genre]. */
|
||||
val artists: Collection<Artist>
|
||||
/** The total duration of the songs in this genre, in milliseconds. */
|
||||
val durationMs: Long
|
||||
/** Useful information to quickly obtain a (single) cover for a Genre. */
|
||||
val cover: Cover
|
||||
}
|
||||
|
||||
/**
|
||||
* A playlist.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface Playlist : MusicParent {
|
||||
override val name: Name.Known
|
||||
override val songs: List<Song>
|
||||
/** The total duration of the songs in this genre, in milliseconds. */
|
||||
val durationMs: Long
|
||||
/** Useful information to quickly obtain a (single) cover for a Genre. */
|
||||
val cover: Cover
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Musikr.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
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
|
||||
|
||||
interface Musikr {
|
||||
suspend fun run(
|
||||
locations: List<MusicLocation>,
|
||||
storage: Storage,
|
||||
interpretation: Interpretation,
|
||||
onProgress: suspend (IndexingProgress) -> Unit = {}
|
||||
): MutableLibrary
|
||||
|
||||
companion object {
|
||||
fun new(context: Context): Musikr =
|
||||
MusikrImpl(ExploreStep.from(context), ExtractStep.from(context), EvaluateStep.new())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the current progress of music loading.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
sealed interface IndexingProgress {
|
||||
data class Songs(val loaded: Int, val explored: Int) : IndexingProgress
|
||||
|
||||
data object Indeterminate : IndexingProgress
|
||||
}
|
||||
|
||||
class MusikrImpl(
|
||||
private val exploreStep: ExploreStep,
|
||||
private val extractStep: ExtractStep,
|
||||
private val evaluateStep: EvaluateStep
|
||||
) : Musikr {
|
||||
override suspend fun run(
|
||||
locations: List<MusicLocation>,
|
||||
storage: Storage,
|
||||
interpretation: Interpretation,
|
||||
onProgress: suspend (IndexingProgress) -> Unit
|
||||
) = coroutineScope {
|
||||
var exploredCount = 0
|
||||
var extractedCount = 0
|
||||
val explored =
|
||||
exploreStep
|
||||
.explore(locations)
|
||||
.buffer(Channel.UNLIMITED)
|
||||
.onStart { onProgress(IndexingProgress.Songs(0, 0)) }
|
||||
.onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) }
|
||||
val extracted =
|
||||
extractStep
|
||||
.extract(storage, explored)
|
||||
.buffer(Channel.UNLIMITED)
|
||||
.onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) }
|
||||
.onCompletion { onProgress(IndexingProgress.Indeterminate) }
|
||||
evaluateStep.evaluate(interpretation, extracted)
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Cache.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.cache
|
||||
|
||||
import org.oxycblt.musikr.fs.query.DeviceFile
|
||||
import org.oxycblt.musikr.pipeline.RawSong
|
||||
|
||||
interface Cache {
|
||||
suspend fun read(file: DeviceFile): CacheResult
|
||||
|
||||
suspend fun write(song: RawSong)
|
||||
|
||||
companion object {
|
||||
fun full(db: CacheDatabase): Cache = FullCache(db.cachedSongsDao())
|
||||
|
||||
fun writeOnly(db: CacheDatabase): Cache = WriteOnlyCache(db.cachedSongsDao())
|
||||
}
|
||||
}
|
||||
|
||||
sealed interface CacheResult {
|
||||
data class Hit(val song: RawSong) : CacheResult
|
||||
|
||||
data class Miss(val file: DeviceFile) : CacheResult
|
||||
}
|
||||
|
||||
private class FullCache(private val cacheInfoDao: CacheInfoDao) : Cache {
|
||||
override suspend fun read(file: DeviceFile) =
|
||||
cacheInfoDao.selectSong(file.uri.toString(), file.lastModified)?.let {
|
||||
CacheResult.Hit(it.intoRawSong(file))
|
||||
} ?: CacheResult.Miss(file)
|
||||
|
||||
override suspend fun write(song: RawSong) =
|
||||
cacheInfoDao.updateSong(CachedSong.fromRawSong(song))
|
||||
}
|
||||
|
||||
private class WriteOnlyCache(private val cacheInfoDao: CacheInfoDao) : Cache {
|
||||
override suspend fun read(file: DeviceFile) = CacheResult.Miss(file)
|
||||
|
||||
override suspend fun write(song: RawSong) =
|
||||
cacheInfoDao.updateSong(CachedSong.fromRawSong(song))
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* CacheDatabase.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.cache
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Database
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.Query
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverter
|
||||
import androidx.room.TypeConverters
|
||||
import org.oxycblt.ktaglib.Properties
|
||||
import org.oxycblt.musikr.cover.Cover
|
||||
import org.oxycblt.musikr.fs.query.DeviceFile
|
||||
import org.oxycblt.musikr.pipeline.RawSong
|
||||
import org.oxycblt.musikr.tag.Date
|
||||
import org.oxycblt.musikr.tag.parse.ParsedTags
|
||||
import org.oxycblt.musikr.tag.util.correctWhitespace
|
||||
import org.oxycblt.musikr.tag.util.splitEscaped
|
||||
|
||||
@Database(entities = [CachedSong::class], version = 50, exportSchema = false)
|
||||
abstract class CacheDatabase : RoomDatabase() {
|
||||
internal abstract fun cachedSongsDao(): CacheInfoDao
|
||||
|
||||
companion object {
|
||||
fun from(context: Context) =
|
||||
Room.databaseBuilder(
|
||||
context.applicationContext, CacheDatabase::class.java, "music_cache.db")
|
||||
.fallbackToDestructiveMigration()
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
@Dao
|
||||
internal interface CacheInfoDao {
|
||||
@Query("SELECT * FROM CachedSong WHERE uri = :uri AND dateModified = :dateModified")
|
||||
suspend fun selectSong(uri: String, dateModified: Long): CachedSong?
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun updateSong(cachedSong: CachedSong)
|
||||
}
|
||||
|
||||
@Entity
|
||||
@TypeConverters(CachedSong.Converters::class)
|
||||
internal data class CachedSong(
|
||||
@PrimaryKey val uri: String,
|
||||
val dateModified: Long,
|
||||
val mimeType: String,
|
||||
val durationMs: Long,
|
||||
val bitrate: Int,
|
||||
val sampleRate: Int,
|
||||
val musicBrainzId: String?,
|
||||
val name: String,
|
||||
val sortName: String?,
|
||||
val track: Int?,
|
||||
val disc: Int?,
|
||||
val subtitle: String?,
|
||||
val date: Date?,
|
||||
val albumMusicBrainzId: String?,
|
||||
val albumName: String?,
|
||||
val albumSortName: String?,
|
||||
val releaseTypes: List<String>,
|
||||
val artistMusicBrainzIds: List<String>,
|
||||
val artistNames: List<String>,
|
||||
val artistSortNames: List<String>,
|
||||
val albumArtistMusicBrainzIds: List<String>,
|
||||
val albumArtistNames: List<String>,
|
||||
val albumArtistSortNames: List<String>,
|
||||
val genreNames: List<String>,
|
||||
val replayGainTrackAdjustment: Float?,
|
||||
val replayGainAlbumAdjustment: Float?,
|
||||
val cover: Cover.Single?,
|
||||
) {
|
||||
fun intoRawSong(file: DeviceFile) =
|
||||
RawSong(
|
||||
file,
|
||||
Properties(mimeType, durationMs, bitrate, sampleRate),
|
||||
ParsedTags(
|
||||
musicBrainzId = musicBrainzId,
|
||||
name = name,
|
||||
sortName = sortName,
|
||||
durationMs = durationMs,
|
||||
track = track,
|
||||
disc = disc,
|
||||
subtitle = subtitle,
|
||||
date = date,
|
||||
albumMusicBrainzId = albumMusicBrainzId,
|
||||
albumName = albumName,
|
||||
albumSortName = albumSortName,
|
||||
releaseTypes = releaseTypes,
|
||||
artistMusicBrainzIds = artistMusicBrainzIds,
|
||||
artistNames = artistNames,
|
||||
artistSortNames = artistSortNames,
|
||||
albumArtistMusicBrainzIds = albumArtistMusicBrainzIds,
|
||||
albumArtistNames = albumArtistNames,
|
||||
albumArtistSortNames = albumArtistSortNames,
|
||||
genreNames = genreNames,
|
||||
replayGainTrackAdjustment = replayGainTrackAdjustment,
|
||||
replayGainAlbumAdjustment = replayGainAlbumAdjustment),
|
||||
cover)
|
||||
|
||||
object Converters {
|
||||
@TypeConverter
|
||||
fun fromMultiValue(values: List<String>) =
|
||||
values.joinToString(";") { it.replace(";", "\\;") }
|
||||
|
||||
@TypeConverter
|
||||
fun toMultiValue(string: String) = string.splitEscaped { it == ';' }.correctWhitespace()
|
||||
|
||||
@TypeConverter fun fromDate(date: Date?) = date?.toString()
|
||||
|
||||
@TypeConverter fun toDate(string: String?) = string?.let(Date::from)
|
||||
|
||||
@TypeConverter fun fromCover(cover: Cover.Single?) = cover?.key
|
||||
|
||||
@TypeConverter fun toCover(key: String?) = key?.let { Cover.Single(it) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun fromRawSong(rawSong: RawSong) =
|
||||
CachedSong(
|
||||
uri = rawSong.file.uri.toString(),
|
||||
dateModified = rawSong.file.lastModified,
|
||||
musicBrainzId = rawSong.tags.musicBrainzId,
|
||||
name = rawSong.tags.name,
|
||||
sortName = rawSong.tags.sortName,
|
||||
durationMs = rawSong.tags.durationMs,
|
||||
track = rawSong.tags.track,
|
||||
disc = rawSong.tags.disc,
|
||||
subtitle = rawSong.tags.subtitle,
|
||||
date = rawSong.tags.date,
|
||||
albumMusicBrainzId = rawSong.tags.albumMusicBrainzId,
|
||||
albumName = rawSong.tags.albumName,
|
||||
albumSortName = rawSong.tags.albumSortName,
|
||||
releaseTypes = rawSong.tags.releaseTypes,
|
||||
artistMusicBrainzIds = rawSong.tags.artistMusicBrainzIds,
|
||||
artistNames = rawSong.tags.artistNames,
|
||||
artistSortNames = rawSong.tags.artistSortNames,
|
||||
albumArtistMusicBrainzIds = rawSong.tags.albumArtistMusicBrainzIds,
|
||||
albumArtistNames = rawSong.tags.albumArtistNames,
|
||||
albumArtistSortNames = rawSong.tags.albumArtistSortNames,
|
||||
genreNames = rawSong.tags.genreNames,
|
||||
replayGainTrackAdjustment = rawSong.tags.replayGainTrackAdjustment,
|
||||
replayGainAlbumAdjustment = rawSong.tags.replayGainAlbumAdjustment,
|
||||
cover = rawSong.cover,
|
||||
mimeType = rawSong.properties.mimeType,
|
||||
bitrate = rawSong.properties.bitrate,
|
||||
sampleRate = rawSong.properties.sampleRate)
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* Cover.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.cover
|
||||
|
||||
import org.oxycblt.musikr.Song
|
||||
|
||||
sealed interface Cover {
|
||||
val key: String
|
||||
|
||||
data class Single(override val key: String) : Cover
|
||||
|
||||
class Multi(val all: List<Single>) : Cover {
|
||||
override val key = "multi@${all.hashCode()}"
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun nil() = Multi(listOf())
|
||||
|
||||
fun single(key: String) = Single(key)
|
||||
|
||||
fun multi(songs: Collection<Song>) = order(songs).run { Multi(this) }
|
||||
|
||||
private fun order(songs: Collection<Song>) =
|
||||
songs
|
||||
.mapNotNull { it.cover }
|
||||
.groupBy { it.key }
|
||||
.entries
|
||||
.sortedByDescending { it.key }
|
||||
.sortedByDescending { it.value.size }
|
||||
.map { it.value.first() }
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* CoverFiles.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.cover
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
internal interface CoverFiles {
|
||||
suspend fun read(id: String): InputStream?
|
||||
|
||||
suspend fun write(id: String, data: ByteArray)
|
||||
|
||||
companion object {
|
||||
fun from(context: Context, path: String, format: CoverFormat): CoverFiles =
|
||||
CoverFilesImpl(File(context.filesDir, path).also { it.mkdirs() }, format)
|
||||
}
|
||||
}
|
||||
|
||||
private class CoverFilesImpl(private val dir: File, private val coverFormat: CoverFormat) :
|
||||
CoverFiles {
|
||||
private val fileMutexes = mutableMapOf<String, Mutex>()
|
||||
private val mapMutex = Mutex()
|
||||
|
||||
private suspend fun getMutexForFile(file: String): Mutex {
|
||||
return mapMutex.withLock { fileMutexes.getOrPut(file) { Mutex() } }
|
||||
}
|
||||
|
||||
override suspend fun read(id: String): InputStream? =
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
File(dir, getTargetFilePath(id)).inputStream()
|
||||
} catch (e: IOException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun write(id: String, data: ByteArray) {
|
||||
val fileMutex = getMutexForFile(id)
|
||||
|
||||
fileMutex.withLock {
|
||||
val targetFile = File(dir, getTargetFilePath(id))
|
||||
if (targetFile.exists()) {
|
||||
return
|
||||
}
|
||||
withContext(Dispatchers.IO) {
|
||||
val tempFile = File(dir, getTempFilePath(id))
|
||||
|
||||
try {
|
||||
tempFile.outputStream().use { coverFormat.transcodeInto(data, it) }
|
||||
tempFile.renameTo(targetFile)
|
||||
} catch (e: IOException) {
|
||||
tempFile.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getTargetFilePath(name: String) = "cover_${name}.${coverFormat.extension}"
|
||||
|
||||
private fun getTempFilePath(name: String) = "${getTargetFilePath(name)}.tmp"
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* CoverFormat.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.cover
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.os.Build
|
||||
import java.io.OutputStream
|
||||
|
||||
internal interface CoverFormat {
|
||||
val extension: String
|
||||
|
||||
fun transcodeInto(data: ByteArray, output: OutputStream): Boolean
|
||||
|
||||
companion object {
|
||||
fun webp(): CoverFormat = WebpCoverFormat()
|
||||
}
|
||||
}
|
||||
|
||||
private class WebpCoverFormat() : CoverFormat {
|
||||
override val extension = EXTENSION
|
||||
|
||||
override fun transcodeInto(data: ByteArray, output: OutputStream) =
|
||||
BitmapFactory.Options().run {
|
||||
inJustDecodeBounds = true
|
||||
BitmapFactory.decodeByteArray(data, 0, data.size, this)
|
||||
inSampleSize = calculateInSampleSize(SIZE)
|
||||
inJustDecodeBounds = false
|
||||
val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size, this) ?: return@run false
|
||||
bitmap.compress(FORMAT, QUALITY, output)
|
||||
true
|
||||
}
|
||||
|
||||
private fun BitmapFactory.Options.calculateInSampleSize(size: Int): Int {
|
||||
var inSampleSize = 1
|
||||
val (height, width) = outHeight to outWidth
|
||||
|
||||
if (height > size || width > size) {
|
||||
val halfHeight = height / 2
|
||||
val halfWidth = width / 2
|
||||
while ((halfHeight / inSampleSize) >= size && (halfWidth / inSampleSize) >= size) {
|
||||
inSampleSize *= 2
|
||||
}
|
||||
}
|
||||
return inSampleSize
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SIZE = 750
|
||||
val FORMAT =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
Bitmap.CompressFormat.WEBP_LOSSY
|
||||
} else {
|
||||
Bitmap.CompressFormat.WEBP
|
||||
}
|
||||
const val QUALITY = 80
|
||||
const val EXTENSION = "webp"
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* CoverIdentifier.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.cover
|
||||
|
||||
import java.security.MessageDigest
|
||||
|
||||
interface CoverIdentifier {
|
||||
suspend fun identify(data: ByteArray): String
|
||||
|
||||
companion object {
|
||||
fun md5(): CoverIdentifier = MD5CoverIdentifier()
|
||||
}
|
||||
}
|
||||
|
||||
private class MD5CoverIdentifier() : CoverIdentifier {
|
||||
@OptIn(ExperimentalStdlibApi::class)
|
||||
override suspend fun identify(data: ByteArray): String {
|
||||
val digest =
|
||||
MessageDigest.getInstance("MD5").run {
|
||||
update(data)
|
||||
digest()
|
||||
}
|
||||
return digest.toHexString()
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* StoredCovers.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.cover
|
||||
|
||||
import android.content.Context
|
||||
import java.io.InputStream
|
||||
|
||||
interface StoredCovers {
|
||||
suspend fun read(cover: Cover.Single): InputStream?
|
||||
|
||||
suspend fun write(data: ByteArray): Cover.Single?
|
||||
|
||||
companion object {
|
||||
fun from(context: Context, path: String): StoredCovers =
|
||||
FileStoredCovers(
|
||||
CoverIdentifier.md5(), CoverFiles.from(context, path, CoverFormat.webp()))
|
||||
}
|
||||
}
|
||||
|
||||
private class FileStoredCovers(
|
||||
private val coverIdentifier: CoverIdentifier,
|
||||
private val coverFiles: CoverFiles
|
||||
) : StoredCovers {
|
||||
override suspend fun read(cover: Cover.Single) = coverFiles.read(cover.key)
|
||||
|
||||
override suspend fun write(data: ByteArray) =
|
||||
coverIdentifier.identify(data).let { key ->
|
||||
coverFiles.write(key, data)
|
||||
Cover.Single(key)
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Format.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs
|
||||
|
||||
import android.webkit.MimeTypeMap
|
||||
import org.oxycblt.musikr.util.unlikelyToBeNull
|
||||
|
||||
sealed interface Format {
|
||||
val mimeType: String
|
||||
|
||||
data object MPEG3 : Format {
|
||||
override val mimeType = "audio/mpeg"
|
||||
}
|
||||
|
||||
data class MPEG4(val containing: Format?) : Format {
|
||||
override val mimeType = "audio/mp4"
|
||||
}
|
||||
|
||||
data object AAC : Format {
|
||||
override val mimeType = "audio/aac"
|
||||
}
|
||||
|
||||
data object ALAC : Format {
|
||||
override val mimeType = "audio/alac"
|
||||
}
|
||||
|
||||
data class Ogg(val containing: Format?) : Format {
|
||||
override val mimeType = "audio/ogg"
|
||||
}
|
||||
|
||||
data object Opus : Format {
|
||||
override val mimeType = "audio/opus"
|
||||
}
|
||||
|
||||
data object Vorbis : Format {
|
||||
override val mimeType = "audio/vorbis"
|
||||
}
|
||||
|
||||
data object FLAC : Format {
|
||||
override val mimeType = "audio/flac"
|
||||
}
|
||||
|
||||
data object Wav : Format {
|
||||
override val mimeType = "audio/wav"
|
||||
}
|
||||
|
||||
data class Unknown(override val mimeType: String) : Format {
|
||||
val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)?.uppercase()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val CODEC_MAP =
|
||||
mapOf(
|
||||
"audio/mpeg" to MPEG3,
|
||||
"audio/mp3" to MPEG3,
|
||||
"audio/aac" to AAC,
|
||||
"audio/aacp" to AAC,
|
||||
"audio/3gpp" to AAC,
|
||||
"audio/3gpp2" to AAC,
|
||||
"audio/alac" to ALAC,
|
||||
"audio/opus" to Opus,
|
||||
"audio/vorbis" to Vorbis,
|
||||
"audio/flac" to FLAC,
|
||||
"audio/wav" to Wav,
|
||||
"audio/raw" to Wav,
|
||||
"audio/x-wav" to Wav,
|
||||
"audio/vnd.wave" to Wav,
|
||||
"audio/wave" to Wav,
|
||||
)
|
||||
|
||||
fun infer(containerMimeType: String, codecMimeType: String): Format {
|
||||
val codecFormat = CODEC_MAP[codecMimeType]
|
||||
if (codecFormat != null) {
|
||||
// Codec found, possibly wrap in container.
|
||||
return unlikelyToBeNull(wrapInContainer(containerMimeType, codecFormat))
|
||||
}
|
||||
val extensionFormat = CODEC_MAP[containerMimeType]
|
||||
if (extensionFormat != null) {
|
||||
// Standalone container of some codec.
|
||||
return extensionFormat
|
||||
}
|
||||
return wrapInContainer(containerMimeType, null) ?: Unknown(containerMimeType)
|
||||
}
|
||||
|
||||
private fun wrapInContainer(containerMimeType: String, format: Format?) =
|
||||
when (containerMimeType) {
|
||||
"audio/mp4",
|
||||
"audio/mp4a-latm",
|
||||
"audio/mpeg4-generic" -> MPEG4(format)
|
||||
"audio/ogg",
|
||||
"application/ogg",
|
||||
"application/x-ogg" -> Ogg(format)
|
||||
else -> format
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* MusicLocation.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import org.oxycblt.musikr.fs.path.DocumentPathFactory
|
||||
import org.oxycblt.musikr.fs.query.contentResolverSafe
|
||||
import org.oxycblt.musikr.tag.util.splitEscaped
|
||||
|
||||
class MusicLocation internal constructor(val uri: Uri, val path: Path) {
|
||||
override fun equals(other: Any?) = other is MusicLocation && 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) {
|
||||
context.contentResolverSafe.takePersistableUriPermission(
|
||||
uri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
|
||||
}
|
||||
return MusicLocation(uri, path)
|
||||
}
|
||||
|
||||
fun existing(context: Context, uri: Uri): MusicLocation? {
|
||||
val documentPathFactory = DocumentPathFactory.from(context)
|
||||
if (!DocumentsContract.isTreeUri(uri)) return null
|
||||
val notPersisted =
|
||||
context.contentResolverSafe.persistedUriPermissions.none {
|
||||
it.uri == uri && it.isReadPermission && it.isWritePermission
|
||||
}
|
||||
if (notPersisted) return null
|
||||
val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null
|
||||
return MusicLocation(uri, path)
|
||||
}
|
||||
|
||||
fun toString(list: List<MusicLocation>) =
|
||||
list.joinToString(";") { it.uri.toString().replace(";", "\\;") }
|
||||
|
||||
fun existing(context: Context, string: String): List<MusicLocation> {
|
||||
return string.splitEscaped { it == ';' }.mapNotNull { existing(context, Uri.parse(it)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Path.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* An abstraction of an android file system path, including the volume and relative path.
|
||||
*
|
||||
* @param volume The volume that the path is on.
|
||||
* @param components The components of the path of the file, relative to the root of the volume.
|
||||
*/
|
||||
data class Path(
|
||||
val volume: Volume,
|
||||
val components: Components,
|
||||
) {
|
||||
/** The name of the file/directory. */
|
||||
val name: String?
|
||||
get() = components.name
|
||||
|
||||
/** The parent directory of the path, or itself if it's the root path. */
|
||||
val directory: Path
|
||||
get() = Path(volume, components.parent())
|
||||
|
||||
/**
|
||||
* Transforms this [Path] into a "file" of the given name that's within the "directory"
|
||||
* represented by the current path. Ex. "/storage/emulated/0/Music" ->
|
||||
* "/storage/emulated/0/Music/file.mp3"
|
||||
*
|
||||
* @param fileName The name of the file to append to the path.
|
||||
* @return The new [Path] instance.
|
||||
*/
|
||||
fun file(fileName: String) = Path(volume, components.child(fileName))
|
||||
|
||||
/**
|
||||
* Resolves the [Path] in a human-readable format.
|
||||
*
|
||||
* @param context [Context] required to obtain human-readable strings.
|
||||
*/
|
||||
fun resolve(context: Context) = "${volume.resolveName(context)}/$components"
|
||||
}
|
||||
|
||||
sealed interface Volume {
|
||||
/** The name of the volume as it appears in MediaStore. */
|
||||
val mediaStoreName: String?
|
||||
|
||||
/**
|
||||
* The components of the path to the volume, relative from the system root. Should not be used
|
||||
* except for compatibility purposes.
|
||||
*/
|
||||
val components: Components?
|
||||
|
||||
/** Resolves the name of the volume in a human-readable format. */
|
||||
fun resolveName(context: Context): String
|
||||
|
||||
/** A volume representing the device's internal storage. */
|
||||
interface Internal : Volume
|
||||
|
||||
/** A volume representing an external storage device, identified by a UUID. */
|
||||
interface External : Volume {
|
||||
/** The UUID of the volume. */
|
||||
val id: String?
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The components of a path. This allows the path to be manipulated without having tp handle
|
||||
* separator parsing.
|
||||
*
|
||||
* @param components The components of the path.
|
||||
*/
|
||||
@JvmInline
|
||||
value class Components private constructor(val components: List<String>) {
|
||||
/** The name of the file/directory. */
|
||||
val name: String?
|
||||
get() = components.lastOrNull()
|
||||
|
||||
override fun toString() = unixString
|
||||
|
||||
/** Formats these components using the unix file separator (/) */
|
||||
val unixString: String
|
||||
get() = components.joinToString(File.separator)
|
||||
|
||||
/** Formats these components using the windows file separator (\). */
|
||||
val windowsString: String
|
||||
get() = components.joinToString("\\")
|
||||
|
||||
/**
|
||||
* Returns a new [Components] instance with the last element of the path removed as a "parent"
|
||||
* element of the original instance.
|
||||
*
|
||||
* @return The new [Components] instance, or the original instance if it's the root path.
|
||||
*/
|
||||
fun parent() = Components(components.dropLast(1))
|
||||
|
||||
/**
|
||||
* Returns a new [Components] instance with the given name appended to the end of the path as a
|
||||
* "child" element of the original instance.
|
||||
*
|
||||
* @param name The name of the file/directory to append to the path.
|
||||
*/
|
||||
fun child(name: String) =
|
||||
if (name.isNotEmpty()) {
|
||||
Components(components + name.trimSlashes())
|
||||
} else {
|
||||
this
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the first [n] elements of the path, effectively resulting in a path that is n levels
|
||||
* deep.
|
||||
*
|
||||
* @param n The number of elements to remove.
|
||||
* @return The new [Components] instance.
|
||||
*/
|
||||
fun depth(n: Int) = Components(components.drop(n))
|
||||
|
||||
/**
|
||||
* Concatenates this [Components] instance with another.
|
||||
*
|
||||
* @param other The [Components] instance to concatenate with.
|
||||
* @return The new [Components] instance.
|
||||
*/
|
||||
fun child(other: Components) = Components(components + other.components)
|
||||
|
||||
/**
|
||||
* Returns the given [Components] has a prefix equal to this [Components] instance. Effectively,
|
||||
* as if the given [Components] instance was a child of this [Components] instance.
|
||||
*/
|
||||
fun contains(other: Components): Boolean {
|
||||
if (other.components.size < components.size) {
|
||||
return false
|
||||
}
|
||||
|
||||
return components == other.components.take(components.size)
|
||||
}
|
||||
|
||||
fun containing(other: Components) = Components(other.components.drop(components.size))
|
||||
|
||||
companion object {
|
||||
fun nil() = Components(listOf())
|
||||
|
||||
/**
|
||||
* Parses a path string into a [Components] instance by the unix path separator (/).
|
||||
*
|
||||
* @param path The path string to parse.
|
||||
* @return The [Components] instance.
|
||||
*/
|
||||
fun parseUnix(path: String) =
|
||||
Components(path.trimSlashes().split(File.separatorChar).filter { it.isNotEmpty() })
|
||||
|
||||
/**
|
||||
* Parses a path string into a [Components] instance by the windows path separator.
|
||||
*
|
||||
* @param path The path string to parse.
|
||||
* @return The [Components] instance.
|
||||
*/
|
||||
fun parseWindows(path: String) =
|
||||
Components(path.trimSlashes().split('\\').filter { it.isNotEmpty() })
|
||||
|
||||
private fun String.trimSlashes() = trimStart(File.separatorChar).trimEnd(File.separatorChar)
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* DocumentPathFactory.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs.path
|
||||
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import java.io.File
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.Volume
|
||||
import org.oxycblt.musikr.fs.query.contentResolverSafe
|
||||
import org.oxycblt.musikr.fs.query.useQuery
|
||||
|
||||
/**
|
||||
* A factory for parsing the reverse-engineered format of the URIs obtained from document picker.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface DocumentPathFactory {
|
||||
/**
|
||||
* Unpacks a document URI into a [Path] instance, using [fromDocumentId].
|
||||
*
|
||||
* @param uri The document URI to unpack.
|
||||
* @return The [Path] instance, or null if the URI could not be unpacked.
|
||||
*/
|
||||
fun unpackDocumentUri(uri: Uri): Path?
|
||||
|
||||
/**
|
||||
* Unpacks a document tree URI into a [Path] instance, using [fromDocumentId].
|
||||
*
|
||||
* @param uri The document tree URI to unpack.
|
||||
* @return The [Path] instance, or null if the URI could not be unpacked.
|
||||
*/
|
||||
fun unpackDocumentTreeUri(uri: Uri): Path?
|
||||
|
||||
/**
|
||||
* Serializes a [Path] instance into a document tree URI format path.
|
||||
*
|
||||
* @param path The [Path] instance to serialize.
|
||||
* @return The serialized path.
|
||||
*/
|
||||
fun toDocumentId(path: Path): String
|
||||
|
||||
/**
|
||||
* Deserializes a document tree URI format path into a [Path] instance.
|
||||
*
|
||||
* @param path The path to deserialize.
|
||||
* @return The [Path] instance, or null if the path could not be deserialized.
|
||||
*/
|
||||
fun fromDocumentId(path: String): Path?
|
||||
|
||||
companion object {
|
||||
fun from(context: Context): DocumentPathFactory {
|
||||
val volumeManager = VolumeManager.from(context)
|
||||
val pathInterpreter = MediaStorePathInterpreter.Factory.from(volumeManager)
|
||||
return DocumentPathFactoryImpl(context, volumeManager, pathInterpreter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class DocumentPathFactoryImpl(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val volumeManager: VolumeManager,
|
||||
private val mediaStorePathInterpreterFactory: MediaStorePathInterpreter.Factory
|
||||
) : DocumentPathFactory {
|
||||
override fun unpackDocumentUri(uri: Uri): Path? {
|
||||
val id = DocumentsContract.getDocumentId(uri)
|
||||
val numericId = id.toLongOrNull()
|
||||
return if (numericId != null) {
|
||||
// The document URI is special and points to an entry only accessible via
|
||||
// ContentResolver. In this case, we have to manually query MediaStore.
|
||||
for (prefix in POSSIBLE_CONTENT_URI_PREFIXES) {
|
||||
val contentUri = ContentUris.withAppendedId(prefix, numericId)
|
||||
|
||||
val path =
|
||||
context.contentResolverSafe.useQuery(
|
||||
contentUri, mediaStorePathInterpreterFactory.projection) {
|
||||
it.moveToFirst()
|
||||
mediaStorePathInterpreterFactory.wrap(it).extract()
|
||||
}
|
||||
|
||||
if (path != null) {
|
||||
return path
|
||||
}
|
||||
}
|
||||
|
||||
null
|
||||
} else {
|
||||
fromDocumentId(id)
|
||||
}
|
||||
}
|
||||
|
||||
override fun unpackDocumentTreeUri(uri: Uri): Path? {
|
||||
// Convert the document tree URI into it's relative path form, which can then be
|
||||
// parsed into a Directory instance.
|
||||
val docUri =
|
||||
DocumentsContract.buildDocumentUriUsingTree(
|
||||
uri, DocumentsContract.getTreeDocumentId(uri))
|
||||
val treeUri = DocumentsContract.getTreeDocumentId(docUri)
|
||||
return fromDocumentId(treeUri)
|
||||
}
|
||||
|
||||
override fun toDocumentId(path: Path): String =
|
||||
when (val volume = path.volume) {
|
||||
// The primary storage has a volume prefix of "primary", regardless
|
||||
// of if it's internal or not.
|
||||
is Volume.Internal -> "$DOCUMENT_URI_PRIMARY_NAME:${path.components}"
|
||||
// Document tree URIs consist of a prefixed volume name followed by a relative path.
|
||||
is Volume.External -> "${volume.id}:${path.components}"
|
||||
}
|
||||
|
||||
override fun fromDocumentId(path: String): Path? {
|
||||
// Document tree URIs consist of a prefixed volume name followed by a relative path,
|
||||
// delimited with a colon.
|
||||
val split = path.split(File.pathSeparator, limit = 2)
|
||||
val volume =
|
||||
when (split[0]) {
|
||||
// The primary storage has a volume prefix of "primary", regardless
|
||||
// of if it's internal or not.
|
||||
DOCUMENT_URI_PRIMARY_NAME -> volumeManager.getInternalVolume()
|
||||
// Removable storage has a volume prefix of it's UUID, try to find it
|
||||
// within StorageManager's volume list.
|
||||
else ->
|
||||
volumeManager.getVolumes().find { it is Volume.External && it.id == split[0] }
|
||||
}
|
||||
val relativePath = split.getOrNull(1) ?: return null
|
||||
return Path(volume ?: return null, Components.parseUnix(relativePath))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DOCUMENT_URI_PRIMARY_NAME = "primary"
|
||||
|
||||
private val POSSIBLE_CONTENT_URI_PREFIXES =
|
||||
arrayOf(
|
||||
Uri.parse("content://downloads/public_downloads"),
|
||||
Uri.parse("content://downloads/my_downloads"))
|
||||
}
|
||||
}
|
||||
@@ -1,247 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* MediaStorePathInterpreter.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs.path
|
||||
|
||||
import android.database.Cursor
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
* Wrapper around a [Cursor] that interprets path information on a per-API/manufacturer basis.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
sealed interface MediaStorePathInterpreter {
|
||||
/**
|
||||
* Extract a [Path] from the wrapped [Cursor]. This should be called after the cursor has been
|
||||
* moved to the row that should be interpreted.
|
||||
*
|
||||
* @return The [Path] instance, or null if the path could not be extracted.
|
||||
*/
|
||||
fun extract(): Path?
|
||||
|
||||
interface Factory {
|
||||
/** The columns that must be added to a query to support this interpreter. */
|
||||
val projection: Array<String>
|
||||
|
||||
/**
|
||||
* Wrap a [Cursor] with this interpreter. This cursor should be the result of a query
|
||||
* containing the columns specified by [projection].
|
||||
*
|
||||
* @param cursor The [Cursor] to wrap.
|
||||
* @return A new [MediaStorePathInterpreter] that will work best on the device's API level.
|
||||
*/
|
||||
fun wrap(cursor: Cursor): MediaStorePathInterpreter
|
||||
|
||||
/**
|
||||
* Create a selector that will filter the given paths. By default this will filter *to* the
|
||||
* given paths, to exclude them, use a NOT.
|
||||
*
|
||||
* @param paths The paths to filter for.
|
||||
* @return A selector that will filter to the given paths, or null if a selector could not
|
||||
* be created from the paths.
|
||||
*/
|
||||
fun createSelector(paths: List<Path>): Selector?
|
||||
|
||||
/**
|
||||
* A selector that will filter to the given paths.
|
||||
*
|
||||
* @param template The template to use for the selector.
|
||||
* @param args The arguments to use for the selector.
|
||||
* @see Factory.createSelector
|
||||
*/
|
||||
data class Selector(val template: String, val args: List<String>)
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Create a [MediaStorePathInterpreter.Factory] that will work best on the device's API
|
||||
* level.
|
||||
*
|
||||
* @param volumeManager The [VolumeManager] to use for volume information.
|
||||
*/
|
||||
fun from(volumeManager: VolumeManager) =
|
||||
when {
|
||||
// Huawei violates the API docs and prevents you from accessing the new path
|
||||
// fields without first granting access to them through SAF. Fall back to DATA
|
||||
// instead.
|
||||
Build.MANUFACTURER.equals("huawei", ignoreCase = true) ||
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ->
|
||||
DataMediaStorePathInterpreter.Factory(volumeManager)
|
||||
else -> VolumeMediaStorePathInterpreter.Factory(volumeManager)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper around a [Cursor] that interprets the DATA column as a path. Create an instance with
|
||||
* [Factory].
|
||||
*/
|
||||
private class DataMediaStorePathInterpreter
|
||||
private constructor(private val cursor: Cursor, volumeManager: VolumeManager) :
|
||||
MediaStorePathInterpreter {
|
||||
private val dataIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)
|
||||
private val volumes = volumeManager.getVolumes()
|
||||
|
||||
override fun extract(): Path? {
|
||||
val data = Components.parseUnix(cursor.getString(dataIndex))
|
||||
|
||||
// Find the volume that transforms the DATA column into a relative path. This is
|
||||
// the Directory we will use.
|
||||
for (volume in volumes) {
|
||||
val volumePath = volume.components ?: continue
|
||||
if (volumePath.contains(data)) {
|
||||
return Path(volume, data.depth(volumePath.components.size))
|
||||
}
|
||||
}
|
||||
|
||||
L.e("Could not find volume for $data [tried: ${volumes.map { it.components }}]")
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory for [DataMediaStorePathInterpreter].
|
||||
*
|
||||
* @param volumeManager The [VolumeManager] to use for volume information.
|
||||
*/
|
||||
class Factory(private val volumeManager: VolumeManager) : MediaStorePathInterpreter.Factory {
|
||||
override val projection: Array<String>
|
||||
get() =
|
||||
arrayOf(
|
||||
MediaStore.Audio.AudioColumns.DISPLAY_NAME, MediaStore.Audio.AudioColumns.DATA)
|
||||
|
||||
override fun createSelector(
|
||||
paths: List<Path>
|
||||
): MediaStorePathInterpreter.Factory.Selector? {
|
||||
val args = mutableListOf<String>()
|
||||
var template = ""
|
||||
for (i in paths.indices) {
|
||||
val path = paths[i]
|
||||
val volume = path.volume.components ?: continue
|
||||
template +=
|
||||
if (args.isEmpty()) {
|
||||
"${MediaStore.Audio.AudioColumns.DATA} LIKE ?"
|
||||
} else {
|
||||
" OR ${MediaStore.Audio.AudioColumns.DATA} LIKE ?"
|
||||
}
|
||||
args.add("/${volume}/${path.components}%")
|
||||
}
|
||||
|
||||
if (template.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
|
||||
return MediaStorePathInterpreter.Factory.Selector(template, args)
|
||||
}
|
||||
|
||||
override fun wrap(cursor: Cursor): MediaStorePathInterpreter =
|
||||
DataMediaStorePathInterpreter(cursor, volumeManager)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper around a [Cursor] that interprets the VOLUME_NAME, RELATIVE_PATH, and DISPLAY_NAME
|
||||
* columns as a path. Create an instance with [Factory].
|
||||
*/
|
||||
private class VolumeMediaStorePathInterpreter
|
||||
private constructor(private val cursor: Cursor, volumeManager: VolumeManager) :
|
||||
MediaStorePathInterpreter {
|
||||
private val displayNameIndex =
|
||||
cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DISPLAY_NAME)
|
||||
private val volumeIndex =
|
||||
cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.VOLUME_NAME)
|
||||
private val relativePathIndex =
|
||||
cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.RELATIVE_PATH)
|
||||
private val volumes = volumeManager.getVolumes()
|
||||
|
||||
override fun extract(): Path? {
|
||||
// Find the StorageVolume whose MediaStore name corresponds to it.
|
||||
val volumeName = cursor.getString(volumeIndex)
|
||||
// Relative path does not include file name, must use DISPLAY_NAME and add it
|
||||
// in manually.
|
||||
val relativePath = cursor.getString(relativePathIndex)
|
||||
val displayName = cursor.getString(displayNameIndex)
|
||||
val volume = volumes.find { it.mediaStoreName == volumeName }
|
||||
if (volume == null) {
|
||||
L.e(
|
||||
"Could not find volume for $volumeName:$relativePath/$displayName [tried: ${volumes.map { it.mediaStoreName }}]")
|
||||
return null
|
||||
}
|
||||
val components = Components.parseUnix(relativePath).child(displayName)
|
||||
return Path(volume, components)
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory for [VolumeMediaStorePathInterpreter].
|
||||
*
|
||||
* @param volumeManager The [VolumeManager] to use for volume information.
|
||||
*/
|
||||
class Factory(private val volumeManager: VolumeManager) : MediaStorePathInterpreter.Factory {
|
||||
override val projection: Array<String>
|
||||
get() =
|
||||
arrayOf(
|
||||
// After API 29, we now have access to the volume name and relative
|
||||
// path, which hopefully are more standard and less likely to break
|
||||
// compared to DATA.
|
||||
MediaStore.Audio.AudioColumns.DISPLAY_NAME,
|
||||
MediaStore.Audio.AudioColumns.VOLUME_NAME,
|
||||
MediaStore.Audio.AudioColumns.RELATIVE_PATH)
|
||||
|
||||
// The selector should be configured to compare both the volume name and relative path
|
||||
// of the given directories, albeit with some conversion to the analogous MediaStore
|
||||
// column values.
|
||||
|
||||
override fun createSelector(
|
||||
paths: List<Path>
|
||||
): MediaStorePathInterpreter.Factory.Selector? {
|
||||
val args = mutableListOf<String>()
|
||||
var template = ""
|
||||
for (i in paths.indices) {
|
||||
val path = paths[i]
|
||||
template +=
|
||||
if (args.isEmpty()) {
|
||||
"(${MediaStore.Audio.AudioColumns.VOLUME_NAME} LIKE ? " +
|
||||
"AND ${MediaStore.Audio.AudioColumns.RELATIVE_PATH} LIKE ?)"
|
||||
} else {
|
||||
" OR (${MediaStore.Audio.AudioColumns.VOLUME_NAME} LIKE ? " +
|
||||
"AND ${MediaStore.Audio.AudioColumns.RELATIVE_PATH} LIKE ?)"
|
||||
}
|
||||
// MediaStore uses a different naming scheme for it's volume column. Convert this
|
||||
// directory's volume to it.
|
||||
args.add(path.volume.mediaStoreName ?: return null)
|
||||
// "%" signifies to accept any DATA value that begins with the Directory's path,
|
||||
// thus recursively filtering all files in the directory.
|
||||
args.add("${path.components}%")
|
||||
}
|
||||
|
||||
if (template.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
|
||||
return MediaStorePathInterpreter.Factory.Selector(template, args)
|
||||
}
|
||||
|
||||
override fun wrap(cursor: Cursor): MediaStorePathInterpreter =
|
||||
VolumeMediaStorePathInterpreter(cursor, volumeManager)
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* VolumeCompat.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs.path
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.storage.StorageManager
|
||||
import android.os.storage.StorageVolume
|
||||
import android.provider.MediaStore
|
||||
import java.lang.reflect.Method
|
||||
import org.oxycblt.musikr.util.lazyReflectedMethod
|
||||
|
||||
// Largely derived from Material Files: https://github.com/zhanghai/MaterialFiles
|
||||
|
||||
/**
|
||||
* Provides the analogous method to [StorageVolume.getDirectory] method that is usable from API 21
|
||||
* to API 23, in which the [StorageVolume] API was hidden and differed greatly.
|
||||
*
|
||||
* @see StorageVolume.getDirectory
|
||||
*/
|
||||
@Suppress("NewApi")
|
||||
private val svApi21GetPathMethod: Method by lazyReflectedMethod(StorageVolume::class, "getPath")
|
||||
|
||||
/**
|
||||
* The list of [StorageVolume]s currently recognized by [StorageManager], in a version-compatible
|
||||
* manner.
|
||||
*
|
||||
* @see StorageManager.getStorageVolumes
|
||||
*/
|
||||
val StorageManager.storageVolumesCompat: List<StorageVolume>
|
||||
get() = storageVolumes.toList()
|
||||
|
||||
/**
|
||||
* The the absolute path to this [StorageVolume]'s directory within the file-system, in a
|
||||
* version-compatible manner. Will be null if the [StorageVolume] cannot be read.
|
||||
*
|
||||
* @see StorageVolume.getDirectory
|
||||
*/
|
||||
val StorageVolume.directoryCompat: String?
|
||||
@SuppressLint("NewApi")
|
||||
get() =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
directory?.absolutePath
|
||||
} else {
|
||||
// Replicate API: Analogous method if mounted, null if not
|
||||
when (stateCompat) {
|
||||
Environment.MEDIA_MOUNTED,
|
||||
Environment.MEDIA_MOUNTED_READ_ONLY -> svApi21GetPathMethod.invoke(this) as String
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the human-readable description of this volume, such as "Internal Shared Storage".
|
||||
*
|
||||
* @param context [Context] required to obtain human-readable string resources.
|
||||
* @return A human-readable name for this volume.
|
||||
*/
|
||||
@SuppressLint("NewApi")
|
||||
fun StorageVolume.getDescriptionCompat(context: Context): String = getDescription(context)
|
||||
|
||||
/**
|
||||
* If this [StorageVolume] is considered the "Primary" volume where the Android System is kept. May
|
||||
* still be a removable volume.
|
||||
*
|
||||
* @see StorageVolume.isPrimary
|
||||
*/
|
||||
val StorageVolume.isPrimaryCompat: Boolean
|
||||
@SuppressLint("NewApi") get() = isPrimary
|
||||
|
||||
/**
|
||||
* If this storage is "emulated", i.e intrinsic to the device, obtained in a version compatible
|
||||
* manner.
|
||||
*
|
||||
* @see StorageVolume.isEmulated
|
||||
*/
|
||||
val StorageVolume.isEmulatedCompat: Boolean
|
||||
@SuppressLint("NewApi") get() = isEmulated
|
||||
|
||||
/**
|
||||
* If this [StorageVolume] represents the "Internal Shared Storage" volume, also known as "primary"
|
||||
* to [MediaStore] and Document [Uri]s, obtained in a version compatible manner.
|
||||
*/
|
||||
val StorageVolume.isInternalCompat: Boolean
|
||||
// Must contain the android system AND be an emulated drive, as non-emulated system
|
||||
// volumes use their UUID instead of primary in MediaStore/Document URIs.
|
||||
get() = isPrimaryCompat && isEmulatedCompat
|
||||
|
||||
/**
|
||||
* The unique identifier for this [StorageVolume], obtained in a version compatible manner. Can be
|
||||
* null.
|
||||
*
|
||||
* @see StorageVolume.getUuid
|
||||
*/
|
||||
val StorageVolume.uuidCompat: String?
|
||||
@SuppressLint("NewApi") get() = uuid
|
||||
|
||||
/**
|
||||
* The current state of this [StorageVolume], such as "mounted" or "read-only", obtained in a
|
||||
* version compatible manner.
|
||||
*
|
||||
* @see StorageVolume.getState
|
||||
*/
|
||||
val StorageVolume.stateCompat: String
|
||||
@SuppressLint("NewApi") get() = state
|
||||
|
||||
/**
|
||||
* Returns the name of this volume that can be used to interact with [MediaStore], in a version
|
||||
* compatible manner. Will be null if the volume is not scanned by [MediaStore].
|
||||
*
|
||||
* @see StorageVolume.getMediaStoreVolumeName
|
||||
*/
|
||||
val StorageVolume.mediaStoreVolumeNameCompat: String?
|
||||
get() =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
mediaStoreVolumeName
|
||||
} else {
|
||||
// Replicate API: primary_external if primary storage, lowercase uuid otherwise
|
||||
if (isPrimaryCompat) {
|
||||
// "primary_external" is used in all versions that Auxio supports, is safe to use.
|
||||
@Suppress("NewApi") MediaStore.VOLUME_EXTERNAL_PRIMARY
|
||||
} else {
|
||||
uuidCompat?.lowercase()
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* VolumeManager.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs.path
|
||||
|
||||
import android.content.Context
|
||||
import android.os.storage.StorageManager
|
||||
import android.os.storage.StorageVolume
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Volume
|
||||
|
||||
/** A wrapper around [StorageManager] that provides instances of the [Volume] interface. */
|
||||
interface VolumeManager {
|
||||
/**
|
||||
* The internal storage volume of the device.
|
||||
*
|
||||
* @see StorageManager.getPrimaryStorageVolume
|
||||
*/
|
||||
fun getInternalVolume(): Volume.Internal
|
||||
|
||||
/**
|
||||
* The list of [Volume]s currently recognized by [StorageManager].
|
||||
*
|
||||
* @see StorageManager.getStorageVolumes
|
||||
*/
|
||||
fun getVolumes(): List<Volume>
|
||||
|
||||
companion object {
|
||||
fun from(context: Context): VolumeManager =
|
||||
VolumeManagerImpl(context.getSystemService(StorageManager::class.java))
|
||||
}
|
||||
}
|
||||
|
||||
private class VolumeManagerImpl(private val storageManager: StorageManager) : VolumeManager {
|
||||
override fun getInternalVolume(): Volume.Internal =
|
||||
InternalVolumeImpl(storageManager.primaryStorageVolume)
|
||||
|
||||
override fun getVolumes() =
|
||||
storageManager.storageVolumesCompat.map {
|
||||
if (it.isInternalCompat) {
|
||||
InternalVolumeImpl(it)
|
||||
} else {
|
||||
ExternalVolumeImpl(it)
|
||||
}
|
||||
}
|
||||
|
||||
private data class InternalVolumeImpl(val storageVolume: StorageVolume) : Volume.Internal {
|
||||
override val mediaStoreName
|
||||
get() = storageVolume.mediaStoreVolumeNameCompat
|
||||
|
||||
override val components
|
||||
get() = storageVolume.directoryCompat?.let(Components.Companion::parseUnix)
|
||||
|
||||
override fun resolveName(context: Context) = storageVolume.getDescriptionCompat(context)
|
||||
}
|
||||
|
||||
private data class ExternalVolumeImpl(val storageVolume: StorageVolume) : Volume.External {
|
||||
override val id
|
||||
get() = storageVolume.uuidCompat
|
||||
|
||||
override val mediaStoreName
|
||||
get() = storageVolume.mediaStoreVolumeNameCompat
|
||||
|
||||
override val components
|
||||
get() = storageVolume.directoryCompat?.let(Components.Companion::parseUnix)
|
||||
|
||||
override fun resolveName(context: Context) = storageVolume.getDescriptionCompat(context)
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* DeviceFiles.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs.query
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
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.flattenMerge
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
|
||||
interface DeviceFiles {
|
||||
fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile>
|
||||
|
||||
companion object {
|
||||
fun from(context: Context): DeviceFiles = DeviceFilesImpl(context.contentResolverSafe)
|
||||
}
|
||||
}
|
||||
|
||||
data class DeviceFile(
|
||||
val uri: Uri,
|
||||
val mimeType: String,
|
||||
val path: Path,
|
||||
val size: Long,
|
||||
val lastModified: Long
|
||||
)
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private class DeviceFilesImpl(private val contentResolver: ContentResolver) : DeviceFiles {
|
||||
override fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile> =
|
||||
locations.flatMapMerge { location ->
|
||||
exploreImpl(
|
||||
contentResolver,
|
||||
location.uri,
|
||||
DocumentsContract.getTreeDocumentId(location.uri),
|
||||
location.path)
|
||||
}
|
||||
|
||||
private fun exploreImpl(
|
||||
contentResolver: ContentResolver,
|
||||
rootUri: Uri,
|
||||
treeDocumentId: String,
|
||||
relativePath: Path
|
||||
): Flow<DeviceFile> = 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)
|
||||
val recursive = mutableListOf<Flow<DeviceFile>>()
|
||||
while (cursor.moveToNext()) {
|
||||
val childId = cursor.getString(childUriIndex)
|
||||
val displayName = cursor.getString(displayNameIndex)
|
||||
val newPath = relativePath.file(displayName)
|
||||
val mimeType = cursor.getString(mimeTypeIndex)
|
||||
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
|
||||
// This does NOT block the current coroutine. Instead, we will
|
||||
// evaluate this flow in parallel later to maximize throughput.
|
||||
recursive.add(exploreImpl(contentResolver, rootUri, childId, newPath))
|
||||
} else if (mimeType.startsWith("audio/") && mimeType != "audio/x-mpegurl") {
|
||||
// Immediately emit all files given that it's just an O(1) op.
|
||||
// This also just makes sure the outer flow has a reason to exist
|
||||
// rather than just being a glorified async.
|
||||
val lastModified = cursor.getLong(lastModifiedIndex)
|
||||
val size = cursor.getLong(sizeIndex)
|
||||
emit(
|
||||
DeviceFile(
|
||||
DocumentsContract.buildDocumentUriUsingTree(rootUri, childId),
|
||||
mimeType,
|
||||
newPath,
|
||||
size,
|
||||
lastModified))
|
||||
}
|
||||
}
|
||||
emitAll(recursive.asFlow().flattenMerge())
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2022 Auxio Project
|
||||
* QueryUtil.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.fs.query
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
|
||||
/**
|
||||
* Get a content resolver that will not mangle MediaStore queries on certain devices. See
|
||||
* https://github.com/OxygenCobalt/Auxio/issues/50 for more info.
|
||||
*/
|
||||
val Context.contentResolverSafe: ContentResolver
|
||||
get() = applicationContext.contentResolver
|
||||
|
||||
/**
|
||||
* A shortcut for querying the [ContentResolver] database.
|
||||
*
|
||||
* @param uri The [Uri] of content to retrieve.
|
||||
* @param projection A list of SQL columns to query from the database.
|
||||
* @param selector A SQL selection statement to filter results. Spaces where arguments should be
|
||||
* filled in are represented with a "?".
|
||||
* @param args The arguments used for the selector.
|
||||
* @return A [Cursor] of the queried values, organized by the column projection.
|
||||
* @throws IllegalStateException If the [ContentResolver] did not return the queried [Cursor].
|
||||
* @see ContentResolver.query
|
||||
*/
|
||||
fun ContentResolver.safeQuery(
|
||||
uri: Uri,
|
||||
projection: Array<out String>,
|
||||
selector: String? = null,
|
||||
args: Array<String>? = null
|
||||
) = requireNotNull(query(uri, projection, selector, args, null)) { "ContentResolver query failed" }
|
||||
|
||||
/**
|
||||
* A shortcut for [safeQuery] with [use] applied, automatically cleaning up the [Cursor]'s resources
|
||||
* when no longer used.
|
||||
*
|
||||
* @param uri The [Uri] of content to retrieve.
|
||||
* @param projection A list of SQL columns to query from the database.
|
||||
* @param selector A SQL selection statement to filter results. Spaces where arguments should be
|
||||
* filled in are represented with a "?".
|
||||
* @param args The arguments used for the selector.
|
||||
* @param block The block of code to run with the queried [Cursor]. Will not be ran if the [Cursor]
|
||||
* is empty.
|
||||
* @throws IllegalStateException If the [ContentResolver] did not return the queried [Cursor].
|
||||
* @see ContentResolver.query
|
||||
*/
|
||||
inline fun <reified R> ContentResolver.useQuery(
|
||||
uri: Uri,
|
||||
projection: Array<out String>,
|
||||
selector: String? = null,
|
||||
args: Array<String>? = null,
|
||||
block: (Cursor) -> R
|
||||
) = safeQuery(uri, projection, selector, args).use(block)
|
||||
@@ -1,306 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* MusicGraph.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.graph
|
||||
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.tag.interpret.PreAlbum
|
||||
import org.oxycblt.musikr.tag.interpret.PreArtist
|
||||
import org.oxycblt.musikr.tag.interpret.PreGenre
|
||||
import org.oxycblt.musikr.tag.interpret.PreSong
|
||||
import org.oxycblt.musikr.util.unlikelyToBeNull
|
||||
import timber.log.Timber as L
|
||||
|
||||
data class MusicGraph(
|
||||
val songVertex: List<SongVertex>,
|
||||
val albumVertex: List<AlbumVertex>,
|
||||
val artistVertex: List<ArtistVertex>,
|
||||
val genreVertex: List<GenreVertex>
|
||||
) {
|
||||
interface Builder {
|
||||
fun add(preSong: PreSong)
|
||||
|
||||
fun build(): MusicGraph
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun builder(): Builder = MusicGraphBuilderImpl()
|
||||
}
|
||||
}
|
||||
|
||||
private class MusicGraphBuilderImpl : MusicGraph.Builder {
|
||||
private val songVertices = mutableMapOf<Music.UID, SongVertex>()
|
||||
private val albumVertices = mutableMapOf<PreAlbum, AlbumVertex>()
|
||||
private val artistVertices = mutableMapOf<PreArtist, ArtistVertex>()
|
||||
private val genreVertices = mutableMapOf<PreGenre, GenreVertex>()
|
||||
|
||||
override fun add(preSong: PreSong) {
|
||||
val uid = preSong.computeUid()
|
||||
if (songVertices.containsKey(uid)) {
|
||||
L.d("Song ${preSong.path} already in graph at ${songVertices[uid]?.preSong?.path}")
|
||||
return
|
||||
}
|
||||
|
||||
val songGenreVertices =
|
||||
preSong.preGenres.map { preGenre ->
|
||||
genreVertices.getOrPut(preGenre) { GenreVertex(preGenre) }
|
||||
}
|
||||
|
||||
val songArtistVertices =
|
||||
preSong.preArtists.map { preArtist ->
|
||||
artistVertices.getOrPut(preArtist) { ArtistVertex(preArtist) }
|
||||
}
|
||||
|
||||
val albumVertex =
|
||||
albumVertices.getOrPut(preSong.preAlbum) {
|
||||
// Albums themselves have their own parent artists that also need to be
|
||||
// linked up.
|
||||
val albumArtistVertices =
|
||||
preSong.preAlbum.preArtists.map { preArtist ->
|
||||
artistVertices.getOrPut(preArtist) { ArtistVertex(preArtist) }
|
||||
}
|
||||
val albumVertex = AlbumVertex(preSong.preAlbum, albumArtistVertices.toMutableList())
|
||||
// Album vertex is linked, now link artists back to album.
|
||||
albumArtistVertices.forEach { artistVertex ->
|
||||
artistVertex.albumVertices.add(albumVertex)
|
||||
}
|
||||
albumVertex
|
||||
}
|
||||
|
||||
val songVertex =
|
||||
SongVertex(
|
||||
preSong,
|
||||
albumVertex,
|
||||
songArtistVertices.toMutableList(),
|
||||
songGenreVertices.toMutableList())
|
||||
albumVertex.songVertices.add(songVertex)
|
||||
|
||||
songArtistVertices.forEach { artistVertex ->
|
||||
artistVertex.songVertices.add(songVertex)
|
||||
songGenreVertices.forEach { genreVertex ->
|
||||
// Mutually link any new genres to the artist
|
||||
artistVertex.genreVertices.add(genreVertex)
|
||||
genreVertex.artistVertices.add(artistVertex)
|
||||
}
|
||||
}
|
||||
|
||||
songGenreVertices.forEach { genreVertex -> genreVertex.songVertices.add(songVertex) }
|
||||
|
||||
songVertices[uid] = songVertex
|
||||
}
|
||||
|
||||
override fun build(): MusicGraph {
|
||||
val genreClusters = genreVertices.values.groupBy { it.preGenre.rawName?.lowercase() }
|
||||
for (cluster in genreClusters.values) {
|
||||
simplifyGenreCluster(cluster)
|
||||
}
|
||||
|
||||
val artistClusters = artistVertices.values.groupBy { it.preArtist.rawName?.lowercase() }
|
||||
for (cluster in artistClusters.values) {
|
||||
simplifyArtistCluster(cluster)
|
||||
}
|
||||
|
||||
val albumClusters = albumVertices.values.groupBy { it.preAlbum.rawName?.lowercase() }
|
||||
for (cluster in albumClusters.values) {
|
||||
simplifyAlbumCluster(cluster)
|
||||
}
|
||||
|
||||
// Remove any edges that wound up connecting to the same artist or genre
|
||||
// in the end after simplification.
|
||||
albumVertices.values.forEach {
|
||||
it.artistVertices = it.artistVertices.distinct().toMutableList()
|
||||
}
|
||||
|
||||
songVertices.values.forEach {
|
||||
it.artistVertices = it.artistVertices.distinct().toMutableList()
|
||||
it.genreVertices = it.genreVertices.distinct().toMutableList()
|
||||
}
|
||||
|
||||
return MusicGraph(
|
||||
songVertices.values.toList(),
|
||||
albumVertices.values.toList(),
|
||||
artistVertices.values.toList(),
|
||||
genreVertices.values.toList())
|
||||
}
|
||||
|
||||
private fun simplifyGenreCluster(cluster: Collection<GenreVertex>) {
|
||||
// All of these genres are semantically equivalent. Pick the most popular variation
|
||||
// and merge all the others into it.
|
||||
val clusterSet = cluster.toMutableSet()
|
||||
val dst = clusterSet.maxBy { it.songVertices.size }
|
||||
clusterSet.remove(dst)
|
||||
for (src in clusterSet) {
|
||||
meldGenreVertices(src, dst)
|
||||
}
|
||||
}
|
||||
|
||||
private fun meldGenreVertices(src: GenreVertex, dst: GenreVertex) {
|
||||
// Link all songs and artists from the irrelevant genre to the relevant genre.
|
||||
dst.songVertices.addAll(src.songVertices)
|
||||
dst.artistVertices.addAll(src.artistVertices)
|
||||
// Update all songs and artists to point to the relevant genre.
|
||||
src.songVertices.forEach {
|
||||
val index = it.genreVertices.indexOf(src)
|
||||
check(index >= 0) { "Illegal state: directed edge between genre and song" }
|
||||
it.genreVertices[index] = dst
|
||||
}
|
||||
src.artistVertices.forEach {
|
||||
it.genreVertices.remove(src)
|
||||
it.genreVertices.add(dst)
|
||||
}
|
||||
// Remove the irrelevant genre from the graph.
|
||||
genreVertices.remove(src.preGenre)
|
||||
}
|
||||
|
||||
private fun simplifyArtistCluster(cluster: Collection<ArtistVertex>) {
|
||||
val fullMusicBrainzIdCoverage = cluster.all { it.preArtist.musicBrainzId != null }
|
||||
if (fullMusicBrainzIdCoverage) {
|
||||
// All artists have MBIDs, nothing needs to be merged.
|
||||
val mbidClusters = cluster.groupBy { unlikelyToBeNull(it.preArtist.musicBrainzId) }
|
||||
for (mbidCluster in mbidClusters.values) {
|
||||
simplifyArtistClusterImpl(mbidCluster)
|
||||
}
|
||||
return
|
||||
}
|
||||
// No full MBID coverage, discard the MBIDs from the graph.
|
||||
val strippedCluster =
|
||||
cluster.map {
|
||||
val noMbidPreArtist = it.preArtist.copy(musicBrainzId = null)
|
||||
val simpleMbidVertex =
|
||||
artistVertices.getOrPut(noMbidPreArtist) { ArtistVertex(noMbidPreArtist) }
|
||||
meldArtistVertices(it, simpleMbidVertex)
|
||||
simpleMbidVertex
|
||||
}
|
||||
simplifyArtistClusterImpl(strippedCluster)
|
||||
}
|
||||
|
||||
private fun simplifyArtistClusterImpl(cluster: Collection<ArtistVertex>) {
|
||||
if (cluster.size == 1) {
|
||||
// One canonical artist, nothing to collapse
|
||||
return
|
||||
}
|
||||
val clusterSet = cluster.toMutableSet()
|
||||
val relevantArtistVertex = clusterSet.maxBy { it.songVertices.size }
|
||||
clusterSet.remove(relevantArtistVertex)
|
||||
for (irrelevantArtistVertex in clusterSet) {
|
||||
meldArtistVertices(irrelevantArtistVertex, relevantArtistVertex)
|
||||
}
|
||||
}
|
||||
|
||||
private fun meldArtistVertices(src: ArtistVertex, dst: ArtistVertex) {
|
||||
// Link all songs and albums from the irrelevant artist to the relevant artist.
|
||||
dst.songVertices.addAll(src.songVertices)
|
||||
dst.albumVertices.addAll(src.albumVertices)
|
||||
// Update all songs, albums, and genres to point to the relevant artist.
|
||||
src.songVertices.forEach {
|
||||
val index = it.artistVertices.indexOf(src)
|
||||
check(index >= 0) { "Illegal state: directed edge between artist and song" }
|
||||
it.artistVertices[index] = dst
|
||||
}
|
||||
src.albumVertices.forEach {
|
||||
val index = it.artistVertices.indexOf(src)
|
||||
check(index >= 0) { "Illegal state: directed edge between artist and album" }
|
||||
it.artistVertices[index] = dst
|
||||
}
|
||||
src.genreVertices.forEach {
|
||||
it.artistVertices.remove(src)
|
||||
it.artistVertices.add(dst)
|
||||
}
|
||||
|
||||
// Remove the irrelevant artist from the graph.
|
||||
artistVertices.remove(src.preArtist)
|
||||
}
|
||||
|
||||
private fun simplifyAlbumCluster(cluster: Collection<AlbumVertex>) {
|
||||
val fullMusicBrainzIdCoverage = cluster.all { it.preAlbum.musicBrainzId != null }
|
||||
if (fullMusicBrainzIdCoverage) {
|
||||
// All albums have MBIDs, nothing needs to be merged.
|
||||
val mbidClusters = cluster.groupBy { unlikelyToBeNull(it.preAlbum.musicBrainzId) }
|
||||
for (mbidCluster in mbidClusters.values) {
|
||||
simplifyAlbumClusterImpl(mbidCluster)
|
||||
}
|
||||
return
|
||||
}
|
||||
// No full MBID coverage, discard the MBIDs from the graph.
|
||||
val strippedCluster =
|
||||
cluster.map {
|
||||
val noMbidPreAlbum = it.preAlbum.copy(musicBrainzId = null)
|
||||
val simpleMbidVertex =
|
||||
albumVertices.getOrPut(noMbidPreAlbum) {
|
||||
AlbumVertex(noMbidPreAlbum, it.artistVertices.toMutableList())
|
||||
}
|
||||
meldAlbumVertices(it, simpleMbidVertex)
|
||||
simpleMbidVertex
|
||||
}
|
||||
simplifyAlbumClusterImpl(strippedCluster)
|
||||
}
|
||||
|
||||
private fun simplifyAlbumClusterImpl(cluster: Collection<AlbumVertex>) {
|
||||
// All of these albums are semantically equivalent. Pick the most popular variation
|
||||
// and merge all the others into it.
|
||||
val clusterSet = cluster.toMutableSet()
|
||||
val dst = clusterSet.maxBy { it.songVertices.size }
|
||||
clusterSet.remove(dst)
|
||||
for (src in clusterSet) {
|
||||
meldAlbumVertices(src, dst)
|
||||
}
|
||||
}
|
||||
|
||||
private fun meldAlbumVertices(src: AlbumVertex, dst: AlbumVertex) {
|
||||
// Link all songs and artists from the irrelevant album to the relevant album.
|
||||
dst.songVertices.addAll(src.songVertices)
|
||||
dst.artistVertices.addAll(src.artistVertices)
|
||||
// Update all songs and artists to point to the relevant album.
|
||||
src.songVertices.forEach { it.albumVertex = dst }
|
||||
src.artistVertices.forEach {
|
||||
it.albumVertices.remove(src)
|
||||
it.albumVertices.add(dst)
|
||||
}
|
||||
// Remove the irrelevant album from the graph.
|
||||
albumVertices.remove(src.preAlbum)
|
||||
}
|
||||
}
|
||||
|
||||
class SongVertex(
|
||||
val preSong: PreSong,
|
||||
var albumVertex: AlbumVertex,
|
||||
var artistVertices: MutableList<ArtistVertex>,
|
||||
var genreVertices: MutableList<GenreVertex>
|
||||
) {
|
||||
var tag: Any? = null
|
||||
}
|
||||
|
||||
class AlbumVertex(val preAlbum: PreAlbum, var artistVertices: MutableList<ArtistVertex>) {
|
||||
val songVertices = mutableSetOf<SongVertex>()
|
||||
var tag: Any? = null
|
||||
}
|
||||
|
||||
class ArtistVertex(
|
||||
val preArtist: PreArtist,
|
||||
) {
|
||||
val songVertices = mutableSetOf<SongVertex>()
|
||||
val albumVertices = mutableSetOf<AlbumVertex>()
|
||||
val genreVertices = mutableSetOf<GenreVertex>()
|
||||
var tag: Any? = null
|
||||
}
|
||||
|
||||
class GenreVertex(val preGenre: PreGenre) {
|
||||
val songVertices = mutableSetOf<SongVertex>()
|
||||
val artistVertices = mutableSetOf<ArtistVertex>()
|
||||
var tag: Any? = null
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* AudioProperties.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.metadata
|
||||
|
||||
import android.content.Context
|
||||
import android.media.MediaExtractor
|
||||
import android.media.MediaFormat
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
import org.oxycblt.musikr.Song
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
* The properties of a [Song]'s file.
|
||||
*
|
||||
* @param bitrateKbps The bit rate, in kilobytes-per-second. Null if it could not be parsed.
|
||||
* @param sampleRateHz The sample rate, in hertz.
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
data class AudioProperties(val bitrateKbps: Int?, val sampleRateHz: Int?) {
|
||||
/** Implements the process of extracting [AudioProperties] from a given [Song]. */
|
||||
interface Factory {
|
||||
/**
|
||||
* Extract the [AudioProperties] of a given [Song].
|
||||
*
|
||||
* @param song The [Song] to read.
|
||||
* @return The [AudioProperties] of the [Song], if possible to obtain.
|
||||
*/
|
||||
suspend fun extract(song: Song): AudioProperties
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A framework-backed implementation of [AudioProperties.Factory].
|
||||
*
|
||||
* @param context [Context] required to read audio files.
|
||||
*/
|
||||
class AudioPropertiesFactoryImpl
|
||||
@Inject
|
||||
constructor(@ApplicationContext private val context: Context) : AudioProperties.Factory {
|
||||
|
||||
override suspend fun extract(song: Song): AudioProperties {
|
||||
// While we would use ExoPlayer to extract this information, it doesn't support
|
||||
// common data like bit rate in progressive data sources due to there being no
|
||||
// demand. Thus, we are stuck with the inferior OS-provided MediaExtractor.
|
||||
val extractor = MediaExtractor()
|
||||
|
||||
try {
|
||||
extractor.setDataSource(context, song.uri, emptyMap())
|
||||
} catch (e: Exception) {
|
||||
// Can feasibly fail with invalid file formats. Note that this isn't considered
|
||||
// an error condition in the UI, as there is still plenty of other song information
|
||||
// that we can show.
|
||||
L.w("Unable to extract song attributes.")
|
||||
L.w(e.stackTraceToString())
|
||||
return AudioProperties(null, null)
|
||||
}
|
||||
|
||||
// Get the first track from the extractor (This is basically always the only
|
||||
// track we need to analyze).
|
||||
val format = extractor.getTrackFormat(0)
|
||||
|
||||
// Accessing fields can throw an exception if the fields are not present, and
|
||||
// the new method for using default values is not available on lower API levels.
|
||||
// So, we are forced to handle the exception and map it to a saner null value.
|
||||
val bitrate =
|
||||
try {
|
||||
// Convert bytes-per-second to kilobytes-per-second.
|
||||
format.getInteger(MediaFormat.KEY_BIT_RATE) / 1000
|
||||
} catch (e: NullPointerException) {
|
||||
L.d("Unable to extract bit rate field")
|
||||
null
|
||||
}
|
||||
|
||||
val sampleRate =
|
||||
try {
|
||||
format.getInteger(MediaFormat.KEY_SAMPLE_RATE)
|
||||
} catch (e: NullPointerException) {
|
||||
L.e("Unable to extract sample rate field")
|
||||
null
|
||||
}
|
||||
|
||||
extractor.release()
|
||||
|
||||
L.d("Finished extracting audio properties")
|
||||
|
||||
return AudioProperties(bitrate, sampleRate)
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* MetadataExtractor.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.metadata
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.oxycblt.ktaglib.FileRef
|
||||
import org.oxycblt.ktaglib.KTagLib
|
||||
import org.oxycblt.ktaglib.Metadata
|
||||
import org.oxycblt.musikr.fs.query.DeviceFile
|
||||
import org.oxycblt.musikr.util.unlikelyToBeNull
|
||||
|
||||
interface MetadataExtractor {
|
||||
suspend fun extract(file: DeviceFile): Metadata?
|
||||
|
||||
companion object {
|
||||
fun from(context: Context): MetadataExtractor = MetadataExtractorImpl(context)
|
||||
}
|
||||
}
|
||||
|
||||
private class MetadataExtractorImpl(private val context: Context) : MetadataExtractor {
|
||||
override suspend fun extract(file: DeviceFile) =
|
||||
withContext(Dispatchers.IO) {
|
||||
KTagLib.open(context, FileRef(unlikelyToBeNull(file.path.name), file.uri))
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* MetadataModule.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.metadata
|
||||
|
||||
import dagger.Binds
|
||||
import dagger.Module
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
interface MetadataModule {
|
||||
@Binds
|
||||
fun audioPropertiesFactory(interpreter: AudioPropertiesFactoryImpl): AudioProperties.Factory
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* AlbumImpl.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.model
|
||||
|
||||
import org.oxycblt.musikr.Album
|
||||
import org.oxycblt.musikr.Artist
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.cover.Cover
|
||||
import org.oxycblt.musikr.tag.Date
|
||||
import org.oxycblt.musikr.tag.interpret.PreAlbum
|
||||
import org.oxycblt.musikr.util.update
|
||||
|
||||
interface AlbumCore {
|
||||
val preAlbum: PreAlbum
|
||||
val songs: List<Song>
|
||||
|
||||
fun resolveArtists(): List<Artist>
|
||||
}
|
||||
|
||||
/**
|
||||
* Library-backed implementation of [Album].
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
class AlbumImpl(private val core: AlbumCore) : Album {
|
||||
private val preAlbum = core.preAlbum
|
||||
|
||||
override val uid =
|
||||
// Attempt to use a MusicBrainz ID first before falling back to a hashed UID.
|
||||
preAlbum.musicBrainzId?.let { Music.UID.musicBrainz(Music.UID.Item.ALBUM, it) }
|
||||
?: Music.UID.auxio(Music.UID.Item.ALBUM) {
|
||||
// Hash based on only names despite the presence of a date to increase stability.
|
||||
// I don't know if there is any situation where an artist will have two albums with
|
||||
// the exact same name, but if there is, I would love to know.
|
||||
update(preAlbum.rawName)
|
||||
update(preAlbum.preArtists.map { it.rawName })
|
||||
}
|
||||
override val name = preAlbum.name
|
||||
override val releaseType = preAlbum.releaseType
|
||||
override val durationMs = core.songs.sumOf { it.durationMs }
|
||||
override val dateAdded = core.songs.minOf { it.dateAdded }
|
||||
override val cover = Cover.multi(core.songs)
|
||||
override val dates: Date.Range? =
|
||||
core.songs.mapNotNull { it.date }.ifEmpty { null }?.run { Date.Range(min(), max()) }
|
||||
|
||||
override val artists: List<Artist>
|
||||
get() = core.resolveArtists()
|
||||
|
||||
override val songs = core.songs
|
||||
|
||||
private val hashCode = 31 * (31 * uid.hashCode() + preAlbum.hashCode()) + songs.hashCode()
|
||||
|
||||
override fun hashCode() = hashCode
|
||||
|
||||
override fun equals(other: Any?) =
|
||||
other is AlbumImpl && uid == other.uid && preAlbum == other.preAlbum && songs == other.songs
|
||||
|
||||
override fun toString() = "Album(uid=$uid, name=$name)"
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* ArtistImpl.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.model
|
||||
|
||||
import org.oxycblt.musikr.Album
|
||||
import org.oxycblt.musikr.Artist
|
||||
import org.oxycblt.musikr.Genre
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.cover.Cover
|
||||
import org.oxycblt.musikr.tag.interpret.PreArtist
|
||||
import org.oxycblt.musikr.util.update
|
||||
|
||||
interface ArtistCore {
|
||||
val preArtist: PreArtist
|
||||
val songs: Set<Song>
|
||||
val albums: Set<Album>
|
||||
|
||||
fun resolveGenres(): Set<Genre>
|
||||
}
|
||||
|
||||
/**
|
||||
* Library-backed implementation of [Artist].
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
class ArtistImpl(private val core: ArtistCore) : Artist {
|
||||
override val uid =
|
||||
// Attempt to use a MusicBrainz ID first before falling back to a hashed UID.
|
||||
core.preArtist.musicBrainzId?.let { Music.UID.musicBrainz(Music.UID.Item.ARTIST, it) }
|
||||
?: Music.UID.auxio(Music.UID.Item.ARTIST) { update(core.preArtist.rawName) }
|
||||
override val name = core.preArtist.name
|
||||
|
||||
override val songs = core.songs
|
||||
override var explicitAlbums = core.albums
|
||||
override var implicitAlbums = core.songs.mapTo(mutableSetOf()) { it.album } - core.albums
|
||||
|
||||
override val genres: List<Genre>
|
||||
get() = core.resolveGenres().toList()
|
||||
|
||||
override val durationMs = core.songs.sumOf { it.durationMs }
|
||||
override val cover = Cover.multi(core.songs)
|
||||
|
||||
private val hashCode =
|
||||
31 * (31 * uid.hashCode() + core.preArtist.hashCode()) * core.songs.hashCode()
|
||||
|
||||
override fun hashCode() = hashCode
|
||||
|
||||
override fun equals(other: Any?) =
|
||||
other is ArtistImpl &&
|
||||
uid == other.uid &&
|
||||
core.preArtist == other.core.preArtist &&
|
||||
songs == other.songs
|
||||
|
||||
override fun toString() = "Artist(uid=$uid, name=$name)"
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* GenreImpl.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.model
|
||||
|
||||
import org.oxycblt.musikr.Artist
|
||||
import org.oxycblt.musikr.Genre
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.cover.Cover
|
||||
import org.oxycblt.musikr.tag.interpret.PreGenre
|
||||
import org.oxycblt.musikr.util.update
|
||||
|
||||
interface GenreCore {
|
||||
val preGenre: PreGenre
|
||||
val songs: Set<Song>
|
||||
val artists: Set<Artist>
|
||||
}
|
||||
|
||||
/**
|
||||
* Library-backed implementation of [Genre].
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
class GenreImpl(private val core: GenreCore) : Genre {
|
||||
override val uid = Music.UID.auxio(Music.UID.Item.GENRE) { update(core.preGenre.rawName) }
|
||||
override val name = core.preGenre.name
|
||||
|
||||
override val songs = mutableSetOf<Song>()
|
||||
override val artists = mutableSetOf<Artist>()
|
||||
override val durationMs = core.songs.sumOf { it.durationMs }
|
||||
override val cover = Cover.multi(core.songs)
|
||||
|
||||
private val hashCode = 31 * (31 * uid.hashCode() + core.preGenre.hashCode()) + songs.hashCode()
|
||||
|
||||
override fun hashCode() = hashCode
|
||||
|
||||
override fun equals(other: Any?) =
|
||||
other is GenreImpl &&
|
||||
uid == other.uid &&
|
||||
core.preGenre == other.core.preGenre &&
|
||||
songs == other.songs
|
||||
|
||||
override fun toString() = "Genre(uid=$uid, name=$name)"
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* LibraryFactory.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.model
|
||||
|
||||
import org.oxycblt.musikr.Album
|
||||
import org.oxycblt.musikr.Artist
|
||||
import org.oxycblt.musikr.Genre
|
||||
import org.oxycblt.musikr.MutableLibrary
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.graph.AlbumVertex
|
||||
import org.oxycblt.musikr.graph.ArtistVertex
|
||||
import org.oxycblt.musikr.graph.GenreVertex
|
||||
import org.oxycblt.musikr.graph.MusicGraph
|
||||
import org.oxycblt.musikr.graph.SongVertex
|
||||
|
||||
interface LibraryFactory {
|
||||
fun create(graph: MusicGraph): MutableLibrary
|
||||
|
||||
companion object {
|
||||
fun new(): LibraryFactory = LibraryFactoryImpl()
|
||||
}
|
||||
}
|
||||
|
||||
private class LibraryFactoryImpl() : LibraryFactory {
|
||||
override fun create(graph: MusicGraph): MutableLibrary {
|
||||
val songs =
|
||||
graph.songVertex.mapTo(mutableSetOf()) { vertex ->
|
||||
SongImpl(SongVertexCore(vertex)).also { vertex.tag = it }
|
||||
}
|
||||
val albums =
|
||||
graph.albumVertex.mapTo(mutableSetOf()) { vertex ->
|
||||
AlbumImpl(AlbumVertexCore(vertex)).also { vertex.tag = it }
|
||||
}
|
||||
val artists =
|
||||
graph.artistVertex.mapTo(mutableSetOf()) { vertex ->
|
||||
ArtistImpl(ArtistVertexCore(vertex)).also { vertex.tag = it }
|
||||
}
|
||||
val genres =
|
||||
graph.genreVertex.mapTo(mutableSetOf()) { vertex ->
|
||||
GenreImpl(GenreVertexCore(vertex)).also { vertex.tag = it }
|
||||
}
|
||||
return LibraryImpl(songs, albums, artists, genres)
|
||||
}
|
||||
|
||||
private class SongVertexCore(private val vertex: SongVertex) : SongCore {
|
||||
override val preSong = vertex.preSong
|
||||
|
||||
override fun resolveAlbum() = vertex.albumVertex.tag as Album
|
||||
|
||||
override fun resolveArtists() = vertex.artistVertices.map { it.tag as Artist }
|
||||
|
||||
override fun resolveGenres() = vertex.genreVertices.map { it.tag as Genre }
|
||||
}
|
||||
|
||||
private class AlbumVertexCore(private val vertex: AlbumVertex) : AlbumCore {
|
||||
override val preAlbum = vertex.preAlbum
|
||||
|
||||
override val songs = vertex.songVertices.map { SongImpl(SongVertexCore(it)) }
|
||||
|
||||
override fun resolveArtists() = vertex.artistVertices.map { it.tag as Artist }
|
||||
}
|
||||
|
||||
private class ArtistVertexCore(private val vertex: ArtistVertex) : ArtistCore {
|
||||
override val preArtist = vertex.preArtist
|
||||
|
||||
override val songs = vertex.songVertices.mapTo(mutableSetOf()) { it.tag as Song }
|
||||
|
||||
override val albums = vertex.albumVertices.mapTo(mutableSetOf()) { it.tag as Album }
|
||||
|
||||
override fun resolveGenres() =
|
||||
vertex.genreVertices.mapTo(mutableSetOf()) { it.tag as Genre }
|
||||
}
|
||||
|
||||
private class GenreVertexCore(vertex: GenreVertex) : GenreCore {
|
||||
override val preGenre = vertex.preGenre
|
||||
|
||||
override val songs = vertex.songVertices.mapTo(mutableSetOf()) { it.tag as Song }
|
||||
|
||||
override val artists = vertex.artistVertices.mapTo(mutableSetOf()) { it.tag as Artist }
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* LibraryImpl.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.model
|
||||
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.MutableLibrary
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
|
||||
class LibraryImpl(
|
||||
override val songs: Collection<SongImpl>,
|
||||
override val albums: Collection<AlbumImpl>,
|
||||
override val artists: Collection<ArtistImpl>,
|
||||
override val genres: Collection<GenreImpl>
|
||||
) : MutableLibrary {
|
||||
override val playlists = emptySet<Playlist>()
|
||||
|
||||
private val songUidMap = songs.associateBy { it.uid }
|
||||
private val albumUidMap = albums.associateBy { it.uid }
|
||||
private val artistUidMap = artists.associateBy { it.uid }
|
||||
private val genreUidMap = genres.associateBy { it.uid }
|
||||
private val playlistUidMap = playlists.associateBy { it.uid }
|
||||
|
||||
override fun findSong(uid: Music.UID) = songUidMap[uid]
|
||||
|
||||
override fun findSongByPath(path: Path) = songs.find { it.path == path }
|
||||
|
||||
override fun findAlbum(uid: Music.UID) = albumUidMap[uid]
|
||||
|
||||
override fun findArtist(uid: Music.UID) = artistUidMap[uid]
|
||||
|
||||
override fun findGenre(uid: Music.UID) = genreUidMap[uid]
|
||||
|
||||
override fun findPlaylist(uid: Music.UID) = playlistUidMap[uid]
|
||||
|
||||
override fun findPlaylistByName(name: String) = playlists.find { it.name.raw == name }
|
||||
|
||||
override suspend fun createPlaylist(name: String, songs: List<Song>): MutableLibrary {
|
||||
return this
|
||||
}
|
||||
|
||||
override suspend fun renamePlaylist(playlist: Playlist, name: String): MutableLibrary {
|
||||
return this
|
||||
}
|
||||
|
||||
override suspend fun addToPlaylist(playlist: Playlist, songs: List<Song>): MutableLibrary {
|
||||
return this
|
||||
}
|
||||
|
||||
override suspend fun rewritePlaylist(playlist: Playlist, songs: List<Song>): MutableLibrary {
|
||||
return this
|
||||
}
|
||||
|
||||
override suspend fun deletePlaylist(playlist: Playlist): MutableLibrary {
|
||||
return this
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* PlaylistImpl.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.model
|
||||
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.cover.Cover
|
||||
import org.oxycblt.musikr.playlist.PlaylistHandle
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import org.oxycblt.musikr.tag.interpret.PrePlaylist
|
||||
|
||||
interface PlaylistCore {
|
||||
val prePlaylist: PrePlaylist
|
||||
val handle: PlaylistHandle
|
||||
val songs: List<Song>
|
||||
}
|
||||
|
||||
class PlaylistImpl(private val core: PlaylistCore) : Playlist {
|
||||
override val uid = core.handle.uid
|
||||
override val name: Name.Known = core.prePlaylist.name
|
||||
override val durationMs = core.songs.sumOf { it.durationMs }
|
||||
override val cover = Cover.multi(core.songs)
|
||||
override val songs = core.songs
|
||||
|
||||
private var hashCode =
|
||||
31 * (31 * uid.hashCode() + core.prePlaylist.hashCode()) + songs.hashCode()
|
||||
|
||||
override fun equals(other: Any?) =
|
||||
other is PlaylistImpl && core.prePlaylist == other.core.prePlaylist && songs == other.songs
|
||||
|
||||
override fun hashCode() = hashCode
|
||||
|
||||
override fun toString() = "Playlist(uid=$uid, name=$name)"
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* SongImpl.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.model
|
||||
|
||||
import org.oxycblt.musikr.Album
|
||||
import org.oxycblt.musikr.Artist
|
||||
import org.oxycblt.musikr.Genre
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.tag.interpret.PreSong
|
||||
|
||||
interface SongCore {
|
||||
val preSong: PreSong
|
||||
|
||||
fun resolveAlbum(): Album
|
||||
|
||||
fun resolveArtists(): List<Artist>
|
||||
|
||||
fun resolveGenres(): List<Genre>
|
||||
}
|
||||
|
||||
/**
|
||||
* Library-backed implementation of [Song].
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
class SongImpl(private val handle: SongCore) : Song {
|
||||
private val preSong = handle.preSong
|
||||
|
||||
override val uid = preSong.computeUid()
|
||||
override val name = preSong.name
|
||||
override val track = preSong.track
|
||||
override val disc = preSong.disc
|
||||
override val date = preSong.date
|
||||
override val uri = preSong.uri
|
||||
override val path = preSong.path
|
||||
override val format = preSong.format
|
||||
override val size = preSong.size
|
||||
override val durationMs = preSong.durationMs
|
||||
override val replayGainAdjustment = preSong.replayGainAdjustment
|
||||
override val lastModified = preSong.lastModified
|
||||
override val dateAdded = preSong.dateAdded
|
||||
override val cover = preSong.cover
|
||||
override val album: Album
|
||||
get() = handle.resolveAlbum()
|
||||
|
||||
override val artists: List<Artist>
|
||||
get() = handle.resolveArtists()
|
||||
|
||||
override val genres: List<Genre>
|
||||
get() = handle.resolveGenres()
|
||||
|
||||
private val hashCode = 31 * uid.hashCode() + preSong.hashCode()
|
||||
|
||||
override fun hashCode() = hashCode
|
||||
|
||||
override fun equals(other: Any?) =
|
||||
other is SongImpl && uid == other.uid && preSong == other.preSong
|
||||
|
||||
override fun toString() = "Song(uid=$uid, name=$name)"
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* EvaluateStep.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.pipeline
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.buffer
|
||||
import kotlinx.coroutines.flow.filterIsInstance
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import org.oxycblt.musikr.Interpretation
|
||||
import org.oxycblt.musikr.MutableLibrary
|
||||
import org.oxycblt.musikr.graph.MusicGraph
|
||||
import org.oxycblt.musikr.model.LibraryFactory
|
||||
import org.oxycblt.musikr.tag.interpret.TagInterpreter
|
||||
|
||||
interface EvaluateStep {
|
||||
suspend fun evaluate(
|
||||
interpretation: Interpretation,
|
||||
extractedMusic: Flow<ExtractedMusic>
|
||||
): MutableLibrary
|
||||
|
||||
companion object {
|
||||
fun new(): EvaluateStep = EvaluateStepImpl(TagInterpreter.new(), LibraryFactory.new())
|
||||
}
|
||||
}
|
||||
|
||||
private class EvaluateStepImpl(
|
||||
private val tagInterpreter: TagInterpreter,
|
||||
private val libraryFactory: LibraryFactory
|
||||
) : EvaluateStep {
|
||||
override suspend fun evaluate(
|
||||
interpretation: Interpretation,
|
||||
extractedMusic: Flow<ExtractedMusic>
|
||||
): MutableLibrary {
|
||||
val preSongs =
|
||||
extractedMusic
|
||||
.filterIsInstance<ExtractedMusic.Song>()
|
||||
.map { tagInterpreter.interpret(it.song, interpretation) }
|
||||
.flowOn(Dispatchers.Main)
|
||||
.buffer(Channel.UNLIMITED)
|
||||
val graphBuilder = MusicGraph.builder()
|
||||
preSongs.collect { graphBuilder.add(it) }
|
||||
val graph = graphBuilder.build()
|
||||
return libraryFactory.create(graph)
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* ExploreStep.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.pipeline
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.asFlow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.query.DeviceFile
|
||||
import org.oxycblt.musikr.fs.query.DeviceFiles
|
||||
import org.oxycblt.musikr.playlist.m3u.M3U
|
||||
|
||||
interface ExploreStep {
|
||||
fun explore(locations: List<MusicLocation>): Flow<ExploreNode>
|
||||
|
||||
companion object {
|
||||
fun from(context: Context): ExploreStep = ExploreStepImpl(DeviceFiles.from(context))
|
||||
}
|
||||
}
|
||||
|
||||
private class ExploreStepImpl(private val deviceFiles: DeviceFiles) : ExploreStep {
|
||||
override fun explore(locations: List<MusicLocation>) =
|
||||
deviceFiles
|
||||
.explore(locations.asFlow())
|
||||
.mapNotNull {
|
||||
when {
|
||||
it.mimeType == M3U.MIME_TYPE -> null
|
||||
it.mimeType.startsWith("audio/") -> ExploreNode.Audio(it)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
.flowOn(Dispatchers.IO)
|
||||
}
|
||||
|
||||
sealed interface ExploreNode {
|
||||
data class Audio(val file: DeviceFile) : ExploreNode
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* ExtractStep.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.pipeline
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.buffer
|
||||
import kotlinx.coroutines.flow.filterIsInstance
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import org.oxycblt.ktaglib.Properties
|
||||
import org.oxycblt.musikr.Storage
|
||||
import org.oxycblt.musikr.cache.CacheResult
|
||||
import org.oxycblt.musikr.cover.Cover
|
||||
import org.oxycblt.musikr.fs.query.DeviceFile
|
||||
import org.oxycblt.musikr.metadata.MetadataExtractor
|
||||
import org.oxycblt.musikr.tag.parse.ParsedTags
|
||||
import org.oxycblt.musikr.tag.parse.TagParser
|
||||
|
||||
interface ExtractStep {
|
||||
fun extract(storage: Storage, nodes: Flow<ExploreNode>): Flow<ExtractedMusic>
|
||||
|
||||
companion object {
|
||||
fun from(context: Context): ExtractStep =
|
||||
ExtractStepImpl(MetadataExtractor.from(context), TagParser.new())
|
||||
}
|
||||
}
|
||||
|
||||
private class ExtractStepImpl(
|
||||
private val metadataExtractor: MetadataExtractor,
|
||||
private val tagParser: TagParser
|
||||
) : ExtractStep {
|
||||
override fun extract(storage: Storage, nodes: Flow<ExploreNode>): Flow<ExtractedMusic> {
|
||||
val cacheResults =
|
||||
nodes
|
||||
.filterIsInstance<ExploreNode.Audio>()
|
||||
.map { storage.cache.read(it.file) }
|
||||
.flowOn(Dispatchers.IO)
|
||||
.buffer(Channel.UNLIMITED)
|
||||
val divertedFlow =
|
||||
cacheResults.divert {
|
||||
when (it) {
|
||||
is CacheResult.Hit -> Divert.Left(it.song)
|
||||
is CacheResult.Miss -> Divert.Right(it.file)
|
||||
}
|
||||
}
|
||||
val cachedSongs = divertedFlow.left.map { ExtractedMusic.Song(it) }
|
||||
val uncachedSongs = divertedFlow.right
|
||||
val distributedFlow = uncachedSongs.distribute(16)
|
||||
val extractedSongs =
|
||||
Array(distributedFlow.flows.size) { i ->
|
||||
distributedFlow.flows[i]
|
||||
.mapNotNull { file ->
|
||||
val metadata = metadataExtractor.extract(file) ?: return@mapNotNull null
|
||||
val tags = tagParser.parse(file, metadata)
|
||||
val cover = metadata.cover?.let { storage.storedCovers.write(it) }
|
||||
RawSong(file, metadata.properties, tags, cover)
|
||||
}
|
||||
.flowOn(Dispatchers.IO)
|
||||
.buffer(Channel.UNLIMITED)
|
||||
}
|
||||
val writtenSongs =
|
||||
merge(*extractedSongs)
|
||||
.map {
|
||||
storage.cache.write(it)
|
||||
ExtractedMusic.Song(it)
|
||||
}
|
||||
.flowOn(Dispatchers.IO)
|
||||
.buffer(Channel.UNLIMITED)
|
||||
return merge<ExtractedMusic>(
|
||||
divertedFlow.manager, cachedSongs, distributedFlow.manager, writtenSongs)
|
||||
}
|
||||
}
|
||||
|
||||
data class RawSong(
|
||||
val file: DeviceFile,
|
||||
val properties: Properties,
|
||||
val tags: ParsedTags,
|
||||
val cover: Cover.Single?
|
||||
)
|
||||
|
||||
sealed interface ExtractedMusic {
|
||||
data class Song(val song: RawSong) : ExtractedMusic
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* FlowUtil.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.pipeline
|
||||
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
import kotlinx.coroutines.flow.withIndex
|
||||
|
||||
sealed interface Divert<L, R> {
|
||||
data class Left<L, R>(val value: L) : Divert<L, R>
|
||||
|
||||
data class Right<L, R>(val value: R) : Divert<L, R>
|
||||
}
|
||||
|
||||
class DivertedFlow<L, R>(val manager: Flow<Nothing>, val left: Flow<L>, val right: Flow<R>)
|
||||
|
||||
inline fun <T, L, R> Flow<T>.divert(
|
||||
crossinline predicate: (T) -> Divert<L, R>
|
||||
): DivertedFlow<L, R> {
|
||||
val leftChannel = Channel<L>(Channel.UNLIMITED)
|
||||
val rightChannel = Channel<R>(Channel.UNLIMITED)
|
||||
val managedFlow =
|
||||
flow<Nothing> {
|
||||
collect {
|
||||
when (val result = predicate(it)) {
|
||||
is Divert.Left -> leftChannel.send(result.value)
|
||||
is Divert.Right -> rightChannel.send(result.value)
|
||||
}
|
||||
}
|
||||
leftChannel.close()
|
||||
rightChannel.close()
|
||||
}
|
||||
return DivertedFlow(managedFlow, leftChannel.receiveAsFlow(), rightChannel.receiveAsFlow())
|
||||
}
|
||||
|
||||
class DistributedFlow<T>(val manager: Flow<Nothing>, val flows: Array<Flow<T>>)
|
||||
|
||||
/**
|
||||
* Equally "distributes" the values of some flow across n new flows.
|
||||
*
|
||||
* Note that this function requires the "manager" flow to be consumed alongside the split flows in
|
||||
* order to function. Without this, all of the newly split flows will simply block.
|
||||
*/
|
||||
fun <T> Flow<T>.distribute(n: Int): DistributedFlow<T> {
|
||||
val posChannels = Array(n) { Channel<T>(Channel.UNLIMITED) }
|
||||
val managerFlow =
|
||||
flow<Nothing> {
|
||||
withIndex().collect {
|
||||
val index = it.index % n
|
||||
posChannels[index].send(it.value)
|
||||
}
|
||||
for (channel in posChannels) {
|
||||
channel.close()
|
||||
}
|
||||
}
|
||||
val hotFlows = posChannels.map { it.receiveAsFlow() }.toTypedArray()
|
||||
return DistributedFlow(managerFlow, hotFlows)
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* ExternalPlaylistManager.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.playlist
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.path.DocumentPathFactory
|
||||
import org.oxycblt.musikr.fs.query.contentResolverSafe
|
||||
import org.oxycblt.musikr.playlist.m3u.M3U
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
* Generic playlist file importing abstraction.
|
||||
*
|
||||
* @see ImportedPlaylist
|
||||
* @see M3U
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface ExternalPlaylistManager {
|
||||
/**
|
||||
* Import the playli L.d("Unable to extract bit rate field") st file at the given [uri].
|
||||
*
|
||||
* @param uri The [Uri] of the playlist file to import.
|
||||
* @return An [ImportedPlaylist] containing the paths to the files listed in the playlist file,
|
||||
* or null if the playlist could not be imported.
|
||||
*/
|
||||
suspend fun import(uri: Uri): ImportedPlaylist?
|
||||
|
||||
/**
|
||||
* Export the given [playlist] to the given [uri].
|
||||
*
|
||||
* @param playlist The playlist to export.
|
||||
* @param uri The [Uri] to export the playlist to.
|
||||
* @param config The configuration to use when exporting the playlist.
|
||||
* @return True if the playlist was successfully exported, false otherwise.
|
||||
*/
|
||||
suspend fun export(playlist: Playlist, uri: Uri, config: ExportConfig): Boolean
|
||||
|
||||
companion object {
|
||||
fun from(context: Context): ExternalPlaylistManager =
|
||||
ExternalPlaylistManagerImpl(
|
||||
context, DocumentPathFactory.from(context), M3U.from(context))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration to use when exporting playlists.
|
||||
*
|
||||
* @property absolute Whether or not to use absolute paths when exporting. If not, relative paths
|
||||
* will be used.
|
||||
* @property windowsPaths Whether or not to use Windows-style paths when exporting (i.e prefixed
|
||||
* with C:\\ and using \). If not, Unix-style paths will be used (i.e prefixed with /).
|
||||
* @see ExternalPlaylistManager.export
|
||||
*/
|
||||
data class ExportConfig(val absolute: Boolean, val windowsPaths: Boolean)
|
||||
|
||||
/**
|
||||
* A playlist that has been imported.
|
||||
*
|
||||
* @property name The name of the playlist. May be null if not provided.
|
||||
* @property paths The paths of the files in the playlist.
|
||||
* @see ExternalPlaylistManager
|
||||
* @see M3U
|
||||
*/
|
||||
data class ImportedPlaylist(val name: String?, val paths: List<PossiblePaths>)
|
||||
|
||||
typealias PossiblePaths = List<Path>
|
||||
|
||||
class ExternalPlaylistManagerImpl(
|
||||
private val context: Context,
|
||||
private val documentPathFactory: DocumentPathFactory,
|
||||
private val m3u: M3U
|
||||
) : ExternalPlaylistManager {
|
||||
override suspend fun import(uri: Uri): ImportedPlaylist? {
|
||||
val filePath = documentPathFactory.unpackDocumentUri(uri) ?: return null
|
||||
|
||||
return try {
|
||||
context.contentResolverSafe.openInputStream(uri)?.use {
|
||||
val imported = m3u.read(it, filePath.directory) ?: return null
|
||||
val name = imported.name
|
||||
if (name != null) {
|
||||
return imported
|
||||
}
|
||||
// Strip extension
|
||||
val fileName = filePath.name ?: return imported
|
||||
val split = fileName.split(".")
|
||||
var newName = split[0]
|
||||
// Replace delimiters with space
|
||||
newName = newName.replace(Regex("[_-]"), " ")
|
||||
// Replace long stretches of whitespace with one space
|
||||
newName = newName.replace(Regex("\\s+"), " ")
|
||||
return ImportedPlaylist(newName, imported.paths)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
L.e("Failed to import playlist: $e")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun export(playlist: Playlist, uri: Uri, config: ExportConfig): Boolean {
|
||||
val filePath = documentPathFactory.unpackDocumentUri(uri) ?: return false
|
||||
val workingDirectory =
|
||||
if (config.absolute) {
|
||||
Path(filePath.volume, Components.parseUnix("/"))
|
||||
} else {
|
||||
filePath.directory
|
||||
}
|
||||
return try {
|
||||
val outputStream = context.contentResolverSafe.openOutputStream(uri)
|
||||
if (outputStream == null) {
|
||||
L.e("Failed to export playlist: Could not open output stream")
|
||||
return false
|
||||
}
|
||||
outputStream.use {
|
||||
m3u.write(playlist, it, workingDirectory, config)
|
||||
true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
L.e("Failed to export playlist: $e")
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* PlaylistFile.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.playlist
|
||||
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Song
|
||||
|
||||
data class PlaylistFile(
|
||||
val name: String,
|
||||
val songPointers: List<SongPointer>,
|
||||
val editor: PlaylistHandle
|
||||
)
|
||||
|
||||
sealed interface SongPointer {
|
||||
data class UID(val uid: Music.UID) : SongPointer
|
||||
// data class Path(val options: List<Path>) : SongPointer
|
||||
}
|
||||
|
||||
interface PlaylistHandle {
|
||||
val uid: Music.UID
|
||||
|
||||
suspend fun rename(name: String)
|
||||
|
||||
suspend fun add(songs: List<Song>)
|
||||
|
||||
suspend fun rewrite(songs: List<Song>)
|
||||
|
||||
suspend fun delete()
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* PlaylistDatabase.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.playlist.db
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Database
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.Transaction
|
||||
import androidx.room.TypeConverters
|
||||
import org.oxycblt.musikr.Music
|
||||
|
||||
/**
|
||||
* Allows persistence of all user-created music information.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@Database(
|
||||
entities = [PlaylistInfo::class, PlaylistSong::class, PlaylistSongCrossRef::class],
|
||||
version = 30,
|
||||
exportSchema = false)
|
||||
@TypeConverters(Music.UID.TypeConverters::class)
|
||||
abstract class PlaylistDatabase : RoomDatabase() {
|
||||
internal abstract fun playlistDao(): PlaylistDao
|
||||
|
||||
companion object {
|
||||
fun from(context: Context) =
|
||||
Room.databaseBuilder(
|
||||
context.applicationContext, PlaylistDatabase::class.java, "user_music.db")
|
||||
.fallbackToDestructiveMigration()
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Handle playlist defragmentation? I really don't want dead songs to accumulate in this
|
||||
// database.
|
||||
|
||||
/**
|
||||
* The DAO for persisted playlist information.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@Dao
|
||||
internal abstract class PlaylistDao {
|
||||
/**
|
||||
* Read out all playlists stored in the database.
|
||||
*
|
||||
* @return A list of [RawPlaylist] representing each playlist stored.
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM PlaylistInfo")
|
||||
abstract suspend fun readRawPlaylists(): List<RawPlaylist>
|
||||
|
||||
/**
|
||||
* Create a new playlist.
|
||||
*
|
||||
* @param rawPlaylist The [RawPlaylist] to create.
|
||||
*/
|
||||
@Transaction
|
||||
open suspend fun insertPlaylist(rawPlaylist: RawPlaylist) {
|
||||
insertInfo(rawPlaylist.playlistInfo)
|
||||
insertSongs(rawPlaylist.songs)
|
||||
insertRefs(
|
||||
rawPlaylist.songs.map {
|
||||
PlaylistSongCrossRef(
|
||||
playlistUid = rawPlaylist.playlistInfo.playlistUid, songUid = it.songUid)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the currently-stored [PlaylistInfo] for a playlist entry.
|
||||
*
|
||||
* @param playlistInfo The new [PlaylistInfo] to store.
|
||||
*/
|
||||
@Transaction
|
||||
open suspend fun replacePlaylistInfo(playlistInfo: PlaylistInfo) {
|
||||
deleteInfo(playlistInfo.playlistUid)
|
||||
insertInfo(playlistInfo)
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a playlist entry's [PlaylistInfo] and [PlaylistSong].
|
||||
*
|
||||
* @param playlistUid The [Music.UID] of the playlist to delete.
|
||||
*/
|
||||
@Transaction
|
||||
open suspend fun deletePlaylist(playlistUid: Music.UID) {
|
||||
deleteInfo(playlistUid)
|
||||
deleteRefs(playlistUid)
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert new song entries into a playlist.
|
||||
*
|
||||
* @param playlistUid The [Music.UID] of the playlist to insert into.
|
||||
* @param songs The [PlaylistSong] representing each song to put into the playlist.
|
||||
*/
|
||||
@Transaction
|
||||
open suspend fun insertPlaylistSongs(playlistUid: Music.UID, songs: List<PlaylistSong>) {
|
||||
insertSongs(songs)
|
||||
insertRefs(
|
||||
songs.map { PlaylistSongCrossRef(playlistUid = playlistUid, songUid = it.songUid) })
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the currently stored songs of the given playlist entry.
|
||||
*
|
||||
* @param playlistUid The [Music.UID] of the playlist to update.
|
||||
* @param songs The [PlaylistSong] representing the new list of songs to be placed in the
|
||||
* playlist.
|
||||
*/
|
||||
@Transaction
|
||||
open suspend fun replacePlaylistSongs(playlistUid: Music.UID, songs: List<PlaylistSong>) {
|
||||
deleteRefs(playlistUid)
|
||||
insertSongs(songs)
|
||||
insertRefs(
|
||||
songs.map { PlaylistSongCrossRef(playlistUid = playlistUid, songUid = it.songUid) })
|
||||
}
|
||||
|
||||
/** Internal, do not use. */
|
||||
@Insert(onConflict = OnConflictStrategy.ABORT)
|
||||
abstract suspend fun insertInfo(info: PlaylistInfo)
|
||||
|
||||
/** Internal, do not use. */
|
||||
@Query("DELETE FROM PlaylistInfo where playlistUid = :playlistUid")
|
||||
abstract suspend fun deleteInfo(playlistUid: Music.UID)
|
||||
|
||||
/** Internal, do not use. */
|
||||
@Insert(onConflict = OnConflictStrategy.IGNORE)
|
||||
abstract suspend fun insertSongs(songs: List<PlaylistSong>)
|
||||
|
||||
/** Internal, do not use. */
|
||||
@Insert(onConflict = OnConflictStrategy.ABORT)
|
||||
abstract suspend fun insertRefs(refs: List<PlaylistSongCrossRef>)
|
||||
|
||||
/** Internal, do not use. */
|
||||
@Query("DELETE FROM PlaylistSongCrossRef where playlistUid = :playlistUid")
|
||||
abstract suspend fun deleteRefs(playlistUid: Music.UID)
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* RawPlaylist.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.playlist.db
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Junction
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.Relation
|
||||
import org.oxycblt.musikr.Music
|
||||
|
||||
/**
|
||||
* Raw playlist information persisted to [PlaylistDatabase].
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
internal data class RawPlaylist(
|
||||
@Embedded val playlistInfo: PlaylistInfo,
|
||||
@Relation(
|
||||
parentColumn = "playlistUid",
|
||||
entityColumn = "songUid",
|
||||
associateBy = Junction(PlaylistSongCrossRef::class))
|
||||
val songs: List<PlaylistSong>
|
||||
)
|
||||
|
||||
/**
|
||||
* UID and name information corresponding to a [RawPlaylist] entry.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@Entity internal data class PlaylistInfo(@PrimaryKey val playlistUid: Music.UID, val name: String)
|
||||
|
||||
/**
|
||||
* Song information corresponding to a [RawPlaylist] entry.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@Entity internal data class PlaylistSong(@PrimaryKey val songUid: Music.UID)
|
||||
|
||||
/**
|
||||
* Links individual songs to a playlist entry.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@Entity
|
||||
internal data class PlaylistSongCrossRef(
|
||||
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
||||
@ColumnInfo(index = true) val playlistUid: Music.UID,
|
||||
@ColumnInfo(index = true) val songUid: Music.UID
|
||||
)
|
||||
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* StoredPlaylists.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.playlist.db
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.asFlow
|
||||
import kotlinx.coroutines.flow.emitAll
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import org.oxycblt.musikr.playlist.PlaylistFile
|
||||
|
||||
interface StoredPlaylists {
|
||||
fun read(): Flow<PlaylistFile>
|
||||
|
||||
companion object {
|
||||
fun from(database: PlaylistDatabase): StoredPlaylists =
|
||||
StoredPlaylistsImpl(database.playlistDao())
|
||||
}
|
||||
}
|
||||
|
||||
private class StoredPlaylistsImpl(private val playlistDao: PlaylistDao) : StoredPlaylists {
|
||||
override fun read() = flow { emitAll(playlistDao.readRawPlaylists().asFlow().map { TODO() }) }
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* M3U.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.playlist.m3u
|
||||
|
||||
import android.content.Context
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import java.io.BufferedReader
|
||||
import java.io.BufferedWriter
|
||||
import java.io.InputStream
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStream
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.Volume
|
||||
import org.oxycblt.musikr.fs.path.VolumeManager
|
||||
import org.oxycblt.musikr.playlist.ExportConfig
|
||||
import org.oxycblt.musikr.playlist.ImportedPlaylist
|
||||
import org.oxycblt.musikr.playlist.PossiblePaths
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import org.oxycblt.musikr.tag.util.correctWhitespace
|
||||
import org.oxycblt.musikr.util.unlikelyToBeNull
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
* Minimal M3U file format implementation.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface M3U {
|
||||
/**
|
||||
* Reads an M3U file from the given [stream] and returns a [ImportedPlaylist] containing the
|
||||
* paths to the files listed in the M3U file.
|
||||
*
|
||||
* @param stream The stream to read the M3U file from.
|
||||
* @param workingDirectory The directory that the M3U file is contained in. This is used to
|
||||
* resolve relative paths.
|
||||
* @return An [ImportedPlaylist] containing the paths to the files listed in the M3U file,
|
||||
*/
|
||||
fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist?
|
||||
|
||||
/**
|
||||
* Writes the given [playlist] to the given [outputStream] in the M3U format,.
|
||||
*
|
||||
* @param playlist The playlist to write.
|
||||
* @param outputStream The stream to write the M3U file to.
|
||||
* @param workingDirectory The directory that the M3U file is contained in. This is used to
|
||||
* create relative paths to where the M3U file is assumed to be stored.
|
||||
* @param config The configuration to use when exporting the playlist.
|
||||
*/
|
||||
fun write(
|
||||
playlist: Playlist,
|
||||
outputStream: OutputStream,
|
||||
workingDirectory: Path,
|
||||
config: ExportConfig
|
||||
)
|
||||
|
||||
companion object {
|
||||
/** The mime type used for M3U files by the android system. */
|
||||
const val MIME_TYPE = "audio/x-mpegurl"
|
||||
|
||||
fun from(context: Context): M3U = M3UImpl(context, VolumeManager.from(context))
|
||||
}
|
||||
}
|
||||
|
||||
private class M3UImpl(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val volumeManager: VolumeManager
|
||||
) : M3U {
|
||||
override fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist? {
|
||||
val volumes = volumeManager.getVolumes()
|
||||
val reader = BufferedReader(InputStreamReader(stream))
|
||||
val paths = mutableListOf<PossiblePaths>()
|
||||
var name: String? = null
|
||||
|
||||
consumeFile@ while (true) {
|
||||
var path: String?
|
||||
collectMetadata@ while (true) {
|
||||
// The M3U format consists of "entries" that begin with a bunch of metadata
|
||||
// prefixed with "#", and then a relative/absolute path or url to the file.
|
||||
// We don't really care about the metadata except for the playlist name, so
|
||||
// we discard everything but that.
|
||||
val currentLine =
|
||||
(reader.readLine() ?: break@consumeFile).correctWhitespace()
|
||||
?: continue@collectMetadata
|
||||
if (currentLine.startsWith("#")) {
|
||||
// Metadata entries are roughly structured
|
||||
val split = currentLine.split(":", limit = 2)
|
||||
when (split[0]) {
|
||||
// Playlist name
|
||||
"#PLAYLIST" -> name = split.getOrNull(1)?.correctWhitespace()
|
||||
// Add more metadata handling here if needed.
|
||||
else -> {}
|
||||
}
|
||||
} else {
|
||||
// Something that isn't a metadata entry, assume it's a path. It could be
|
||||
// a URL, but it'll just get mangled really badly and not match with anything,
|
||||
// so it's okay.
|
||||
path = currentLine
|
||||
break@collectMetadata
|
||||
}
|
||||
}
|
||||
|
||||
if (path == null) {
|
||||
L.e("Expected a path, instead got an EOF")
|
||||
break@consumeFile
|
||||
}
|
||||
|
||||
// There is basically no formal specification of file paths in M3U, and it differs
|
||||
// based on the programs that generated it. I more or less have to consider any possible
|
||||
// interpretation as valid.
|
||||
val interpretations = interpretPath(path)
|
||||
val possibilities =
|
||||
interpretations.flatMap { expandInterpretation(it, workingDirectory, volumes) }
|
||||
|
||||
paths.add(possibilities)
|
||||
}
|
||||
|
||||
return if (paths.isNotEmpty()) {
|
||||
ImportedPlaylist(name, paths)
|
||||
} else {
|
||||
// Couldn't get anything useful out of this file.
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private data class InterpretedPath(val components: Components, val likelyAbsolute: Boolean)
|
||||
|
||||
private fun interpretPath(path: String): List<InterpretedPath> =
|
||||
when {
|
||||
path.startsWith('/') -> listOf(InterpretedPath(Components.parseUnix(path), true))
|
||||
path.startsWith("./") -> listOf(InterpretedPath(Components.parseUnix(path), false))
|
||||
path.matches(WINDOWS_VOLUME_PREFIX_REGEX) ->
|
||||
listOf(InterpretedPath(Components.parseWindows(path.substring(2)), true))
|
||||
path.startsWith("\\") -> listOf(InterpretedPath(Components.parseWindows(path), true))
|
||||
path.startsWith(".\\") -> listOf(InterpretedPath(Components.parseWindows(path), false))
|
||||
else ->
|
||||
listOf(
|
||||
InterpretedPath(Components.parseUnix(path), false),
|
||||
InterpretedPath(Components.parseWindows(path), true))
|
||||
}
|
||||
|
||||
private fun expandInterpretation(
|
||||
path: InterpretedPath,
|
||||
workingDirectory: Path,
|
||||
volumes: List<Volume>
|
||||
): List<Path> {
|
||||
val absoluteInterpretation = Path(workingDirectory.volume, path.components)
|
||||
val relativeInterpretation =
|
||||
Path(workingDirectory.volume, path.components.absoluteTo(workingDirectory.components))
|
||||
val volumeExactMatch = volumes.find { it.components?.contains(path.components) == true }
|
||||
val volumeInterpretation =
|
||||
volumeExactMatch?.let {
|
||||
val components =
|
||||
unlikelyToBeNull(volumeExactMatch.components).containing(path.components)
|
||||
Path(volumeExactMatch, components)
|
||||
}
|
||||
return if (path.likelyAbsolute) {
|
||||
listOfNotNull(volumeInterpretation, absoluteInterpretation, relativeInterpretation)
|
||||
} else {
|
||||
listOfNotNull(relativeInterpretation, volumeInterpretation, absoluteInterpretation)
|
||||
}
|
||||
}
|
||||
|
||||
override fun write(
|
||||
playlist: Playlist,
|
||||
outputStream: OutputStream,
|
||||
workingDirectory: Path,
|
||||
config: ExportConfig
|
||||
) {
|
||||
val writer = outputStream.bufferedWriter()
|
||||
// Try to be as compliant to the spec as possible while also cramming it full of extensions
|
||||
// I imagine other players will use.
|
||||
writer.writeLine("#EXTM3U")
|
||||
writer.writeLine("#EXTENC:UTF-8")
|
||||
writer.writeLine("#PLAYLIST:${playlist.name.raw}")
|
||||
for (song in playlist.songs) {
|
||||
writer.writeLine("#EXTINF:${song.durationMs},${song.name.raw}")
|
||||
val albumName = song.album.name
|
||||
if (albumName is Name.Known) {
|
||||
writer.writeLine("#EXTALB:${albumName.raw}")
|
||||
}
|
||||
// TODO: See if repeating #EXTART and #EXTGEN is legal
|
||||
for (artist in song.artists) {
|
||||
val name = artist.name
|
||||
if (name is Name.Known) {
|
||||
writer.writeLine("#EXTART:${name.raw}")
|
||||
}
|
||||
}
|
||||
for (genre in song.genres) {
|
||||
val name = genre.name
|
||||
if (name is Name.Known) {
|
||||
writer.writeLine("#EXTGEN:${name.raw}")
|
||||
}
|
||||
}
|
||||
|
||||
val formattedPath =
|
||||
if (config.absolute) {
|
||||
// The path is already absolute in this case, but we need to prefix and separate
|
||||
// it differently depending on the setting.
|
||||
if (config.windowsPaths) {
|
||||
// Assume the plain windows C volume, since that's probably where most music
|
||||
// libraries are on a windows PC.
|
||||
"C:\\\\${song.path.components.windowsString}"
|
||||
} else {
|
||||
"/${song.path.components.unixString}"
|
||||
}
|
||||
} else {
|
||||
// First need to make this path relative to the working directory of the M3U
|
||||
// file, and then format it with the correct separators.
|
||||
val relativePath = song.path.components.relativeTo(workingDirectory.components)
|
||||
if (config.windowsPaths) {
|
||||
relativePath.windowsString
|
||||
} else {
|
||||
relativePath.unixString
|
||||
}
|
||||
}
|
||||
writer.writeLine(formattedPath)
|
||||
}
|
||||
writer.flush()
|
||||
}
|
||||
|
||||
private fun BufferedWriter.writeLine(line: String) {
|
||||
write(line)
|
||||
newLine()
|
||||
}
|
||||
|
||||
private fun Components.absoluteTo(workingDirectory: Components): Components {
|
||||
var absoluteComponents = workingDirectory
|
||||
for (component in components) {
|
||||
when (component) {
|
||||
// Parent specifier, go "back" one directory (in practice cleave off the last
|
||||
// component)
|
||||
".." -> absoluteComponents = absoluteComponents.parent()
|
||||
// Current directory, the components are already there.
|
||||
"." -> {}
|
||||
// New directory, add it
|
||||
else -> absoluteComponents = absoluteComponents.child(component)
|
||||
}
|
||||
}
|
||||
return absoluteComponents
|
||||
}
|
||||
|
||||
private fun Components.relativeTo(workingDirectory: Components): Components {
|
||||
// We want to find the common prefix of the working directory and path, and then
|
||||
// and them combine them with the correct relative elements to make sure they
|
||||
// resolve the same.
|
||||
var commonIndex = 0
|
||||
while (commonIndex < components.size &&
|
||||
commonIndex < workingDirectory.components.size &&
|
||||
components[commonIndex] == workingDirectory.components[commonIndex]) {
|
||||
++commonIndex
|
||||
}
|
||||
|
||||
var relativeComponents = Components.parseUnix(".")
|
||||
|
||||
// TODO: Simplify this logic
|
||||
when {
|
||||
commonIndex == components.size && commonIndex == workingDirectory.components.size -> {
|
||||
// The paths are the same. This shouldn't occur.
|
||||
}
|
||||
commonIndex == components.size -> {
|
||||
// The working directory is deeper in the path, backtrack.
|
||||
for (i in 0 ..< workingDirectory.components.size - commonIndex) {
|
||||
relativeComponents = relativeComponents.child("..")
|
||||
}
|
||||
}
|
||||
commonIndex == workingDirectory.components.size -> {
|
||||
// Working directory is shallower than the path, can just append the
|
||||
// non-common remainder of the path
|
||||
relativeComponents = relativeComponents.child(depth(commonIndex))
|
||||
}
|
||||
else -> {
|
||||
// The paths are siblings. Backtrack and append as needed.
|
||||
for (i in 0 ..< workingDirectory.components.size - commonIndex) {
|
||||
relativeComponents = relativeComponents.child("..")
|
||||
}
|
||||
relativeComponents = relativeComponents.child(depth(commonIndex))
|
||||
}
|
||||
}
|
||||
|
||||
return relativeComponents
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val WINDOWS_VOLUME_PREFIX_REGEX = Regex("^[A-Za-z]:\\\\.*")
|
||||
}
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2022 Auxio Project
|
||||
* Date.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag
|
||||
|
||||
import kotlin.math.max
|
||||
import org.oxycblt.musikr.util.inRangeOrNull
|
||||
import org.oxycblt.musikr.util.positiveOrNull
|
||||
|
||||
/**
|
||||
* An ISO-8601/RFC 3339 Date.
|
||||
*
|
||||
* This class only encodes the timestamp spec and it's conversion to a human-readable date, without
|
||||
* any other time management or validation. In general, this should only be used for display. Use
|
||||
* [from] to create an instance.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
class Date private constructor(private val tokens: List<Int>) : Comparable<Date> {
|
||||
val year = tokens[0]
|
||||
val month = tokens.getOrNull(1)
|
||||
val day = tokens.getOrNull(2)
|
||||
val hour = tokens.getOrNull(3)
|
||||
val minute = tokens.getOrNull(4)
|
||||
val second = tokens.getOrNull(5)
|
||||
|
||||
override fun equals(other: Any?) = other is Date && compareTo(other) == 0
|
||||
|
||||
override fun hashCode() = tokens.hashCode()
|
||||
|
||||
override fun toString() = StringBuilder().appendDate().toString()
|
||||
|
||||
override fun compareTo(other: Date): Int {
|
||||
for (i in 0 until max(tokens.size, other.tokens.size)) {
|
||||
val ai = tokens.getOrNull(i)
|
||||
val bi = other.tokens.getOrNull(i)
|
||||
when {
|
||||
ai != null && bi != null -> {
|
||||
val result = ai.compareTo(bi)
|
||||
if (result != 0) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
ai == null && bi != null -> return -1 // a < b
|
||||
ai == null && bi == null -> return 0 // a = b
|
||||
else -> return 1 // a < b
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
private fun StringBuilder.appendDate(): StringBuilder {
|
||||
// Construct an ISO-8601 date, dropping precision that doesn't exist.
|
||||
append(year.toStringFixed(4))
|
||||
append("-${(month ?: return this).toStringFixed(2)}")
|
||||
append("-${(day ?: return this).toStringFixed(2)}")
|
||||
append("T${(hour ?: return this).toStringFixed(2)}")
|
||||
append(":${(minute ?: return this.append('Z')).toStringFixed(2)}")
|
||||
append(":${(second ?: return this.append('Z')).toStringFixed(2)}")
|
||||
return this.append('Z')
|
||||
}
|
||||
|
||||
private fun Int.toStringFixed(len: Int) = toString().padStart(len, '0').substring(0 until len)
|
||||
|
||||
/**
|
||||
* A range of [Date]s. This is used in contexts where the [Date] of an item is derived from
|
||||
* several sub-items and thus can have a "range" of release dates. Use [from] to create an
|
||||
* instance.
|
||||
*
|
||||
* @author Alexander Capehart
|
||||
*/
|
||||
class Range(
|
||||
/** The earliest [Date] in the range. */
|
||||
val min: Date,
|
||||
/** the latest [Date] in the range. May be the same as [min]. ] */
|
||||
val max: Date
|
||||
) : Comparable<Range> {
|
||||
init {
|
||||
check(min <= max) { "Min date must be <= max date" }
|
||||
}
|
||||
|
||||
override fun equals(other: Any?) = other is Range && min == other.min && max == other.max
|
||||
|
||||
override fun hashCode() = 31 * max.hashCode() + min.hashCode()
|
||||
|
||||
override fun compareTo(other: Range) = min.compareTo(other.min)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* A [Regex] that can parse a variable-precision ISO-8601 timestamp. Derived from
|
||||
* https://github.com/quodlibet/mutagen
|
||||
*/
|
||||
private val ISO8601_REGEX by lazy {
|
||||
Regex(
|
||||
"""^(\d{4})([-.](\d{2})([-.](\d{2})([T ](\d{2})([:.](\d{2})([:.](\d{2})(Z)?)?)?)?)?)?$""")
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a [Date] from a year component.
|
||||
*
|
||||
* @param year The year component.
|
||||
* @return A new [Date] of the given component, or null if the component is invalid.
|
||||
*/
|
||||
fun from(year: Int) =
|
||||
if (year in 10000000..100000000) {
|
||||
// Year is actually more likely to be a separated date timestamp. Interpret
|
||||
// it as such.
|
||||
val stringYear = year.toString()
|
||||
from(
|
||||
stringYear.substring(0..3).toInt(),
|
||||
stringYear.substring(4..5).toInt(),
|
||||
stringYear.substring(6..7).toInt())
|
||||
} else {
|
||||
fromTokens(listOf(year))
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a [Date] from a date component.
|
||||
*
|
||||
* @param year The year component.
|
||||
* @param month The month component.
|
||||
* @param day The day component.
|
||||
* @return A new [Date] consisting of the given components. May have reduced precision if
|
||||
* the components were partially invalid, and will be null if all components are invalid.
|
||||
*/
|
||||
fun from(year: Int, month: Int, day: Int) = fromTokens(listOf(year, month, day))
|
||||
|
||||
/**
|
||||
* Create [Date] from a datetime component.
|
||||
*
|
||||
* @param year The year component.
|
||||
* @param month The month component.
|
||||
* @param day The day component.
|
||||
* @param hour The hour component
|
||||
* @return A new [Date] consisting of the given components. May have reduced precision if
|
||||
* the components were partially invalid, and will be null if all components are invalid.
|
||||
*/
|
||||
fun from(year: Int, month: Int, day: Int, hour: Int, minute: Int) =
|
||||
fromTokens(listOf(year, month, day, hour, minute))
|
||||
|
||||
/**
|
||||
* Create a [Date] from a [String] timestamp.
|
||||
*
|
||||
* @param timestamp The ISO-8601 timestamp to parse. Can have reduced precision.
|
||||
* @return A new [Date] consisting of the given components. May have reduced precision if
|
||||
* the components were partially invalid, and will be null if all components are invalid
|
||||
* or if the timestamp is invalid.
|
||||
*/
|
||||
fun from(timestamp: String): Date? {
|
||||
val tokens =
|
||||
// Match the input with the timestamp regex. If there is no match, see if we can
|
||||
// fall back to some kind of year value.
|
||||
(ISO8601_REGEX.matchEntire(timestamp)
|
||||
?: return timestamp.toIntOrNull()?.let(Companion::from))
|
||||
.groupValues
|
||||
// Filter to the specific tokens we want and convert them to integer tokens.
|
||||
.mapIndexedNotNull { index, s -> if (index % 2 != 0) s.toIntOrNull() else null }
|
||||
return fromTokens(tokens)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a [Date] from the given non-validated tokens.
|
||||
*
|
||||
* @param tokens The tokens to use for each date component, in order of precision.
|
||||
* @return A new [Date] consisting of the given components. May have reduced precision if
|
||||
* the components were partially invalid, and will be null if all components are invalid.
|
||||
*/
|
||||
private fun fromTokens(tokens: List<Int>): Date? {
|
||||
val validated = mutableListOf<Int>()
|
||||
transformTokens(tokens, validated)
|
||||
if (validated.isEmpty()) {
|
||||
// No token was valid, return null.
|
||||
return null
|
||||
}
|
||||
return Date(validated)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a list of tokens provided by [src], and add the valid ones to [dst]. Will stop
|
||||
* as soon as an invalid token is found.
|
||||
*
|
||||
* @param src The input tokens to validate.
|
||||
* @param dst The destination list to add valid tokens to.
|
||||
*/
|
||||
private fun transformTokens(src: List<Int>, dst: MutableList<Int>) {
|
||||
dst.add(src.getOrNull(0)?.positiveOrNull() ?: return)
|
||||
dst.add(src.getOrNull(1)?.inRangeOrNull(1..12) ?: return)
|
||||
dst.add(src.getOrNull(2)?.inRangeOrNull(1..31) ?: return)
|
||||
dst.add(src.getOrNull(3)?.inRangeOrNull(0..23) ?: return)
|
||||
dst.add(src.getOrNull(4)?.inRangeOrNull(0..59) ?: return)
|
||||
dst.add(src.getOrNull(5)?.inRangeOrNull(0..59) ?: return)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* Disc.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag
|
||||
|
||||
/**
|
||||
* A disc identifier for a song.
|
||||
*
|
||||
* @param number The disc number.
|
||||
* @param name The name of the disc group, if any. Null if not present.
|
||||
*/
|
||||
class Disc(val number: Int, val name: String?) : Comparable<Disc> {
|
||||
// We don't want to group discs by differing subtitles, so only compare by the number
|
||||
override fun equals(other: Any?) = other is Disc && number == other.number
|
||||
|
||||
override fun hashCode() = number.hashCode()
|
||||
|
||||
override fun compareTo(other: Disc) = number.compareTo(other.number)
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* Name.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag
|
||||
|
||||
import org.oxycblt.musikr.tag.interpret.Token
|
||||
|
||||
/**
|
||||
* The name of a music item.
|
||||
*
|
||||
* This class automatically implements advanced sorting heuristics for music naming,
|
||||
*
|
||||
* @author Alexander Capehart
|
||||
*/
|
||||
sealed interface Name : Comparable<Name> {
|
||||
/** A name that could be obtained for the music item. */
|
||||
abstract class Known : Name {
|
||||
/** The raw name string obtained. Should be ignored in favor of [resolve]. */
|
||||
abstract val raw: String
|
||||
/** The raw sort name string obtained. */
|
||||
abstract val sort: String?
|
||||
/** A tokenized version of the name that will be compared. */
|
||||
abstract val tokens: List<Token>
|
||||
|
||||
final override fun compareTo(other: Name) =
|
||||
when (other) {
|
||||
is Known -> {
|
||||
val result =
|
||||
tokens.zip(other.tokens).fold(0) { acc, (token, otherToken) ->
|
||||
acc.takeIf { it != 0 } ?: token.compareTo(otherToken)
|
||||
}
|
||||
if (result != 0) result else tokens.size.compareTo(other.tokens.size)
|
||||
}
|
||||
is Unknown -> 1
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A placeholder name that is used when a [Known] name could not be obtained for the item.
|
||||
*
|
||||
* @author Alexander Capehart
|
||||
*/
|
||||
data class Unknown(val placeholder: Placeholder) : Name {
|
||||
override fun compareTo(other: Name) =
|
||||
when (other) {
|
||||
// Unknown names do not need any direct comparison right now.
|
||||
is Unknown -> 0
|
||||
// Unknown names always come before known names.
|
||||
is Known -> -1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum class Placeholder {
|
||||
ALBUM,
|
||||
ARTIST,
|
||||
GENRE
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Auxio Project
|
||||
* ReleaseType.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag
|
||||
|
||||
/**
|
||||
* The type of release an [Album] is considered. This includes EPs, Singles, Compilations, etc.
|
||||
*
|
||||
* This class is derived from the MusicBrainz Release Group Type specification. It can be found at:
|
||||
* https://musicbrainz.org/doc/Release_Group/Type
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
sealed interface ReleaseType {
|
||||
/**
|
||||
* A specification of what kind of performance this release is. If null, the release is
|
||||
* considered "Plain".
|
||||
*/
|
||||
val refinement: Refinement?
|
||||
|
||||
/**
|
||||
* A plain album.
|
||||
*
|
||||
* @param refinement A specification of what kind of performance this release is. If null, the
|
||||
* release is considered "Plain".
|
||||
*/
|
||||
data class Album(override val refinement: Refinement?) : ReleaseType
|
||||
|
||||
/**
|
||||
* A "Extended Play", or EP. Usually a smaller release consisting of 4-5 songs.
|
||||
*
|
||||
* @param refinement A specification of what kind of performance this release is. If null, the
|
||||
* release is considered "Plain".
|
||||
*/
|
||||
data class EP(override val refinement: Refinement?) : ReleaseType
|
||||
|
||||
/**
|
||||
* A single. Usually a release consisting of 1-2 songs.
|
||||
*
|
||||
* @param refinement A specification of what kind of performance this release is. If null, the
|
||||
* release is considered "Plain".
|
||||
*/
|
||||
data class Single(override val refinement: Refinement?) : ReleaseType
|
||||
|
||||
/**
|
||||
* A compilation. Usually consists of many songs from a variety of artists.
|
||||
*
|
||||
* @param refinement A specification of what kind of performance this release is. If null, the
|
||||
* release is considered "Plain".
|
||||
*/
|
||||
data class Compilation(override val refinement: Refinement?) : ReleaseType
|
||||
|
||||
/**
|
||||
* A soundtrack. Similar to a [Compilation], but created for a specific piece of (usually
|
||||
* visual) media.
|
||||
*/
|
||||
data object Soundtrack : ReleaseType {
|
||||
override val refinement: Refinement?
|
||||
get() = null
|
||||
}
|
||||
|
||||
/**
|
||||
* A (DJ) Mix. These are usually one large track consisting of the artist playing several
|
||||
* sub-tracks with smooth transitions between them.
|
||||
*/
|
||||
data object Mix : ReleaseType {
|
||||
override val refinement: Refinement?
|
||||
get() = null
|
||||
}
|
||||
|
||||
/**
|
||||
* A Mix-tape. These are usually [EP]-sized releases of music made to promote an Artist or a
|
||||
* future release.
|
||||
*/
|
||||
data object Mixtape : ReleaseType {
|
||||
override val refinement: Refinement?
|
||||
get() = null
|
||||
}
|
||||
|
||||
/**
|
||||
* A demo. These are usually [EP]-sized releases of music made to promote an Artist or a future
|
||||
* release.
|
||||
*/
|
||||
data object Demo : ReleaseType {
|
||||
override val refinement: Refinement?
|
||||
get() = null
|
||||
}
|
||||
|
||||
/** A specification of what kind of performance a particular release is. */
|
||||
enum class Refinement {
|
||||
/** A release consisting of a live performance */
|
||||
LIVE,
|
||||
|
||||
/** A release consisting of another Artists remix of a prior performance. */
|
||||
REMIX
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Parse a [ReleaseType] from a string formatted with the MusicBrainz Release Group Type
|
||||
* specification.
|
||||
*
|
||||
* @param types A list of values consisting of valid release type values.
|
||||
* @return A [ReleaseType] consisting of the given types, or null if the types were not
|
||||
* valid.
|
||||
*/
|
||||
fun parse(types: List<String>): ReleaseType? {
|
||||
val primary = types.getOrNull(0) ?: return null
|
||||
return when {
|
||||
// Primary types should be the first types in the sequence.
|
||||
primary.equals("album", true) -> types.parseSecondaryTypes(1) { Album(it) }
|
||||
primary.equals("ep", true) -> types.parseSecondaryTypes(1) { EP(it) }
|
||||
primary.equals("single", true) -> types.parseSecondaryTypes(1) { Single(it) }
|
||||
// The spec makes no mention of whether primary types are a pre-requisite for
|
||||
// secondary types, so we assume that it's not and map oprhan secondary types
|
||||
// to Album release types.
|
||||
else -> types.parseSecondaryTypes(0) { Album(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse "secondary" types (i.e not [Album], [EP], or [Single]) from a string formatted with
|
||||
* the MusicBrainz Release Group Type specification.
|
||||
*
|
||||
* @param index The index of the release type to parse.
|
||||
* @param convertRefinement Code to convert a [Refinement] into a [ReleaseType]
|
||||
* corresponding to the callee's context. This is used in order to handle secondary times
|
||||
* that are actually [Refinement]s.
|
||||
* @return A [ReleaseType] corresponding to the secondary type found at that index.
|
||||
*/
|
||||
private inline fun List<String>.parseSecondaryTypes(
|
||||
index: Int,
|
||||
convertRefinement: (Refinement?) -> ReleaseType
|
||||
): ReleaseType {
|
||||
val secondary = getOrNull(index)
|
||||
return if (secondary.equals("compilation", true)) {
|
||||
// Secondary type is a compilation, actually parse the third type
|
||||
// and put that into a compilation if needed.
|
||||
parseSecondaryTypeImpl(getOrNull(index + 1)) { Compilation(it) }
|
||||
} else {
|
||||
// Secondary type is a plain value, use the original values given.
|
||||
parseSecondaryTypeImpl(secondary, convertRefinement)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse "secondary" types (i.e not [Album], [EP], [Single]) that do not correspond to any
|
||||
* child values.
|
||||
*
|
||||
* @param type The release type value to parse.
|
||||
* @param convertRefinement Code to convert a [Refinement] into a [ReleaseType]
|
||||
* corresponding to the callee's context. This is used in order to handle secondary times
|
||||
* that are actually [Refinement]s.
|
||||
*/
|
||||
private inline fun parseSecondaryTypeImpl(
|
||||
type: String?,
|
||||
convertRefinement: (Refinement?) -> ReleaseType
|
||||
) =
|
||||
when {
|
||||
// Parse all the types that have no children
|
||||
type.equals("soundtrack", true) -> Soundtrack
|
||||
type.equals("mixtape/street", true) -> Mixtape
|
||||
type.equals("dj-mix", true) -> Mix
|
||||
type.equals("live", true) -> convertRefinement(Refinement.LIVE)
|
||||
type.equals("remix", true) -> convertRefinement(Refinement.REMIX)
|
||||
type.equals("demo", true) -> Demo
|
||||
else -> convertRefinement(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2022 Auxio Project
|
||||
* ReplayGainAdjustment.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag
|
||||
|
||||
/**
|
||||
* Represents a ReplayGain adjustment to apply during song playback.
|
||||
*
|
||||
* @param track The track-specific adjustment that should be applied. Null if not available.
|
||||
* @param album A more general album-specific adjustment that should be applied. Null if not
|
||||
* available.
|
||||
*/
|
||||
data class ReplayGainAdjustment(val track: Float?, val album: Float?)
|
||||
@@ -1,130 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Naming.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.interpret
|
||||
|
||||
import java.text.CollationKey
|
||||
import java.text.Collator
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import org.oxycblt.musikr.tag.Placeholder
|
||||
|
||||
abstract class Naming {
|
||||
fun name(raw: String?, sort: String?, placeholder: Placeholder): Name =
|
||||
if (raw != null) {
|
||||
name(raw, sort)
|
||||
} else {
|
||||
Name.Unknown(placeholder)
|
||||
}
|
||||
|
||||
abstract fun name(raw: String, sort: String?): Name.Known
|
||||
|
||||
companion object {
|
||||
fun intelligent(): Naming = IntelligentNaming
|
||||
|
||||
fun simple(): Naming = SimpleNaming
|
||||
}
|
||||
}
|
||||
|
||||
private data object IntelligentNaming : Naming() {
|
||||
override fun name(raw: String, sort: String?) = IntelligentKnownName(raw, sort)
|
||||
}
|
||||
|
||||
private data object SimpleNaming : Naming() {
|
||||
override fun name(raw: String, sort: String?) = SimpleKnownName(raw, sort)
|
||||
}
|
||||
|
||||
private val collator: Collator = Collator.getInstance().apply { strength = Collator.PRIMARY }
|
||||
private val punctRegex by lazy { Regex("[\\p{Punct}+]") }
|
||||
|
||||
// TODO: Consider how you want to handle whitespace and "gaps" in names.
|
||||
|
||||
/**
|
||||
* Plain [Name.Known] implementation that is internationalization-safe.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
private data class SimpleKnownName(override val raw: String, override val sort: String?) :
|
||||
Name.Known() {
|
||||
override val tokens = listOf(parseToken(sort ?: raw))
|
||||
|
||||
private fun parseToken(name: String): Token {
|
||||
// Remove excess punctuation from the string, as those usually aren't considered in sorting.
|
||||
val stripped = name.replace(punctRegex, "").trim().ifEmpty { name }
|
||||
val collationKey = collator.getCollationKey(stripped)
|
||||
// Always use lexicographic mode since we aren't parsing any numeric components
|
||||
return Token(collationKey, Token.Type.LEXICOGRAPHIC)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [Name.Known] implementation that adds advanced sorting behavior at the cost of localization.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
private data class IntelligentKnownName(override val raw: String, override val sort: String?) :
|
||||
Name.Known() {
|
||||
override val tokens = parseTokens(sort ?: raw)
|
||||
|
||||
private fun parseTokens(name: String): List<Token> {
|
||||
// TODO: This routine is consuming much of the song building runtime, find a way to
|
||||
// optimize it
|
||||
val stripped =
|
||||
name
|
||||
// Remove excess punctuation from the string, as those usually aren't
|
||||
// considered in sorting.
|
||||
.replace(punctRegex, "")
|
||||
.ifEmpty { name }
|
||||
.run {
|
||||
// Strip any english articles like "the" or "an" from the start, as music
|
||||
// sorting should ignore such when possible.
|
||||
when {
|
||||
length > 4 && startsWith("the ", ignoreCase = true) -> substring(4)
|
||||
length > 3 && startsWith("an ", ignoreCase = true) -> substring(3)
|
||||
length > 2 && startsWith("a ", ignoreCase = true) -> substring(2)
|
||||
else -> this
|
||||
}
|
||||
}
|
||||
|
||||
// To properly compare numeric components in names, we have to split them up into
|
||||
// individual lexicographic and numeric tokens and then individually compare them
|
||||
// with special logic.
|
||||
return TOKEN_REGEX.findAll(stripped).mapTo(mutableListOf()) { match ->
|
||||
// Remove excess whitespace where possible
|
||||
val token = match.value.trim().ifEmpty { match.value }
|
||||
val collationKey: CollationKey
|
||||
val type: Token.Type
|
||||
// Separate each token into their numeric and lexicographic counterparts.
|
||||
if (token.first().isDigit()) {
|
||||
// The digit string comparison breaks with preceding zero digits, remove those
|
||||
val digits =
|
||||
token.trimStart { Character.getNumericValue(it) == 0 }.ifEmpty { token }
|
||||
// Other languages have other types of digit strings, still use collation keys
|
||||
collationKey = collator.getCollationKey(digits)
|
||||
type = Token.Type.NUMERIC
|
||||
} else {
|
||||
collationKey = collator.getCollationKey(token)
|
||||
type = Token.Type.LEXICOGRAPHIC
|
||||
}
|
||||
Token(collationKey, type)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val TOKEN_REGEX by lazy { Regex("(\\d+)|(\\D+)") }
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* PreMusic.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.interpret
|
||||
|
||||
import android.net.Uri
|
||||
import java.util.UUID
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.cover.Cover
|
||||
import org.oxycblt.musikr.fs.Format
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.playlist.PlaylistHandle
|
||||
import org.oxycblt.musikr.tag.Date
|
||||
import org.oxycblt.musikr.tag.Disc
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import org.oxycblt.musikr.tag.ReleaseType
|
||||
import org.oxycblt.musikr.tag.ReplayGainAdjustment
|
||||
import org.oxycblt.musikr.util.update
|
||||
|
||||
data class PreSong(
|
||||
val musicBrainzId: UUID?,
|
||||
val name: Name.Known,
|
||||
val rawName: String,
|
||||
val track: Int?,
|
||||
val disc: Disc?,
|
||||
val date: Date?,
|
||||
val uri: Uri,
|
||||
val path: Path,
|
||||
val format: Format,
|
||||
val size: Long,
|
||||
val durationMs: Long,
|
||||
val replayGainAdjustment: ReplayGainAdjustment,
|
||||
val lastModified: Long,
|
||||
val dateAdded: Long,
|
||||
val cover: Cover.Single?,
|
||||
val preAlbum: PreAlbum,
|
||||
val preArtists: List<PreArtist>,
|
||||
val preGenres: List<PreGenre>
|
||||
) {
|
||||
fun computeUid() =
|
||||
musicBrainzId?.let { Music.UID.musicBrainz(Music.UID.Item.SONG, it) }
|
||||
?: Music.UID.auxio(Music.UID.Item.SONG) {
|
||||
// Song UIDs are based on the raw data without parsing so that they remain
|
||||
// consistent across music setting changes. Parents are not held up to the
|
||||
// same standard since grouping is already inherently linked to settings.
|
||||
update(rawName)
|
||||
update(preAlbum.rawName)
|
||||
update(date)
|
||||
|
||||
update(track)
|
||||
update(disc?.number)
|
||||
|
||||
update(preArtists.map { artist -> artist.rawName })
|
||||
update(preAlbum.preArtists.map { artist -> artist.rawName })
|
||||
}
|
||||
}
|
||||
|
||||
data class PreAlbum(
|
||||
val musicBrainzId: UUID?,
|
||||
val name: Name,
|
||||
val rawName: String?,
|
||||
val releaseType: ReleaseType,
|
||||
val preArtists: List<PreArtist>
|
||||
)
|
||||
|
||||
data class PreArtist(val musicBrainzId: UUID?, val name: Name, val rawName: String?)
|
||||
|
||||
data class PreGenre(
|
||||
val name: Name,
|
||||
val rawName: String?,
|
||||
)
|
||||
|
||||
data class PrePlaylist(val name: Name.Known, val rawName: String?, val handle: PlaylistHandle)
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Separators.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.interpret
|
||||
|
||||
import org.oxycblt.musikr.tag.util.correctWhitespace
|
||||
import org.oxycblt.musikr.tag.util.splitEscaped
|
||||
|
||||
/**
|
||||
* Defines the user-specified parsing of multi-value tags. This should be used to parse any tags
|
||||
* that may be delimited with a separator character.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
interface Separators {
|
||||
/**
|
||||
* Parse a separated value from one or more strings. If the value is already composed of more
|
||||
* than one value, nothing is done. Otherwise, it will attempt to split it based on the user's
|
||||
* separator preferences.
|
||||
*
|
||||
* @return A new list of one or more [String]s parsed by the separator configuration
|
||||
*/
|
||||
fun split(strings: List<String>): List<String>
|
||||
|
||||
companion object {
|
||||
const val COMMA = ','
|
||||
const val SEMICOLON = ';'
|
||||
const val SLASH = '/'
|
||||
const val PLUS = '+'
|
||||
const val AND = '&'
|
||||
|
||||
/**
|
||||
* Creates a new instance from a string of separator characters to use.
|
||||
*
|
||||
* @param chars The separator characters to use. Each character in the string will be
|
||||
* checked for when splitting a string list.
|
||||
* @return A new [Separators] instance reflecting the separators.
|
||||
*/
|
||||
fun from(chars: String) =
|
||||
if (chars.isNotEmpty()) {
|
||||
CharSeparators(chars.toSet())
|
||||
} else {
|
||||
NoSeparators
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class CharSeparators(private val chars: Set<Char>) : Separators {
|
||||
override fun split(strings: List<String>) =
|
||||
if (strings.size == 1) splitImpl(strings.first()) else strings
|
||||
|
||||
private fun splitImpl(string: String) =
|
||||
string.splitEscaped { chars.contains(it) }.correctWhitespace()
|
||||
}
|
||||
|
||||
private object NoSeparators : Separators {
|
||||
override fun split(strings: List<String>) = strings
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* TagInterpreter.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.interpret
|
||||
|
||||
import org.oxycblt.musikr.Interpretation
|
||||
import org.oxycblt.musikr.fs.Format
|
||||
import org.oxycblt.musikr.pipeline.RawSong
|
||||
import org.oxycblt.musikr.tag.Disc
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import org.oxycblt.musikr.tag.Placeholder
|
||||
import org.oxycblt.musikr.tag.ReleaseType
|
||||
import org.oxycblt.musikr.tag.ReplayGainAdjustment
|
||||
import org.oxycblt.musikr.tag.parse.ParsedTags
|
||||
import org.oxycblt.musikr.tag.util.parseId3GenreNames
|
||||
import org.oxycblt.musikr.util.toUuidOrNull
|
||||
|
||||
interface TagInterpreter {
|
||||
fun interpret(song: RawSong, interpretation: Interpretation): PreSong
|
||||
|
||||
companion object {
|
||||
fun new(): TagInterpreter = TagInterpreterImpl
|
||||
}
|
||||
}
|
||||
|
||||
private data object TagInterpreterImpl : TagInterpreter {
|
||||
override fun interpret(song: RawSong, interpretation: Interpretation): PreSong {
|
||||
val individualPreArtists =
|
||||
makePreArtists(
|
||||
song.tags.artistMusicBrainzIds,
|
||||
song.tags.artistNames,
|
||||
song.tags.artistSortNames,
|
||||
interpretation)
|
||||
val albumPreArtists =
|
||||
makePreArtists(
|
||||
song.tags.albumArtistMusicBrainzIds,
|
||||
song.tags.albumArtistNames,
|
||||
song.tags.albumArtistSortNames,
|
||||
interpretation)
|
||||
val preAlbum =
|
||||
makePreAlbum(song.tags, individualPreArtists, albumPreArtists, interpretation)
|
||||
val rawArtists =
|
||||
individualPreArtists.ifEmpty { albumPreArtists }.ifEmpty { listOf(unknownPreArtist()) }
|
||||
val rawGenres =
|
||||
makePreGenres(song.tags, interpretation).ifEmpty { listOf(unknownPreGenre()) }
|
||||
val uri = song.file.uri
|
||||
return PreSong(
|
||||
uri = uri,
|
||||
path = song.file.path,
|
||||
size = song.file.size,
|
||||
format = Format.infer(song.file.mimeType, song.properties.mimeType),
|
||||
lastModified = song.file.lastModified,
|
||||
// TODO: Figure out what to do with date added
|
||||
dateAdded = song.file.lastModified,
|
||||
musicBrainzId = song.tags.musicBrainzId?.toUuidOrNull(),
|
||||
name = interpretation.naming.name(song.tags.name, song.tags.sortName),
|
||||
rawName = song.tags.name,
|
||||
track = song.tags.track,
|
||||
disc = song.tags.disc?.let { Disc(it, song.tags.subtitle) },
|
||||
date = song.tags.date,
|
||||
durationMs = song.tags.durationMs,
|
||||
replayGainAdjustment =
|
||||
ReplayGainAdjustment(
|
||||
song.tags.replayGainTrackAdjustment,
|
||||
song.tags.replayGainAlbumAdjustment,
|
||||
),
|
||||
preAlbum = preAlbum,
|
||||
preArtists = rawArtists,
|
||||
preGenres = rawGenres,
|
||||
cover = song.cover)
|
||||
}
|
||||
|
||||
private fun makePreAlbum(
|
||||
parsedTags: ParsedTags,
|
||||
individualPreArtists: List<PreArtist>,
|
||||
albumPreArtists: List<PreArtist>,
|
||||
interpretation: Interpretation
|
||||
): PreAlbum {
|
||||
return PreAlbum(
|
||||
musicBrainzId = parsedTags.albumMusicBrainzId?.toUuidOrNull(),
|
||||
name =
|
||||
interpretation.naming.name(
|
||||
parsedTags.albumName, parsedTags.albumSortName, Placeholder.ALBUM),
|
||||
rawName = parsedTags.albumName,
|
||||
releaseType =
|
||||
ReleaseType.parse(interpretation.separators.split(parsedTags.releaseTypes))
|
||||
?: ReleaseType.Album(null),
|
||||
preArtists =
|
||||
albumPreArtists
|
||||
.ifEmpty { individualPreArtists }
|
||||
.ifEmpty { listOf(unknownPreArtist()) })
|
||||
}
|
||||
|
||||
private fun makePreArtists(
|
||||
rawMusicBrainzIds: List<String>,
|
||||
rawNames: List<String>,
|
||||
rawSortNames: List<String>,
|
||||
interpretation: Interpretation
|
||||
): List<PreArtist> {
|
||||
val musicBrainzIds = interpretation.separators.split(rawMusicBrainzIds)
|
||||
val names = interpretation.separators.split(rawNames)
|
||||
val sortNames = interpretation.separators.split(rawSortNames)
|
||||
return names.mapIndexed { i, name ->
|
||||
makePreArtist(musicBrainzIds.getOrNull(i), name, sortNames.getOrNull(i), interpretation)
|
||||
}
|
||||
}
|
||||
|
||||
private fun makePreArtist(
|
||||
musicBrainzId: String?,
|
||||
rawName: String?,
|
||||
sortName: String?,
|
||||
interpretation: Interpretation
|
||||
): PreArtist {
|
||||
val name = interpretation.naming.name(rawName, null, Placeholder.ARTIST)
|
||||
val musicBrainzId = musicBrainzId?.toUuidOrNull()
|
||||
return PreArtist(musicBrainzId, name, rawName)
|
||||
}
|
||||
|
||||
private fun unknownPreArtist() = PreArtist(null, Name.Unknown(Placeholder.GENRE), null)
|
||||
|
||||
private fun makePreGenres(
|
||||
parsedTags: ParsedTags,
|
||||
interpretation: Interpretation
|
||||
): List<PreGenre> {
|
||||
val genreNames =
|
||||
parsedTags.genreNames.parseId3GenreNames()
|
||||
?: interpretation.separators.split(parsedTags.genreNames)
|
||||
return genreNames.map { makePreGenre(it, interpretation) }
|
||||
}
|
||||
|
||||
private fun makePreGenre(rawName: String?, interpretation: Interpretation) =
|
||||
PreGenre(interpretation.naming.name(rawName, null, Placeholder.GENRE), rawName)
|
||||
|
||||
private fun unknownPreGenre() = PreGenre(Name.Unknown(Placeholder.GENRE), null)
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Token.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.interpret
|
||||
|
||||
import java.text.CollationKey
|
||||
|
||||
/** An individual part of a name string that can be compared intelligently. */
|
||||
data class Token(val collationKey: CollationKey, val type: Type) : Comparable<Token> {
|
||||
override fun compareTo(other: Token): Int {
|
||||
// Numeric tokens should always be lower than lexicographic tokens.
|
||||
val modeComp = type.compareTo(other.type)
|
||||
if (modeComp != 0) {
|
||||
return modeComp
|
||||
}
|
||||
|
||||
// Numeric strings must be ordered by magnitude, thus immediately short-circuit
|
||||
// the comparison if the lengths do not match.
|
||||
if (type == Type.NUMERIC &&
|
||||
collationKey.sourceString.length != other.collationKey.sourceString.length) {
|
||||
return collationKey.sourceString.length - other.collationKey.sourceString.length
|
||||
}
|
||||
|
||||
return collationKey.compareTo(other.collationKey)
|
||||
}
|
||||
|
||||
/** Denotes the type of comparison to be performed with this token. */
|
||||
enum class Type {
|
||||
/** Compare as a digit string, like "65". */
|
||||
NUMERIC,
|
||||
/** Compare as a standard alphanumeric string, like "65daysofstatic" */
|
||||
LEXICOGRAPHIC
|
||||
}
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* ExoPlayerTagFields.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.parse
|
||||
|
||||
import androidx.core.text.isDigitsOnly
|
||||
import org.oxycblt.ktaglib.Metadata
|
||||
import org.oxycblt.musikr.tag.Date
|
||||
import org.oxycblt.musikr.tag.util.parseId3v2PositionField
|
||||
import org.oxycblt.musikr.tag.util.parseXiphPositionField
|
||||
import org.oxycblt.musikr.util.nonZeroOrNull
|
||||
|
||||
// Song
|
||||
fun Metadata.musicBrainzId() =
|
||||
(xiph["MUSICBRAINZ_RELEASETRACKID"]
|
||||
?: xiph["MUSICBRAINZ RELEASE TRACK ID"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ RELEASE TRACK ID"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ_RELEASETRACKID"])
|
||||
?.first()
|
||||
|
||||
fun Metadata.name() = (xiph["TITLE"] ?: id3v2["TIT2"])?.first()
|
||||
|
||||
fun Metadata.sortName() = (xiph["TITLESORT"] ?: id3v2["TSOT"])?.first()
|
||||
|
||||
// Track.
|
||||
fun Metadata.track() =
|
||||
(parseXiphPositionField(
|
||||
xiph["TRACKNUMBER"]?.first(),
|
||||
(xiph["TOTALTRACKS"] ?: xiph["TRACKTOTAL"] ?: xiph["TRACKC"])?.first())
|
||||
?: id3v2["TRCK"]?.run { first().parseId3v2PositionField() })
|
||||
|
||||
// Disc and it's subtitle name.
|
||||
fun Metadata.disc() =
|
||||
(parseXiphPositionField(
|
||||
xiph["DISCNUMBER"]?.first(),
|
||||
(xiph["TOTALDISCS"] ?: xiph["DISCTOTAL"] ?: xiph["DISCC"])?.run { first() })
|
||||
?: id3v2["TPOS"]?.run { first().parseId3v2PositionField() })
|
||||
|
||||
fun Metadata.subtitle() = (xiph["DISCSUBTITLE"] ?: id3v2["TSST"])?.first()
|
||||
|
||||
// Dates are somewhat complicated, as not only did their semantics change from a flat year
|
||||
// value in ID3v2.3 to a full ISO-8601 date in ID3v2.4, but there are also a variety of
|
||||
// date types.
|
||||
// Our hierarchy for dates is as such:
|
||||
// 1. ID3v2.4 Original Date, as it resolves the "Released in X, Remastered in Y" issue
|
||||
// 2. ID3v2.4 Recording Date, as it is the most common date type
|
||||
// 3. ID3v2.4 Release Date, as it is the second most common date type
|
||||
// 4. ID3v2.3 Original Date, as it is like #1
|
||||
// 5. ID3v2.3 Release Year, as it is the most common date type
|
||||
// TODO: Show original and normal dates side-by-side
|
||||
// TODO: Handle dates that are in "January" because the actual specific release date
|
||||
// isn't known?
|
||||
fun Metadata.date() =
|
||||
(xiph["ORIGINALDATE"]?.run { Date.from(first()) }
|
||||
?: xiph["DATE"]?.run { Date.from(first()) }
|
||||
?: xiph["YEAR"]?.run { Date.from(first()) }
|
||||
?:
|
||||
|
||||
// xiph dates are less complicated, but there are still several types
|
||||
// Our hierarchy for dates is as such:
|
||||
// 1. Original Date, as it solves the "Released in X, Remastered in Y" issue
|
||||
// 2. Date, as it is the most common date type
|
||||
// 3. Year, as old xiph tags tended to use this (I know this because it's the only
|
||||
// date tag that android supports, so it must be 15 years old or more!)
|
||||
id3v2["TDOR"]?.run { Date.from(first()) }
|
||||
?: id3v2["TDRC"]?.run { Date.from(first()) }
|
||||
?: id3v2["TDRL"]?.run { Date.from(first()) }
|
||||
?: parseId3v23Date())
|
||||
|
||||
// Album
|
||||
fun Metadata.albumMusicBrainzId() =
|
||||
(xiph["MUSICBRAINZ_ALBUMID"]
|
||||
?: xiph["MUSICBRAINZ ALBUM ID"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ ALBUM ID"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ_ALBUMID"])
|
||||
?.first()
|
||||
|
||||
fun Metadata.albumName() = (xiph["ALBUM"] ?: id3v2["TALB"])?.first()
|
||||
|
||||
fun Metadata.albumSortName() = (xiph["ALBUMSORT"] ?: id3v2["TSOA"])?.first()
|
||||
|
||||
fun Metadata.releaseTypes() =
|
||||
(xiph["RELEASETYPE"]
|
||||
?: xiph["MUSICBRAINZ ALBUM TYPE"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ ALBUM TYPE"]
|
||||
?: id3v2["TXXX:RELEASETYPE"]
|
||||
?:
|
||||
// This is a non-standard iTunes extension
|
||||
id3v2["GRP1"])
|
||||
|
||||
// Artist
|
||||
fun Metadata.artistMusicBrainzIds() =
|
||||
(xiph["MUSICBRAINZ_ARTISTID"]
|
||||
?: xiph["MUSICBRAINZ ARTIST ID"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ ARTIST ID"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ_ARTISTID"])
|
||||
|
||||
fun Metadata.artistNames() =
|
||||
(xiph["ARTISTS"]
|
||||
?: xiph["ARTIST"]
|
||||
?: id3v2["TXXX:ARTISTS"]
|
||||
?: id3v2["TPE1"]
|
||||
?: id3v2["TXXX:ARTIST"])
|
||||
|
||||
fun Metadata.artistSortNames() =
|
||||
(xiph["ARTISTSSORT"]
|
||||
?: xiph["ARTISTS_SORT"]
|
||||
?: xiph["ARTISTS SORT"]
|
||||
?: xiph["ARTISTSORT"]
|
||||
?: xiph["ARTIST SORT"]
|
||||
?: id3v2["TXXX:ARTISTSSORT"]
|
||||
?: id3v2["TXXX:ARTISTS_SORT"]
|
||||
?: id3v2["TXXX:ARTISTS SORT"]
|
||||
?: id3v2["TSOP"]
|
||||
?: id3v2["TXXX:ARTISTSORT"]
|
||||
?: id3v2["TXXX:ARTIST SORT"])
|
||||
|
||||
fun Metadata.albumArtistMusicBrainzIds() =
|
||||
(xiph["MUSICBRAINZ_ALBUMARTISTID"]
|
||||
?: xiph["MUSICBRAINZ ALBUM ARTIST ID"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ ALBUM ARTIST ID"]
|
||||
?: id3v2["TXXX:MUSICBRAINZ_ALBUMARTISTID"])
|
||||
|
||||
fun Metadata.albumArtistNames() =
|
||||
(xiph["ALBUMARTISTS"]
|
||||
?: xiph["ALBUM_ARTISTS"]
|
||||
?: xiph["ALBUM ARTISTS"]
|
||||
?: xiph["ALBUMARTIST"]
|
||||
?: xiph["ALBUM ARTIST"]
|
||||
?: id3v2["TXXX:ALBUMARTISTS"]
|
||||
?: id3v2["TXXX:ALBUM_ARTISTS"]
|
||||
?: id3v2["TXXX:ALBUM ARTISTS"]
|
||||
?: id3v2["TPE2"]
|
||||
?: id3v2["TXXX:ALBUMARTIST"]
|
||||
?: id3v2["TXXX:ALBUM ARTIST"])
|
||||
|
||||
fun Metadata.albumArtistSortNames() =
|
||||
(xiph["ALBUMARTISTSSORT"]
|
||||
?: xiph["ALBUMARTISTS_SORT"]
|
||||
?: xiph["ALBUMARTISTS SORT"]
|
||||
?: xiph["ALBUMARTISTSORT"]
|
||||
?: xiph["ALBUM ARTIST SORT"]
|
||||
?: id3v2["TXXX:ALBUMARTISTSSORT"]
|
||||
?: id3v2["TXXX:ALBUMARTISTS_SORT"]
|
||||
?: id3v2["TXXX:ALBUMARTISTS SORT"]
|
||||
?: id3v2["TXXX:ALBUMARTISTSORT"]
|
||||
// This is a non-standard iTunes extension
|
||||
?: id3v2["TSO2"]
|
||||
?: id3v2["TXXX:ALBUM ARTIST SORT"])
|
||||
|
||||
// Genre
|
||||
fun Metadata.genreNames() = xiph["GENRE"] ?: id3v2["TCON"]
|
||||
|
||||
// Compilation Flag
|
||||
fun Metadata.isCompilation() =
|
||||
(xiph["COMPILATION"]
|
||||
?: xiph["ITUNESCOMPILATION"]
|
||||
?: id3v2["TCMP"] // This is a non-standard itunes extension
|
||||
?: id3v2["TXXX:COMPILATION"]
|
||||
?: id3v2["TXXX:ITUNESCOMPILATION"])
|
||||
?.let {
|
||||
// Ignore invalid instances of this tag
|
||||
it == listOf("1")
|
||||
}
|
||||
|
||||
// ReplayGain information
|
||||
fun Metadata.replayGainTrackAdjustment() =
|
||||
(xiph["R128_TRACK_GAIN"]?.parseR128Adjustment()
|
||||
?: xiph["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
|
||||
?: id3v2["TXXX:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment())
|
||||
|
||||
fun Metadata.replayGainAlbumAdjustment() =
|
||||
(xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment()
|
||||
?: xiph["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
|
||||
?: id3v2["TXXX:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment())
|
||||
|
||||
private fun Metadata.parseId3v23Date(): Date? {
|
||||
// Assume that TDAT/TIME can refer to TYER or TORY depending on if TORY
|
||||
// is present.
|
||||
val year =
|
||||
id3v2["TORY"]?.run { first().toIntOrNull() }
|
||||
?: id3v2["TYER"]?.run { first().toIntOrNull() }
|
||||
?: return null
|
||||
|
||||
val tdat = id3v2["TDAT"]
|
||||
return if (tdat != null && tdat.first().length == 4 && tdat.first().isDigitsOnly()) {
|
||||
// TDAT frames consist of a 4-digit string where the first two digits are
|
||||
// the month and the last two digits are the day.
|
||||
val mm = tdat.first().substring(0..1).toInt()
|
||||
val dd = tdat.first().substring(2..3).toInt()
|
||||
|
||||
val time = id3v2["TIME"]
|
||||
if (time != null && time.first().length == 4 && time.first().isDigitsOnly()) {
|
||||
// TIME frames consist of a 4-digit string where the first two digits are
|
||||
// the hour and the last two digits are the minutes. No second value is
|
||||
// possible.
|
||||
val hh = time.first().substring(0..1).toInt()
|
||||
val mi = time.first().substring(2..3).toInt()
|
||||
// Able to return a full date.
|
||||
Date.from(year, mm, dd, hh, mi)
|
||||
} else {
|
||||
// Unable to parse time, just return a date
|
||||
Date.from(year, mm, dd)
|
||||
}
|
||||
} else {
|
||||
// Unable to parse month/day, just return a year
|
||||
return Date.from(year)
|
||||
}
|
||||
}
|
||||
|
||||
private fun List<String>.parseR128Adjustment() =
|
||||
first().replace(REPLAYGAIN_ADJUSTMENT_FILTER_REGEX, "").toFloatOrNull()?.nonZeroOrNull()?.run {
|
||||
// Convert to fixed-point and adjust to LUFS 18 to match the ReplayGain scale
|
||||
this / 256f + 5
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a ReplayGain adjustment into a float value.
|
||||
*
|
||||
* @return A parsed adjustment float, or null if the adjustment had invalid formatting.
|
||||
*/
|
||||
private fun List<String>.parseReplayGainAdjustment() =
|
||||
first().replace(REPLAYGAIN_ADJUSTMENT_FILTER_REGEX, "").toFloatOrNull()?.nonZeroOrNull()
|
||||
|
||||
/**
|
||||
* Matches non-float information from ReplayGain adjustments. Derived from vanilla music:
|
||||
* https://github.com/vanilla-music/vanilla
|
||||
*/
|
||||
val REPLAYGAIN_ADJUSTMENT_FILTER_REGEX by lazy { Regex("[^\\d.-]") }
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* ParsedTags.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.parse
|
||||
|
||||
import org.oxycblt.musikr.tag.Date
|
||||
|
||||
data class ParsedTags(
|
||||
val durationMs: Long,
|
||||
val replayGainTrackAdjustment: Float? = null,
|
||||
val replayGainAlbumAdjustment: Float? = null,
|
||||
val musicBrainzId: String? = null,
|
||||
val name: String,
|
||||
val sortName: String? = null,
|
||||
val track: Int? = null,
|
||||
val disc: Int? = null,
|
||||
val subtitle: String? = null,
|
||||
val date: Date? = null,
|
||||
val albumMusicBrainzId: String? = null,
|
||||
val albumName: String? = null,
|
||||
val albumSortName: String? = null,
|
||||
val releaseTypes: List<String> = listOf(),
|
||||
val artistMusicBrainzIds: List<String> = listOf(),
|
||||
val artistNames: List<String> = listOf(),
|
||||
val artistSortNames: List<String> = listOf(),
|
||||
val albumArtistMusicBrainzIds: List<String> = listOf(),
|
||||
val albumArtistNames: List<String> = listOf(),
|
||||
val albumArtistSortNames: List<String> = listOf(),
|
||||
val genreNames: List<String> = listOf()
|
||||
)
|
||||
@@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* TagParser.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.parse
|
||||
|
||||
import org.oxycblt.ktaglib.Metadata
|
||||
import org.oxycblt.musikr.fs.query.DeviceFile
|
||||
|
||||
interface TagParser {
|
||||
fun parse(file: DeviceFile, metadata: Metadata): ParsedTags
|
||||
|
||||
companion object {
|
||||
fun new(): TagParser = TagParserImpl
|
||||
}
|
||||
}
|
||||
|
||||
class MissingTagError(what: String) : Error("missing tag: $what")
|
||||
|
||||
private data object TagParserImpl : TagParser {
|
||||
override fun parse(file: DeviceFile, metadata: Metadata): ParsedTags {
|
||||
return ParsedTags(
|
||||
durationMs = metadata.properties.durationMs,
|
||||
replayGainTrackAdjustment = metadata.replayGainTrackAdjustment(),
|
||||
replayGainAlbumAdjustment = metadata.replayGainAlbumAdjustment(),
|
||||
musicBrainzId = metadata.musicBrainzId(),
|
||||
name = metadata.name() ?: file.path.name ?: throw MissingTagError("name"),
|
||||
sortName = metadata.sortName(),
|
||||
track = metadata.track(),
|
||||
disc = metadata.disc(),
|
||||
subtitle = metadata.subtitle(),
|
||||
date = metadata.date(),
|
||||
albumMusicBrainzId = metadata.albumMusicBrainzId(),
|
||||
albumName = metadata.albumName(),
|
||||
albumSortName = metadata.albumSortName(),
|
||||
releaseTypes = metadata.releaseTypes() ?: listOf(),
|
||||
artistMusicBrainzIds = metadata.artistMusicBrainzIds() ?: listOf(),
|
||||
artistNames = metadata.artistNames() ?: listOf(),
|
||||
artistSortNames = metadata.artistSortNames() ?: listOf(),
|
||||
albumArtistMusicBrainzIds = metadata.albumArtistMusicBrainzIds() ?: listOf(),
|
||||
albumArtistNames = metadata.albumArtistNames() ?: listOf(),
|
||||
albumArtistSortNames = metadata.albumArtistSortNames() ?: listOf(),
|
||||
genreNames = metadata.genreNames() ?: listOf())
|
||||
}
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* ID3.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.util
|
||||
|
||||
/// --- ID3v2 PARSING ---
|
||||
|
||||
/**
|
||||
* Parse a multi-value genre name using ID3 rules. This will convert any ID3v1 integer
|
||||
* representations of genre fields into their named counterparts, and split up singular ID3v2-style
|
||||
* integer genre fields into one or more genres.
|
||||
*
|
||||
* @return A list of one or more genre names, or null if this multi-value list has no valid
|
||||
* formatting.
|
||||
*/
|
||||
fun List<String>.parseId3GenreNames() =
|
||||
if (size == 1) {
|
||||
first().parseId3MultiValueGenre()
|
||||
} else {
|
||||
// Nothing to split, just map any ID3v1 genres to their name counterparts.
|
||||
map { it.parseId3v1Genre() ?: it }
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a single ID3v1/ID3v2 integer genre field into their named representations.
|
||||
*
|
||||
* @return list of one or more genre names, or null if this is not in ID3v2 format.
|
||||
*/
|
||||
private fun String.parseId3MultiValueGenre() =
|
||||
parseId3v1Genre()?.let { listOf(it) } ?: parseId3v2Genre()
|
||||
|
||||
/**
|
||||
* Parse an ID3v1 integer genre field.
|
||||
*
|
||||
* @return A named genre if the field is a valid integer, "Cover" or "Remix" if the field is
|
||||
* "CR"/"RX" respectively, and nothing if the field is not a valid ID3v1 integer genre.
|
||||
*/
|
||||
private fun String.parseId3v1Genre(): String? {
|
||||
// ID3v1 genres are a plain integer value without formatting, so in that case
|
||||
// try to index the genre table with such.
|
||||
val numeric =
|
||||
toIntOrNull()
|
||||
// Not a numeric value, try some other fixed values.
|
||||
?: return when (this) {
|
||||
// CR and RX are not technically ID3v1, but are formatted similarly to a plain
|
||||
// number.
|
||||
"CR" -> "Cover"
|
||||
"RX" -> "Remix"
|
||||
else -> null
|
||||
}
|
||||
return genreTable.getOrNull(numeric)
|
||||
}
|
||||
|
||||
/**
|
||||
* A [Regex] that implements parsing for ID3v2's genre format. Derived from mutagen:
|
||||
* https://github.com/quodlibet/mutagen
|
||||
*/
|
||||
private val id3v2GenreRe by lazy { Regex("((?:\\((\\d+|RX|CR)\\))*)(.+)?") }
|
||||
|
||||
/**
|
||||
* Parse an ID3v2 integer genre field, which has support for multiple genre values and combined
|
||||
* named/integer genres.
|
||||
*
|
||||
* @return A list of one or more genres, or null if the field is not a valid ID3v2 integer genre.
|
||||
*/
|
||||
private fun String.parseId3v2Genre(): List<String>? {
|
||||
val groups = (id3v2GenreRe.matchEntire(this) ?: return null).groupValues
|
||||
val genres = mutableSetOf<String>()
|
||||
|
||||
// ID3v2.3 genres are far more complex and require string grokking to properly implement.
|
||||
// You can read the spec for it here: https://id3.org/id3v2.3.0#TCON
|
||||
// This implementation in particular is based off Mutagen's genre parser.
|
||||
|
||||
// Case 1: Genre IDs in the format (INT|RX|CR). If these exist, parse them as
|
||||
// ID3v1 tags.
|
||||
val genreIds = groups.getOrNull(1)
|
||||
if (!genreIds.isNullOrEmpty()) {
|
||||
val ids = genreIds.substring(1, genreIds.lastIndex).split(")(")
|
||||
for (id in ids) {
|
||||
id.parseId3v1Genre()?.let(genres::add)
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2: Genre names as a normal string. The only case we have to look out for are
|
||||
// escaped strings formatted as ((genre).
|
||||
val genreName = groups.getOrNull(3)
|
||||
if (!genreName.isNullOrEmpty()) {
|
||||
if (genreName.startsWith("((")) {
|
||||
genres.add(genreName.substring(1))
|
||||
} else {
|
||||
genres.add(genreName)
|
||||
}
|
||||
}
|
||||
|
||||
// If this parsing task didn't change anything, move on.
|
||||
if (genres.size == 1 && genres.first() == this) {
|
||||
return null
|
||||
}
|
||||
|
||||
return genres.toList()
|
||||
}
|
||||
|
||||
/**
|
||||
* A table of the "conventional" mapping between ID3v1 integer genres and their named counterparts.
|
||||
* Includes non-standard extensions.
|
||||
*/
|
||||
private val genreTable =
|
||||
arrayOf(
|
||||
// ID3 Standard
|
||||
"Blues",
|
||||
"Classic Rock",
|
||||
"Country",
|
||||
"Dance",
|
||||
"Disco",
|
||||
"Funk",
|
||||
"Grunge",
|
||||
"Hip-Hop",
|
||||
"Jazz",
|
||||
"Metal",
|
||||
"New Age",
|
||||
"Oldies",
|
||||
"Other",
|
||||
"Pop",
|
||||
"R&B",
|
||||
"Rap",
|
||||
"Reggae",
|
||||
"Rock",
|
||||
"Techno",
|
||||
"Industrial",
|
||||
"Alternative",
|
||||
"Ska",
|
||||
"Death Metal",
|
||||
"Pranks",
|
||||
"Soundtrack",
|
||||
"Euro-Techno",
|
||||
"Ambient",
|
||||
"Trip-Hop",
|
||||
"Vocal",
|
||||
"Jazz+Funk",
|
||||
"Fusion",
|
||||
"Trance",
|
||||
"Classical",
|
||||
"Instrumental",
|
||||
"Acid",
|
||||
"House",
|
||||
"Game",
|
||||
"Sound Clip",
|
||||
"Gospel",
|
||||
"Noise",
|
||||
"AlternRock",
|
||||
"Bass",
|
||||
"Soul",
|
||||
"Punk",
|
||||
"Space",
|
||||
"Meditative",
|
||||
"Instrumental Pop",
|
||||
"Instrumental Rock",
|
||||
"Ethnic",
|
||||
"Gothic",
|
||||
"Darkwave",
|
||||
"Techno-Industrial",
|
||||
"Electronic",
|
||||
"Pop-Folk",
|
||||
"Eurodance",
|
||||
"Dream",
|
||||
"Southern Rock",
|
||||
"Comedy",
|
||||
"Cult",
|
||||
"Gangsta",
|
||||
"Top 40",
|
||||
"Christian Rap",
|
||||
"Pop/Funk",
|
||||
"Jungle",
|
||||
"Native American",
|
||||
"Cabaret",
|
||||
"New Wave",
|
||||
"Psychadelic",
|
||||
"Rave",
|
||||
"Showtunes",
|
||||
"Trailer",
|
||||
"Lo-Fi",
|
||||
"Tribal",
|
||||
"Acid Punk",
|
||||
"Acid Jazz",
|
||||
"Polka",
|
||||
"Retro",
|
||||
"Musical",
|
||||
"Rock & Roll",
|
||||
"Hard Rock",
|
||||
|
||||
// Winamp extensions, more or less a de-facto standard
|
||||
"Folk",
|
||||
"Folk-Rock",
|
||||
"National Folk",
|
||||
"Swing",
|
||||
"Fast Fusion",
|
||||
"Bebob",
|
||||
"Latin",
|
||||
"Revival",
|
||||
"Celtic",
|
||||
"Bluegrass",
|
||||
"Avantgarde",
|
||||
"Gothic Rock",
|
||||
"Progressive Rock",
|
||||
"Psychedelic Rock",
|
||||
"Symphonic Rock",
|
||||
"Slow Rock",
|
||||
"Big Band",
|
||||
"Chorus",
|
||||
"Easy Listening",
|
||||
"Acoustic",
|
||||
"Humour",
|
||||
"Speech",
|
||||
"Chanson",
|
||||
"Opera",
|
||||
"Chamber Music",
|
||||
"Sonata",
|
||||
"Symphony",
|
||||
"Booty Bass",
|
||||
"Primus",
|
||||
"Porn Groove",
|
||||
"Satire",
|
||||
"Slow Jam",
|
||||
"Club",
|
||||
"Tango",
|
||||
"Samba",
|
||||
"Folklore",
|
||||
"Ballad",
|
||||
"Power Ballad",
|
||||
"Rhythmic Soul",
|
||||
"Freestyle",
|
||||
"Duet",
|
||||
"Punk Rock",
|
||||
"Drum Solo",
|
||||
"A capella",
|
||||
"Euro-House",
|
||||
"Dance Hall",
|
||||
"Goa",
|
||||
"Drum & Bass",
|
||||
"Club-House",
|
||||
"Hardcore",
|
||||
"Terror",
|
||||
"Indie",
|
||||
"Britpop",
|
||||
"Negerpunk",
|
||||
"Polsk Punk",
|
||||
"Beat",
|
||||
"Christian Gangsta",
|
||||
"Heavy Metal",
|
||||
"Black Metal",
|
||||
"Crossover",
|
||||
"Contemporary Christian",
|
||||
"Christian Rock",
|
||||
"Merengue",
|
||||
"Salsa",
|
||||
"Thrash Metal",
|
||||
"Anime",
|
||||
"JPop",
|
||||
"Synthpop",
|
||||
|
||||
// Winamp 5.6+ extensions, also used by EasyTAG. Not common, but post-rock is a good
|
||||
// genre and should be included in the mapping.
|
||||
"Abstract",
|
||||
"Art Rock",
|
||||
"Baroque",
|
||||
"Bhangra",
|
||||
"Big Beat",
|
||||
"Breakbeat",
|
||||
"Chillout",
|
||||
"Downtempo",
|
||||
"Dub",
|
||||
"EBM",
|
||||
"Eclectic",
|
||||
"Electro",
|
||||
"Electroclash",
|
||||
"Emo",
|
||||
"Experimental",
|
||||
"Garage",
|
||||
"Global",
|
||||
"IDM",
|
||||
"Illbient",
|
||||
"Industro-Goth",
|
||||
"Jam Band",
|
||||
"Krautrock",
|
||||
"Leftfield",
|
||||
"Lounge",
|
||||
"Math Rock",
|
||||
"New Romantic",
|
||||
"Nu-Breakz",
|
||||
"Post-Punk",
|
||||
"Post-Rock",
|
||||
"Psytrance",
|
||||
"Shoegaze",
|
||||
"Space Rock",
|
||||
"Trop Rock",
|
||||
"World Music",
|
||||
"Neoclassical",
|
||||
"Audiobook",
|
||||
"Audio Theatre",
|
||||
"Neue Deutsche Welle",
|
||||
"Podcast",
|
||||
"Indie Rock",
|
||||
"G-Funk",
|
||||
"Dubstep",
|
||||
"Garage Rock",
|
||||
"Psybient",
|
||||
|
||||
// Auxio's extensions, added because Future Garage is also a good genre.
|
||||
"Future Garage")
|
||||
@@ -1,83 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2022 Auxio Project
|
||||
* Transform.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.util
|
||||
|
||||
/// --- GENERIC PARSING ---
|
||||
|
||||
// TODO: Remove the escaping checks, it's too expensive to do this for every single tag.
|
||||
|
||||
/**
|
||||
* Split a [String] by the given selector, automatically handling escaped characters that satisfy
|
||||
* the selector.
|
||||
*
|
||||
* @param selector A block that determines if the string should be split at a given character.
|
||||
* @return One or more [String]s split by the selector.
|
||||
*/
|
||||
inline fun String.splitEscaped(selector: (Char) -> Boolean): List<String> {
|
||||
val split = mutableListOf<String>()
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* Fix trailing whitespace or blank contents in a [String].
|
||||
*
|
||||
* @return A string with trailing whitespace remove,d or null if the [String] was all whitespace or
|
||||
* empty.
|
||||
*/
|
||||
fun String.correctWhitespace() = trim().ifBlank { null }
|
||||
|
||||
/**
|
||||
* Fix trailing whitespace or blank contents within a list of [String]s.
|
||||
*
|
||||
* @return A list of non-blank strings with trailing whitespace removed.
|
||||
*/
|
||||
fun List<String>.correctWhitespace() = mapNotNull { it.correctWhitespace() }
|
||||
@@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* Vorbis.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.tag.util
|
||||
|
||||
import org.oxycblt.musikr.util.positiveOrNull
|
||||
|
||||
/**
|
||||
* Parse an ID3v2-style position + total [String] field. These fields consist of a number and an
|
||||
* (optional) total value delimited by a /.
|
||||
*
|
||||
* @return The position value extracted from the string field, or null if:
|
||||
* - The position could not be parsed
|
||||
* - The position was zeroed AND the total value was not present/zeroed
|
||||
*
|
||||
* @see transformPositionField
|
||||
*/
|
||||
fun String.parseId3v2PositionField() =
|
||||
split('/', limit = 2).let {
|
||||
transformPositionField(it[0].toIntOrNull(), it.getOrNull(1)?.toIntOrNull())
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a vorbis-style position + total field. These fields consist of two fields for the position
|
||||
* and total numbers.
|
||||
*
|
||||
* @param pos The position value, or null if not present.
|
||||
* @param total The total value, if not present.
|
||||
* @return The position value extracted from the field, or null if:
|
||||
* - The position could not be parsed
|
||||
* - The position was zeroed AND the total value was not present/zeroed
|
||||
*
|
||||
* @see transformPositionField
|
||||
*/
|
||||
fun parseXiphPositionField(pos: String?, total: String?) =
|
||||
transformPositionField(pos?.toIntOrNull(), total?.toIntOrNull())
|
||||
|
||||
/**
|
||||
* Transform a raw position + total field into a position a way that tolerates placeholder values.
|
||||
*
|
||||
* @param pos The position value, or null if not present.
|
||||
* @param total The total value, if not present.
|
||||
* @return The position value extracted from the field, or null if:
|
||||
* - The position could not be parsed
|
||||
* - The position was zeroed AND the total value was not present/zeroed
|
||||
*/
|
||||
fun transformPositionField(pos: Int?, total: Int?) =
|
||||
if (pos != null && (pos > 0 || (total?.positiveOrNull() != null))) {
|
||||
pos
|
||||
} else {
|
||||
null
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Auxio Project
|
||||
* LangUtil.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.oxycblt.musikr.util
|
||||
|
||||
import java.security.MessageDigest
|
||||
import java.util.UUID
|
||||
import kotlin.reflect.KClass
|
||||
import org.oxycblt.auxio.BuildConfig
|
||||
import org.oxycblt.musikr.tag.Date
|
||||
|
||||
/**
|
||||
* Sanitizes a value that is unlikely to be null. On debug builds, this aliases to [requireNotNull],
|
||||
* otherwise, it aliases to the unchecked dereference operator (!!). This can be used as a minor
|
||||
* optimization in certain cases.
|
||||
*/
|
||||
fun <T> unlikelyToBeNull(value: T?) =
|
||||
if (BuildConfig.DEBUG) {
|
||||
requireNotNull(value)
|
||||
} else {
|
||||
value!!
|
||||
}
|
||||
|
||||
/**
|
||||
* Aliases a check to ensure that the given number is non-zero.
|
||||
*
|
||||
* @return The given number if it's non-zero, null otherwise.
|
||||
*/
|
||||
fun Int.positiveOrNull() = if (this > 0) this else null
|
||||
|
||||
/**
|
||||
* Aliases a check to ensure that the given number is non-zero.
|
||||
*
|
||||
* @return The same number if it's non-zero, null otherwise.
|
||||
*/
|
||||
fun Float.nonZeroOrNull() = if (this != 0f) this else null
|
||||
|
||||
/**
|
||||
* Aliases a check to ensure a given value is in a specified range.
|
||||
*
|
||||
* @param range The valid range of values for this number.
|
||||
* @return The same number if it is in the range, null otherwise.
|
||||
*/
|
||||
fun Int.inRangeOrNull(range: IntRange) = if (range.contains(this)) this else null
|
||||
|
||||
/**
|
||||
* Convert a [String] to a [UUID].
|
||||
*
|
||||
* @return A [UUID] converted from the [String] value, or null if the value was not valid.
|
||||
* @see UUID.fromString
|
||||
*/
|
||||
fun String.toUuidOrNull(): UUID? =
|
||||
try {
|
||||
UUID.fromString(this)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
null
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a [MessageDigest] with a lowercase [String].
|
||||
*
|
||||
* @param string The [String] to hash. If null, it will not be hashed.
|
||||
*/
|
||||
fun MessageDigest.update(string: String?) {
|
||||
if (string != null) {
|
||||
update(string.lowercase().toByteArray())
|
||||
} else {
|
||||
update(0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a [MessageDigest] with the string representation of a [Date].
|
||||
*
|
||||
* @param date The [Date] to hash. If null, nothing will be done.
|
||||
*/
|
||||
fun MessageDigest.update(date: Date?) {
|
||||
if (date != null) {
|
||||
update(date.toString().toByteArray())
|
||||
} else {
|
||||
update(0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a [MessageDigest] with the lowercase versions of all of the input [String]s.
|
||||
*
|
||||
* @param strings The [String]s to hash. If a [String] is null, it will not be hashed.
|
||||
*/
|
||||
fun MessageDigest.update(strings: List<String?>) {
|
||||
strings.forEach(::update)
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a [MessageDigest] with the little-endian bytes of a [Int].
|
||||
*
|
||||
* @param n The [Int] to write. If null, nothing will be done.
|
||||
*/
|
||||
fun MessageDigest.update(n: Int?) {
|
||||
if (n != null) {
|
||||
update(byteArrayOf(n.toByte(), n.shr(8).toByte(), n.shr(16).toByte(), n.shr(24).toByte()))
|
||||
} else {
|
||||
update(0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily set up a reflected method. Automatically handles visibility changes. Adapted from Material
|
||||
* Files: https://github.com/zhanghai/MaterialFiles
|
||||
*
|
||||
* @param clazz The [KClass] to reflect into.
|
||||
* @param method The name of the method to obtain.
|
||||
*/
|
||||
fun lazyReflectedMethod(clazz: KClass<*>, method: String, vararg params: KClass<*>) = lazy {
|
||||
clazz.java.getDeclaredMethod(method, *params.map { it.java }.toTypedArray()).also {
|
||||
it.isAccessible = true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user