musikr: split off from auxio

This commit is contained in:
Alexander Capehart
2024-12-07 09:51:16 -07:00
parent 75c2d7cd16
commit abeabcb8df
157 changed files with 523 additions and 510 deletions
@@ -50,10 +50,10 @@ import org.oxycblt.auxio.home.HomeViewModel
import org.oxycblt.auxio.home.Outer
import org.oxycblt.auxio.list.ListViewModel
import org.oxycblt.auxio.music.IndexingState
import org.oxycblt.auxio.music.Music
import org.oxycblt.musikr.Music
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.OpenPanel
import org.oxycblt.auxio.playback.PlaybackBottomSheetBehavior
import org.oxycblt.auxio.playback.PlaybackViewModel
@@ -29,13 +29,13 @@ import org.oxycblt.auxio.detail.list.AlbumDetailListAdapter
import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.list.ListFragment
import org.oxycblt.auxio.list.menu.Menu
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.PlaylistMessage
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.resolveNames
import org.oxycblt.auxio.playback.PlaybackDecision
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.util.collect
@@ -29,14 +29,14 @@ import org.oxycblt.auxio.detail.list.ArtistDetailListAdapter
import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.list.ListFragment
import org.oxycblt.auxio.list.menu.Menu
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.PlaylistMessage
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.resolveNames
import org.oxycblt.auxio.playback.PlaybackDecision
import org.oxycblt.auxio.util.collect
import org.oxycblt.auxio.util.collectImmediately
@@ -35,8 +35,8 @@ import org.oxycblt.auxio.list.ListFragment
import org.oxycblt.auxio.list.ListViewModel
import org.oxycblt.auxio.list.PlainDivider
import org.oxycblt.auxio.list.PlainHeader
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.util.getDimenPixels
@@ -23,17 +23,17 @@ import javax.inject.Inject
import org.oxycblt.auxio.R
import org.oxycblt.auxio.list.ListSettings
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.tag.Disc
import org.oxycblt.auxio.musikr.tag.ReleaseType
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.ReleaseType
import timber.log.Timber as L
interface DetailGenerator {
@@ -40,16 +40,16 @@ import org.oxycblt.auxio.list.PlainDivider
import org.oxycblt.auxio.list.PlainHeader
import org.oxycblt.auxio.list.adapter.UpdateInstructions
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.metadata.AudioProperties
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.metadata.AudioProperties
import org.oxycblt.auxio.playback.PlaySong
import org.oxycblt.auxio.playback.PlaybackSettings
import org.oxycblt.auxio.util.Event
@@ -29,13 +29,13 @@ import org.oxycblt.auxio.detail.list.GenreDetailListAdapter
import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.list.ListFragment
import org.oxycblt.auxio.list.menu.Menu
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.PlaylistMessage
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaybackDecision
import org.oxycblt.auxio.util.collect
import org.oxycblt.auxio.util.collectImmediately
@@ -35,13 +35,13 @@ import org.oxycblt.auxio.detail.list.PlaylistDragCallback
import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.list.ListFragment
import org.oxycblt.auxio.list.menu.Menu
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.musikr.Playlist
import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.PlaylistMessage
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.auxio.playback.PlaybackDecision
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.ui.DialogAwareNavigationListener
@@ -32,11 +32,11 @@ import org.oxycblt.auxio.databinding.DialogSongDetailBinding
import org.oxycblt.auxio.detail.list.SongProperty
import org.oxycblt.auxio.detail.list.SongPropertyAdapter
import org.oxycblt.auxio.list.adapter.UpdateInstructions
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.auxio.musikr.metadata.AudioProperties
import org.oxycblt.auxio.musikr.tag.Name
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.resolveNames
import org.oxycblt.musikr.metadata.AudioProperties
import org.oxycblt.musikr.tag.Name
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.playback.replaygain.formatDb
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
@@ -25,7 +25,7 @@ import org.oxycblt.auxio.list.ClickableListListener
import org.oxycblt.auxio.list.adapter.FlexibleListAdapter
import org.oxycblt.auxio.list.adapter.SimpleDiffCallback
import org.oxycblt.auxio.list.recycler.DialogRecyclerView
import org.oxycblt.auxio.music.Artist
import org.oxycblt.musikr.Artist
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.inflater
@@ -23,12 +23,12 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Library
import org.oxycblt.auxio.music.Music
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.Music
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
import timber.log.Timber as L
/**
@@ -32,7 +32,7 @@ import org.oxycblt.auxio.databinding.DialogMusicChoicesBinding
import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.list.ClickableListListener
import org.oxycblt.auxio.list.adapter.UpdateInstructions
import org.oxycblt.auxio.music.Artist
import org.oxycblt.musikr.Artist
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.collectImmediately
import timber.log.Timber as L
@@ -35,10 +35,10 @@ import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.list.SelectableListListener
import org.oxycblt.auxio.list.adapter.SelectionIndicatorAdapter
import org.oxycblt.auxio.list.adapter.SimpleDiffCallback
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.tag.Disc
import org.oxycblt.auxio.musikr.tag.resolveNumber
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.resolveNumber
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.getAttrColorCompat
@@ -29,10 +29,10 @@ import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.list.SelectableListListener
import org.oxycblt.auxio.list.adapter.SelectionIndicatorAdapter
import org.oxycblt.auxio.list.adapter.SimpleDiffCallback
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.inflater
@@ -35,7 +35,7 @@ import org.oxycblt.auxio.list.adapter.SelectionIndicatorAdapter
import org.oxycblt.auxio.list.adapter.SimpleDiffCallback
import org.oxycblt.auxio.list.recycler.BasicHeaderViewHolder
import org.oxycblt.auxio.list.recycler.DividerViewHolder
import org.oxycblt.auxio.music.Music
import org.oxycblt.musikr.Music
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.inflater
@@ -24,10 +24,10 @@ import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.list.adapter.SimpleDiffCallback
import org.oxycblt.auxio.list.recycler.ArtistViewHolder
import org.oxycblt.auxio.list.recycler.SongViewHolder
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
/**
* A [DetailListAdapter] implementing the header and sub-items for the [Genre] detail view.
@@ -40,9 +40,9 @@ import org.oxycblt.auxio.list.adapter.SelectionIndicatorAdapter
import org.oxycblt.auxio.list.adapter.SimpleDiffCallback
import org.oxycblt.auxio.list.recycler.MaterialDragCallback
import org.oxycblt.auxio.list.recycler.SongViewHolder
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.resolveNames
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.getAttrColorCompat
import org.oxycblt.auxio.util.inflater
@@ -26,7 +26,7 @@ import org.oxycblt.auxio.databinding.DialogSortBinding
import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.list.sort.SortDialog
import org.oxycblt.auxio.music.Album
import org.oxycblt.musikr.Album
import org.oxycblt.auxio.util.collectImmediately
import timber.log.Timber as L
@@ -26,7 +26,7 @@ import org.oxycblt.auxio.databinding.DialogSortBinding
import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.list.sort.SortDialog
import org.oxycblt.auxio.music.Artist
import org.oxycblt.musikr.Artist
import org.oxycblt.auxio.util.collectImmediately
import timber.log.Timber as L
@@ -26,7 +26,7 @@ import org.oxycblt.auxio.databinding.DialogSortBinding
import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.list.sort.SortDialog
import org.oxycblt.auxio.music.Genre
import org.oxycblt.musikr.Genre
import org.oxycblt.auxio.util.collectImmediately
import timber.log.Timber as L
@@ -26,7 +26,7 @@ import org.oxycblt.auxio.databinding.DialogSortBinding
import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.list.sort.SortDialog
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.musikr.Playlist
import org.oxycblt.auxio.util.collectImmediately
import timber.log.Timber as L
@@ -59,14 +59,14 @@ import org.oxycblt.auxio.list.ListViewModel
import org.oxycblt.auxio.list.SelectionFragment
import org.oxycblt.auxio.list.menu.Menu
import org.oxycblt.auxio.music.IndexingState
import org.oxycblt.auxio.music.Music
import org.oxycblt.musikr.Music
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.musikr.Playlist
import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.PlaylistMessage
import org.oxycblt.auxio.musikr.IndexingProgress
import org.oxycblt.auxio.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.IndexingProgress
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.auxio.playback.PlaybackDecision
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.util.collect
@@ -22,13 +22,13 @@ import javax.inject.Inject
import org.oxycblt.auxio.home.tabs.Tab
import org.oxycblt.auxio.list.ListSettings
import org.oxycblt.auxio.list.adapter.UpdateInstructions
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import timber.log.Timber as L
interface HomeGenerator {
@@ -27,12 +27,12 @@ import org.oxycblt.auxio.home.tabs.Tab
import org.oxycblt.auxio.list.ListSettings
import org.oxycblt.auxio.list.adapter.UpdateInstructions
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaySong
import org.oxycblt.auxio.playback.PlaybackSettings
import org.oxycblt.auxio.util.Event
@@ -37,12 +37,12 @@ import org.oxycblt.auxio.list.adapter.SelectionIndicatorAdapter
import org.oxycblt.auxio.list.recycler.AlbumViewHolder
import org.oxycblt.auxio.list.recycler.FastScrollRecyclerView
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.Album
import org.oxycblt.musikr.Album
import org.oxycblt.auxio.music.IndexingState
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.playback.secsToMs
@@ -35,12 +35,12 @@ import org.oxycblt.auxio.list.adapter.SelectionIndicatorAdapter
import org.oxycblt.auxio.list.recycler.ArtistViewHolder
import org.oxycblt.auxio.list.recycler.FastScrollRecyclerView
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.Artist
import org.oxycblt.musikr.Artist
import org.oxycblt.auxio.music.IndexingState
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.util.collectImmediately
@@ -35,12 +35,12 @@ import org.oxycblt.auxio.list.adapter.SelectionIndicatorAdapter
import org.oxycblt.auxio.list.recycler.FastScrollRecyclerView
import org.oxycblt.auxio.list.recycler.GenreViewHolder
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.Genre
import org.oxycblt.musikr.Genre
import org.oxycblt.auxio.music.IndexingState
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.util.collectImmediately
@@ -35,11 +35,11 @@ import org.oxycblt.auxio.list.recycler.FastScrollRecyclerView
import org.oxycblt.auxio.list.recycler.PlaylistViewHolder
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.IndexingState
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.util.collectImmediately
@@ -37,10 +37,10 @@ import org.oxycblt.auxio.list.recycler.FastScrollRecyclerView
import org.oxycblt.auxio.list.recycler.SongViewHolder
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.IndexingState
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.playback.secsToMs
@@ -20,7 +20,6 @@ package org.oxycblt.auxio.image
import android.content.Context
import android.graphics.Bitmap
import androidx.core.graphics.drawable.toBitmap
import coil3.ImageLoader
import coil3.request.Disposable
import coil3.request.ImageRequest
@@ -28,7 +27,7 @@ import coil3.size.Size
import coil3.toBitmap
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
/**
* A utility to provide bitmaps in a race-less manner.
@@ -53,12 +53,12 @@ import javax.inject.Inject
import org.oxycblt.auxio.R
import org.oxycblt.auxio.image.coil.RoundedRectTransformation
import org.oxycblt.auxio.image.coil.SquareCropTransformation
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.cover.Cover
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.cover.Cover
import org.oxycblt.auxio.ui.MaterialFader
import org.oxycblt.auxio.ui.UISettings
import org.oxycblt.auxio.util.getAttrColorCompat
@@ -44,7 +44,7 @@ import okio.FileSystem
import okio.buffer
import okio.source
import org.oxycblt.auxio.image.stack.CoverRetriever
import org.oxycblt.auxio.musikr.cover.Cover
import org.oxycblt.musikr.cover.Cover
class CoverKeyer @Inject constructor() : Keyer<Cover> {
override fun key(data: Cover, options: Options) = "${data.key}&${options.size}"
@@ -21,8 +21,8 @@ package org.oxycblt.auxio.image.stack
import java.io.InputStream
import javax.inject.Inject
import org.oxycblt.auxio.image.stack.extractor.CoverExtractor
import org.oxycblt.auxio.musikr.cover.Cover
import org.oxycblt.auxio.musikr.cover.CoverCache
import org.oxycblt.musikr.cover.Cover
import org.oxycblt.musikr.cover.CoverCache
import timber.log.Timber
interface CoverRetriever {
@@ -20,7 +20,7 @@ package org.oxycblt.auxio.image.stack.extractor
import android.net.Uri
import javax.inject.Inject
import org.oxycblt.auxio.musikr.cover.Cover
import org.oxycblt.musikr.cover.Cover
interface CoverExtractor {
suspend fun extract(cover: Cover.Single): ByteArray?
@@ -20,7 +20,7 @@ package org.oxycblt.auxio.list
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import org.oxycblt.auxio.music.Music
import org.oxycblt.musikr.Music
/**
* A Fragment containing a selectable list.
@@ -25,14 +25,14 @@ import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.oxycblt.auxio.list.menu.Menu
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaySong
import org.oxycblt.auxio.util.Event
import org.oxycblt.auxio.util.MutableEvent
@@ -21,7 +21,7 @@ package org.oxycblt.auxio.list.adapter
import android.view.View
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import org.oxycblt.auxio.music.Music
import org.oxycblt.musikr.Music
import timber.log.Timber as L
/**
@@ -21,12 +21,12 @@ package org.oxycblt.auxio.list.menu
import android.os.Parcelable
import androidx.annotation.MenuRes
import kotlinx.parcelize.Parcelize
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.playback.PlaySong
/**
@@ -27,12 +27,12 @@ import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogMenuBinding
import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.list.ListViewModel
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.resolveNames
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.util.getPlural
@@ -23,7 +23,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.playback.PlaySong
import timber.log.Timber as L
@@ -32,13 +32,13 @@ import org.oxycblt.auxio.list.PlainDivider
import org.oxycblt.auxio.list.SelectableListListener
import org.oxycblt.auxio.list.adapter.SelectionIndicatorAdapter
import org.oxycblt.auxio.list.adapter.SimpleDiffCallback
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.areNamesTheSame
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.areNamesTheSame
import org.oxycblt.musikr.resolveNames
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.getPlural
import org.oxycblt.auxio.util.inflater
@@ -20,11 +20,11 @@ package org.oxycblt.auxio.list.sort
import org.oxycblt.auxio.IntegerTable
import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
/**
* A sorting method.
@@ -19,7 +19,7 @@
package org.oxycblt.auxio.music
import android.os.Build
import org.oxycblt.auxio.musikr.IndexingProgress
import org.oxycblt.musikr.IndexingProgress
/** Version-aware permission identifier for reading audio files. */
val PERMISSION_READ_AUDIO =
@@ -1,413 +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.auxio.music
import android.content.Context
import android.net.Uri
import android.os.Parcelable
import androidx.room.TypeConverter
import java.security.MessageDigest
import java.util.UUID
import kotlin.math.max
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.musikr.cover.Cover
import org.oxycblt.auxio.musikr.fs.MimeType
import org.oxycblt.auxio.musikr.fs.Path
import org.oxycblt.auxio.musikr.tag.Date
import org.oxycblt.auxio.musikr.tag.Disc
import org.oxycblt.auxio.musikr.tag.Name
import org.oxycblt.auxio.musikr.tag.ReleaseType
import org.oxycblt.auxio.playback.replaygain.ReplayGainAdjustment
import org.oxycblt.auxio.util.concatLocalized
import org.oxycblt.auxio.util.toUuidOrNull
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?
}
/**
* 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 : Item {
/**
* 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 type: MusicType,
private val uuid: UUID
) : Parcelable {
// Cache the hashCode for HashMap efficiency.
@IgnoredOnParcel private var hashCode = format.hashCode()
init {
hashCode = 31 * hashCode + type.hashCode()
hashCode = 31 * hashCode + uuid.hashCode()
}
override fun hashCode() = hashCode
override fun equals(other: Any?) =
other is UID && format == other.format && type == other.type && uuid == other.uuid
override fun toString() = "${format.namespace}:${type.intCode.toString(16)}-$uuid"
/**
* 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(UID::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 type The analogous [MusicType] of the item that created this [UID].
*/
fun auxio(type: MusicType): UID {
return UID(Format.AUXIO, type, 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 type The analogous [MusicType] of the 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(type: MusicType, 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, type, uuid)
}
/**
* Creates a MusicBrainz-style [UID] with a [UUID] derived from the MusicBrainz ID
* extracted from a file.
*
* @param type The analogous [MusicType] of 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(type: MusicType, mbid: UUID) = UID(Format.MUSICBRAINZ, type, 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 type =
MusicType.fromIntCode(ids[0].toIntOrNull(16) ?: return null) ?: 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 {
/** 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 [MimeType] of the audio file. Only intended for display. */
val mimeType: MimeType
/** 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
}
/**
* Run [Name.resolve] on each instance in the given list and concatenate them into a [String] in a
* localized manner.
*
* @param context [Context] required
* @return A concatenated string.
*/
fun <T : Music> List<T>.resolveNames(context: Context) =
concatLocalized(context) { it.name.resolve(context) }
/**
* Returns if [Music.name] matches for each item in a list. Useful for scenarios where the display
* information of an item must be compared without a context.
*
* @param other The list of items to compare to.
* @return True if they are the same (by [Music.name]), false otherwise.
*/
fun <T : Music> List<T>.areNamesTheSame(other: List<T>): Boolean {
for (i in 0 until max(size, other.size)) {
val a = getOrNull(i) ?: return false
val b = other.getOrNull(i) ?: return false
if (a.name != b.name) {
return false
}
}
return true
}
@@ -25,12 +25,16 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import org.oxycblt.auxio.music.MusicRepository.IndexingWorker
import org.oxycblt.auxio.musikr.Indexer
import org.oxycblt.auxio.musikr.IndexingProgress
import org.oxycblt.auxio.musikr.model.MutableLibrary
import org.oxycblt.auxio.musikr.tag.Interpretation
import org.oxycblt.auxio.musikr.tag.Name
import org.oxycblt.auxio.musikr.tag.interpret.Separators
import org.oxycblt.musikr.Indexer
import org.oxycblt.musikr.IndexingProgress
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.model.MutableLibrary
import org.oxycblt.musikr.tag.Interpretation
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.interpret.Separators
import timber.log.Timber as L
/**
@@ -24,7 +24,7 @@ import androidx.core.content.edit
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import org.oxycblt.auxio.R
import org.oxycblt.auxio.musikr.fs.path.DocumentPathFactory
import org.oxycblt.musikr.fs.path.DocumentPathFactory
import org.oxycblt.auxio.settings.Settings
import timber.log.Timber as L
@@ -29,10 +29,15 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.oxycblt.auxio.R
import org.oxycblt.auxio.list.ListSettings
import org.oxycblt.auxio.musikr.playlist.ExportConfig
import org.oxycblt.auxio.musikr.playlist.ExternalPlaylistManager
import org.oxycblt.musikr.playlist.ExportConfig
import org.oxycblt.musikr.playlist.ExternalPlaylistManager
import org.oxycblt.auxio.util.Event
import org.oxycblt.auxio.util.MutableEvent
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import timber.log.Timber as L
/**
@@ -33,7 +33,7 @@ import org.oxycblt.auxio.databinding.DialogMusicChoicesBinding
import org.oxycblt.auxio.list.ClickableListListener
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.Song
import org.oxycblt.musikr.Song
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.collectImmediately
import org.oxycblt.auxio.util.navigateSafe
@@ -29,7 +29,7 @@ import dagger.hilt.android.AndroidEntryPoint
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogDeletePlaylistBinding
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.musikr.Playlist
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.collectImmediately
import org.oxycblt.auxio.util.unlikelyToBeNull
@@ -31,9 +31,9 @@ import dagger.hilt.android.AndroidEntryPoint
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogPlaylistExportBinding
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.musikr.playlist.ExportConfig
import org.oxycblt.auxio.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.playlist.ExportConfig
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.collectImmediately
import org.oxycblt.auxio.util.unlikelyToBeNull
@@ -27,12 +27,12 @@ import kotlinx.coroutines.flow.StateFlow
import org.oxycblt.auxio.R
import org.oxycblt.auxio.list.Item
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.Music
import org.oxycblt.musikr.Music
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.musikr.Playlist
import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.playlist.ExportConfig
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.playlist.ExportConfig
import timber.log.Timber as L
/**
@@ -24,7 +24,7 @@ import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.oxycblt.auxio.databinding.ItemMusicLocationBinding
import org.oxycblt.auxio.list.recycler.DialogRecyclerView
import org.oxycblt.auxio.musikr.fs.Path
import org.oxycblt.musikr.fs.Path
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.inflater
import timber.log.Timber as L
@@ -36,7 +36,7 @@ import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.musikr.fs.path.DocumentPathFactory
import org.oxycblt.musikr.fs.path.DocumentPathFactory
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.showToast
import timber.log.Timber as L
@@ -29,7 +29,7 @@ import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogSeparatorsBinding
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.musikr.tag.interpret.Separators
import org.oxycblt.musikr.tag.interpret.Separators
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import timber.log.Timber as L
@@ -25,7 +25,7 @@ import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.ForegroundServiceNotification
import org.oxycblt.auxio.IntegerTable
import org.oxycblt.auxio.R
import org.oxycblt.auxio.musikr.IndexingProgress
import org.oxycblt.musikr.IndexingProgress
import org.oxycblt.auxio.util.newMainPendingIntent
import timber.log.Timber as L
@@ -30,7 +30,7 @@ import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.ForegroundListener
import org.oxycblt.auxio.ForegroundServiceNotification
import org.oxycblt.auxio.music.IndexingState
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.musikr.MusicParent
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.playback.state.PlaybackStateManager
@@ -27,14 +27,14 @@ import androidx.annotation.StringRes
import androidx.media.utils.MediaConstants
import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MusicParent
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.resolveNames
import org.oxycblt.auxio.playback.formatDurationDs
import org.oxycblt.auxio.util.getPlural
@@ -27,15 +27,15 @@ import org.oxycblt.auxio.detail.DetailGenerator
import org.oxycblt.auxio.detail.DetailSection
import org.oxycblt.auxio.home.HomeGenerator
import org.oxycblt.auxio.list.adapter.UpdateInstructions
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.Music
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.tag.resolveNumber
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.tag.resolveNumber
import org.oxycblt.auxio.search.SearchEngine
class MusicBrowser
@@ -27,7 +27,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import org.oxycblt.auxio.music.MusicRepository
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.musikr.fs.contentResolverSafe
import org.oxycblt.musikr.fs.contentResolverSafe
import timber.log.Timber as L
/**
@@ -1,82 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* Indexer.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.auxio.musikr
import android.net.Uri
import javax.inject.Inject
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.auxio.musikr.model.MutableLibrary
import org.oxycblt.auxio.musikr.pipeline.EvaluateStep
import org.oxycblt.auxio.musikr.pipeline.ExploreStep
import org.oxycblt.auxio.musikr.pipeline.ExtractStep
import org.oxycblt.auxio.musikr.tag.Interpretation
interface Indexer {
suspend fun run(
uris: List<Uri>,
interpretation: Interpretation,
onProgress: suspend (IndexingProgress) -> Unit = {}
): MutableLibrary
}
/**
* 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 IndexerImpl
@Inject
constructor(
private val exploreStep: ExploreStep,
private val extractStep: ExtractStep,
private val evaluateStep: EvaluateStep
) : Indexer {
override suspend fun run(
uris: List<Uri>,
interpretation: Interpretation,
onProgress: suspend (IndexingProgress) -> Unit
) = coroutineScope {
var exploredCount = 0
val explored =
exploreStep
.explore(uris)
.buffer(Channel.UNLIMITED)
.onStart { onProgress(IndexingProgress.Songs(0, 0)) }
.onEach { onProgress(IndexingProgress.Songs(0, ++exploredCount)) }
var extractedCount = 0
val extracted =
extractStep
.extract(explored)
.buffer(Channel.UNLIMITED)
.onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) }
.onCompletion { onProgress(IndexingProgress.Indeterminate) }
evaluateStep.evaluate(interpretation, extracted)
}
}
@@ -1,30 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* StackModule.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.auxio.musikr
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface StackModule {
@Binds fun indexer(impl: IndexerImpl): Indexer
}
@@ -1,55 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* CacheModule.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.auxio.musikr.cover
import android.content.Context
import androidx.room.Room
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
interface StackModule {
@Singleton @Binds fun appFiles(impl: CoverFilesImpl): CoverFiles
@Binds fun coverCache(cache: CoverCacheImpl): CoverCache
@Binds fun coverIdentifier(identifierImpl: CoverIdentifierImpl): CoverIdentifier
@Binds fun coverFormat(coverFormatImpl: CoverFormatImpl): CoverFormat
}
@Module
@InstallIn(SingletonComponent::class)
class StoredCoversDatabaseModule {
@Provides fun storedCoversDao(database: StoredCoversDatabase) = database.storedCoversDao()
@Singleton
@Provides
fun database(@ApplicationContext context: Context) =
Room.databaseBuilder(
context.applicationContext, StoredCoversDatabase::class.java, "stored_covers.db")
.fallbackToDestructiveMigration()
.build()
}
@@ -1,57 +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.auxio.musikr.cover
import org.oxycblt.auxio.list.sort.Sort
import org.oxycblt.auxio.music.Song
sealed interface Cover {
val key: String
data class Single(val song: Song) : Cover {
override val key: String
get() = "${song.uid}@${song.lastModified}"
val uid = song.uid
val uri = song.uri
val lastModified = song.lastModified
}
class Multi(val all: List<Single>) : Cover {
override val key = "multi@${all.hashCode()}"
}
companion object {
private val FALLBACK_SORT = Sort(Sort.Mode.ByAlbum, Sort.Direction.ASCENDING)
fun nil() = Multi(listOf())
fun single(song: Song) = Single(song)
fun multi(songs: Collection<Song>) = order(songs).run { Multi(this) }
private fun order(songs: Collection<Song>) =
FALLBACK_SORT.songs(songs)
.map { it.cover }
.groupBy { it.key }
.entries
.sortedByDescending { it.value.size }
.map { it.value.first() }
}
}
@@ -1,50 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* CoverCache.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.auxio.musikr.cover
import java.io.InputStream
import javax.inject.Inject
interface CoverCache {
suspend fun read(cover: Cover.Single): InputStream?
suspend fun write(cover: Cover.Single, data: ByteArray): InputStream?
}
class CoverCacheImpl
@Inject
constructor(
private val coverIdentifier: CoverIdentifier,
private val storedCoversDao: StoredCoversDao,
private val coverFiles: CoverFiles
) : CoverCache {
override suspend fun read(cover: Cover.Single): InputStream? {
val id = storedCoversDao.getStoredCoverId(cover.uid, cover.lastModified) ?: return null
return coverFiles.read(id)
}
override suspend fun write(cover: Cover.Single, data: ByteArray): InputStream? {
val id = coverIdentifier.identify(data)
coverFiles.write(id, data)
storedCoversDao.setStoredCover(
StoredCover(uid = cover.uid, lastModified = cover.lastModified, coverId = id))
return coverFiles.read(id)
}
}
@@ -1,85 +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.auxio.musikr.cover
import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.File
import java.io.IOException
import java.io.InputStream
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
interface CoverFiles {
suspend fun read(id: String): InputStream?
suspend fun write(id: String, data: ByteArray)
}
class CoverFilesImpl
@Inject
constructor(
@ApplicationContext private val context: Context,
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 {
context.openFileInput(getTargetFilePath(id))
} catch (e: IOException) {
null
}
}
override suspend fun write(id: String, data: ByteArray) {
val fileMutex = getMutexForFile(id)
fileMutex.withLock {
val targetFile = File(context.filesDir, getTargetFilePath(id))
if (targetFile.exists()) {
return
}
withContext(Dispatchers.IO) {
val tempFile = File(context.filesDir, 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,72 +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.auxio.musikr.cover
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import java.io.OutputStream
import javax.inject.Inject
interface CoverFormat {
val extension: String
fun transcodeInto(data: ByteArray, output: OutputStream): Boolean
}
class CoverFormatImpl @Inject constructor() : 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,38 +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.auxio.musikr.cover
import java.security.MessageDigest
import javax.inject.Inject
interface CoverIdentifier {
suspend fun identify(data: ByteArray): String
}
class CoverIdentifierImpl @Inject constructor() : CoverIdentifier {
@OptIn(ExperimentalStdlibApi::class)
override suspend fun identify(data: ByteArray): String {
val digest =
MessageDigest.getInstance("MD5").run {
update(data)
digest()
}
return digest.toHexString()
}
}
@@ -1,49 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* StoredCoversDatabase.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.auxio.musikr.cover
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.RoomDatabase
import androidx.room.TypeConverters
import org.oxycblt.auxio.music.Music
@Database(entities = [StoredCover::class], version = 50, exportSchema = false)
abstract class StoredCoversDatabase : RoomDatabase() {
abstract fun storedCoversDao(): StoredCoversDao
}
@Dao
interface StoredCoversDao {
@Query("SELECT coverId FROM StoredCover WHERE uid = :uid AND lastModified = :lastModified")
@TypeConverters(Music.UID.TypeConverters::class)
suspend fun getStoredCoverId(uid: Music.UID, lastModified: Long): String?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun setStoredCover(storedCover: StoredCover)
}
@Entity
@TypeConverters(Music.UID.TypeConverters::class)
data class StoredCover(@PrimaryKey val uid: Music.UID, val lastModified: Long, val coverId: String)
@@ -1,124 +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.auxio.musikr.fs
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
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.auxio.musikr.fs.path.DocumentPathFactory
import timber.log.Timber
interface DeviceFiles {
fun explore(uris: Flow<Uri>): Flow<DeviceFile>
}
data class DeviceFile(
val uri: Uri,
val mimeType: String,
val path: Path,
val size: Long,
val lastModified: Long
)
@OptIn(ExperimentalCoroutinesApi::class)
class DeviceFilesImpl
@Inject
constructor(
@ApplicationContext private val context: Context,
private val documentPathFactory: DocumentPathFactory
) : DeviceFiles {
private val contentResolver = context.contentResolverSafe
override fun explore(uris: Flow<Uri>): Flow<DeviceFile> =
uris.flatMapMerge { rootUri ->
Timber.d("$rootUri")
exploreImpl(
contentResolver,
rootUri,
DocumentsContract.getTreeDocumentId(rootUri),
requireNotNull(documentPathFactory.unpackDocumentTreeUri(rootUri)))
}
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,319 +0,0 @@
/*
* Copyright (c) 2022 Auxio Project
* Fs.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.auxio.musikr.fs
import android.content.Context
import android.media.MediaFormat
import android.os.storage.StorageManager
import android.os.storage.StorageVolume
import android.webkit.MimeTypeMap
import java.io.File
import javax.inject.Inject
import org.oxycblt.auxio.R
/**
* 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)
}
}
/** 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>
}
class VolumeManagerImpl @Inject constructor(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)
}
}
/**
* A mime type of a file. Only intended for display.
*
* @param fromExtension The mime type obtained by analyzing the file extension.
* @param fromFormat The mime type obtained by analyzing the file format. Null if could not be
* obtained.
* @author Alexander Capehart (OxygenCobalt)
*
* TODO: Get around to simplifying this
*/
data class MimeType(val fromExtension: String, val fromFormat: String?) {
/**
* Resolve the mime type into a human-readable format name, such as "Ogg Vorbis".
*
* @param context [Context] required to obtain human-readable strings.
* @return A human-readable name for this mime type. Will first try [fromFormat], then falling
* back to [fromExtension], and then null if that fails.
*/
fun resolveName(context: Context): String? {
// We try our best to produce a more readable name for the common audio formats.
val formatName =
when (fromFormat) {
// We start with the extracted mime types, as they are more consistent. Note that
// we do not include container formats at all with these names. It is only the
// inner codec that we bother with.
MediaFormat.MIMETYPE_AUDIO_MPEG -> R.string.cdc_mp3
MediaFormat.MIMETYPE_AUDIO_AAC -> R.string.cdc_aac
MediaFormat.MIMETYPE_AUDIO_VORBIS -> R.string.cdc_vorbis
MediaFormat.MIMETYPE_AUDIO_OPUS -> R.string.cdc_opus
MediaFormat.MIMETYPE_AUDIO_FLAC -> R.string.cdc_flac
// TODO: Add ALAC to this as soon as I can stop using MediaFormat for
// extracting metadata and just use ExoPlayer.
// We don't give a name to more unpopular formats.
else -> -1
}
if (formatName > -1) {
return context.getString(formatName)
}
// Fall back to the file extension in the case that we have no mime type or
// a useless "audio/raw" mime type. Here:
// - We return names for container formats instead of the inner format, as we
// cannot parse the file.
// - We are at the mercy of the Android OS, hence we check for every possible mime
// type for a particular format according to Wikipedia.
val extensionName =
when (fromExtension) {
"audio/mpeg",
"audio/mp3" -> R.string.cdc_mp3
"audio/mp4",
"audio/mp4a-latm",
"audio/mpeg4-generic" -> R.string.cdc_mp4
"audio/aac",
"audio/aacp",
"audio/3gpp",
"audio/3gpp2" -> R.string.cdc_aac
"audio/ogg",
"application/ogg",
"application/x-ogg" -> R.string.cdc_ogg
"audio/flac" -> R.string.cdc_flac
"audio/wav",
"audio/x-wav",
"audio/wave",
"audio/vnd.wave" -> R.string.cdc_wav
"audio/x-matroska" -> R.string.cdc_mka
else -> -1
}
return if (extensionName > -1) {
context.getString(extensionName)
} else {
// Fall back to the extension if we can't find a special name for this format.
MimeTypeMap.getSingleton().getExtensionFromMimeType(fromExtension)?.uppercase()
}
}
}
@@ -1,59 +0,0 @@
/*
* Copyright (c) 2023 Auxio Project
* FsModule.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.auxio.musikr.fs
import android.content.ContentResolver
import android.content.Context
import android.os.storage.StorageManager
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import org.oxycblt.auxio.musikr.fs.path.DocumentPathFactory
import org.oxycblt.auxio.musikr.fs.path.DocumentPathFactoryImpl
import org.oxycblt.auxio.musikr.fs.path.MediaStorePathInterpreter
import org.oxycblt.auxio.util.getSystemServiceCompat
@Module
@InstallIn(SingletonComponent::class)
class FsModule {
@Provides
fun volumeManager(@ApplicationContext context: Context): VolumeManager =
VolumeManagerImpl(context.getSystemServiceCompat(StorageManager::class))
@Provides
fun mediaStorePathInterpreterFactory(
volumeManager: VolumeManager
): MediaStorePathInterpreter.Factory = MediaStorePathInterpreter.Factory.from(volumeManager)
@Provides
fun contentResolver(@ApplicationContext context: Context): ContentResolver =
context.contentResolverSafe
}
@Module
@InstallIn(SingletonComponent::class)
interface FsBindsModule {
@Binds
fun documentPathFactory(documentTreePathFactory: DocumentPathFactoryImpl): DocumentPathFactory
@Binds fun deviceFiles(deviceFilesImpl: DeviceFilesImpl): DeviceFiles
}
@@ -1,242 +0,0 @@
/*
* Copyright (c) 2022 Auxio Project
* StorageUtil.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.auxio.musikr.fs
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
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.auxio.util.lazyReflectedMethod
// --- MEDIASTORE UTILITIES ---
/**
* 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)
inline fun <reified R> ContentResolver.mapQuery(
uri: Uri,
projection: Array<out String>,
selector: String? = null,
args: Array<String>? = null,
crossinline transform: Cursor.() -> R
) =
useQuery(uri, projection, selector, args) {
sequence<R> {
while (it.moveToNext()) {
yield(it.transform())
}
}
}
/** Album art [MediaStore] database is not a built-in constant, have to define it ourselves. */
private val externalCoversUri = Uri.parse("content://media/external/audio/albumart")
/**
* Convert a [MediaStore] Song ID into a [Uri] to it's audio file.
*
* @return An external storage audio file [Uri]. May not exist.
* @see ContentUris.withAppendedId
* @see MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
*/
fun Long.toAudioUri() =
ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, this)
/**
* Convert a [MediaStore] Album ID into a [Uri] to it's system-provided album cover. This cover will
* be fast to load, but will be lower quality.
*
* @return An external storage image [Uri]. May not exist.
* @see ContentUris.withAppendedId
*/
fun Long.toSongCoverUri(): Uri =
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.buildUpon().run {
appendPath(this@toSongCoverUri.toString())
appendPath("albumart")
build()
}
fun Long.toAlbumCoverUri(): Uri = ContentUris.withAppendedId(externalCoversUri, this)
// --- STORAGEMANAGER UTILITIES ---
// 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,153 +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.auxio.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 javax.inject.Inject
import org.oxycblt.auxio.musikr.fs.Components
import org.oxycblt.auxio.musikr.fs.Path
import org.oxycblt.auxio.musikr.fs.Volume
import org.oxycblt.auxio.musikr.fs.VolumeManager
import org.oxycblt.auxio.musikr.fs.contentResolverSafe
import org.oxycblt.auxio.musikr.fs.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?
}
class DocumentPathFactoryImpl
@Inject
constructor(
@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,248 +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.auxio.musikr.fs.path
import android.database.Cursor
import android.os.Build
import android.provider.MediaStore
import org.oxycblt.auxio.musikr.fs.Components
import org.oxycblt.auxio.musikr.fs.Path
import org.oxycblt.auxio.musikr.fs.VolumeManager
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,30 +0,0 @@
/*
* Copyright (c) 2023 Auxio Project
* GraphModule.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.auxio.musikr.graph
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface GraphModule {
@Binds fun musicGraphFactory(interpreter: MusicGraphFactoryImpl): MusicGraph.Factory
}
@@ -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.auxio.musikr.graph
import javax.inject.Inject
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.musikr.tag.interpret.PreAlbum
import org.oxycblt.auxio.musikr.tag.interpret.PreArtist
import org.oxycblt.auxio.musikr.tag.interpret.PreGenre
import org.oxycblt.auxio.musikr.tag.interpret.PreSong
import org.oxycblt.auxio.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
}
interface Factory {
fun builder(): Builder
}
}
class MusicGraphFactoryImpl @Inject constructor() : MusicGraph.Factory {
override fun builder(): MusicGraph.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 and albums 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
}
// 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,27 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* AudioMetadata.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.auxio.musikr.metadata
import android.media.MediaMetadataRetriever
import androidx.media3.common.Format
data class AudioMetadata(
val exoPlayerFormat: Format?,
val mediaMetadataRetriever: MediaMetadataRetriever
)
@@ -1,124 +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.auxio.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.auxio.music.Song
import org.oxycblt.auxio.musikr.fs.MimeType
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.
* @param resolvedMimeType The known mime type of the [Song] after it's file format was determined.
* @author Alexander Capehart (OxygenCobalt)
*/
data class AudioProperties(
val bitrateKbps: Int?,
val sampleRateHz: Int?,
val resolvedMimeType: MimeType
) {
/** 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, song.mimeType)
}
// 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
}
// The song's mime type won't have a populated format field right now, try to
// extract it ourselves.
val formatMimeType =
try {
format.getString(MediaFormat.KEY_MIME)
} catch (e: NullPointerException) {
L.e("Unable to extract mime type field")
null
}
extractor.release()
L.d("Finished extracting audio properties")
return AudioProperties(
bitrate,
sampleRate,
MimeType(fromExtension = song.mimeType.fromExtension, fromFormat = formatMimeType))
}
}
@@ -1,61 +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.auxio.musikr.metadata
import android.content.Context
import android.media.MediaMetadataRetriever
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.MetadataRetriever
import androidx.media3.exoplayer.source.MediaSource
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.guava.await
import kotlinx.coroutines.withContext
import org.oxycblt.auxio.musikr.fs.DeviceFile
interface MetadataExtractor {
suspend fun extract(file: DeviceFile): AudioMetadata
}
class MetadataExtractorImpl
@Inject
constructor(
@ApplicationContext private val context: Context,
private val mediaSourceFactory: MediaSource.Factory
) : MetadataExtractor {
override suspend fun extract(file: DeviceFile): AudioMetadata {
val exoPlayerMetadataFuture =
MetadataRetriever.retrieveMetadata(mediaSourceFactory, MediaItem.fromUri(file.uri))
val mediaMetadataRetriever =
MediaMetadataRetriever().apply {
withContext(Dispatchers.IO) { setDataSource(context, file.uri) }
}
val trackGroupArray = exoPlayerMetadataFuture.await()
if (trackGroupArray.isEmpty) {
return AudioMetadata(null, mediaMetadataRetriever)
}
val trackGroup = trackGroupArray.get(0)
if (trackGroup.length == 0) {
return AudioMetadata(null, mediaMetadataRetriever)
}
val format = trackGroup.getFormat(0)
return AudioMetadata(format, mediaMetadataRetriever)
}
}
@@ -1,33 +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.auxio.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
@Binds fun metadataExtractor(extractor: MetadataExtractorImpl): MetadataExtractor
}
@@ -1,198 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* ReusableMetadataRetriever.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.auxio.musikr.metadata
import android.os.Handler
import android.os.HandlerThread
import android.os.Message
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Timeline
import androidx.media3.common.util.Clock
import androidx.media3.common.util.HandlerWrapper
import androidx.media3.exoplayer.LoadingInfo
import androidx.media3.exoplayer.analytics.PlayerId
import androidx.media3.exoplayer.source.MediaPeriod
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.TrackGroupArray
import androidx.media3.exoplayer.upstream.Allocator
import androidx.media3.exoplayer.upstream.DefaultAllocator
import com.google.common.util.concurrent.SettableFuture
import java.util.concurrent.Future
import javax.inject.Inject
import timber.log.Timber
private const val MESSAGE_PREPARE = 0
private const val MESSAGE_CONTINUE_LOADING = 1
private const val MESSAGE_CHECK_FAILURE = 2
private const val MESSAGE_RELEASE = 3
private const val CHECK_INTERVAL_MS = 100
// TODO: Rewrite and re-integrate
interface MetadataRetrieverExt {
fun retrieveMetadata(mediaItem: MediaItem): Future<TrackGroupArray>
fun retrieve()
interface Factory {
fun create(): MetadataRetrieverExt
}
}
class ReusableMetadataRetrieverImpl
@Inject
constructor(private val mediaSourceFactory: MediaSource.Factory) :
MetadataRetrieverExt, Handler.Callback {
private val mediaSourceThread = HandlerThread("Auxio:ChunkedMetadataRetriever:${hashCode()}")
private val mediaSourceHandler: HandlerWrapper
private var job: MetadataJob? = null
private data class JobParams(
val mediaItem: MediaItem,
val future: SettableFuture<TrackGroupArray>
)
private class JobData(
val params: JobParams,
val mediaSource: MediaSource,
var mediaPeriod: MediaPeriod?,
)
private class MetadataJob(val data: JobData, val mediaSourceCaller: MediaSourceCaller)
init {
mediaSourceThread.start()
mediaSourceHandler = Clock.DEFAULT.createHandler(mediaSourceThread.looper, this)
}
override fun retrieveMetadata(mediaItem: MediaItem): Future<TrackGroupArray> {
val job = job
check(job == null || job.data.params.future.isDone) { "Already working on something: $job" }
val future = SettableFuture.create<TrackGroupArray>()
mediaSourceHandler
.obtainMessage(MESSAGE_PREPARE, JobParams(mediaItem, future))
.sendToTarget()
return future
}
override fun retrieve() {
mediaSourceHandler.removeCallbacksAndMessages(null)
mediaSourceThread.quit()
}
override fun handleMessage(msg: Message): Boolean {
when (msg.what) {
MESSAGE_PREPARE -> {
val params = msg.obj as JobParams
val mediaSource = mediaSourceFactory.createMediaSource(params.mediaItem)
val data = JobData(params, mediaSource, null)
val mediaSourceCaller = MediaSourceCaller(data)
mediaSource.prepareSource(
mediaSourceCaller, /* mediaTransferListener= */ null, PlayerId.UNSET)
job = MetadataJob(data, mediaSourceCaller)
mediaSourceHandler.sendEmptyMessageDelayed(
MESSAGE_CHECK_FAILURE, /* delayMs= */ CHECK_INTERVAL_MS)
return true
}
MESSAGE_CONTINUE_LOADING -> {
val job = job ?: return true
checkNotNull(job.data.mediaPeriod)
.continueLoading(LoadingInfo.Builder().setPlaybackPositionUs(0).build())
return true
}
MESSAGE_CHECK_FAILURE -> {
val job = job ?: return true
val mediaPeriod = job.data.mediaPeriod
val mediaSource = job.data.mediaSource
val mediaSourceCaller = job.mediaSourceCaller
try {
if (mediaPeriod == null) {
mediaSource.maybeThrowSourceInfoRefreshError()
} else {
mediaPeriod.maybeThrowPrepareError()
}
} catch (e: Exception) {
Timber.e("Failed to extract MediaSource")
Timber.e(e.stackTraceToString())
mediaPeriod?.let(mediaSource::releasePeriod)
mediaSource.releaseSource(mediaSourceCaller)
job.data.params.future.setException(e)
}
return true
}
MESSAGE_RELEASE -> {
val job = job ?: return true
val mediaPeriod = job.data.mediaPeriod
val mediaSource = job.data.mediaSource
val mediaSourceCaller = job.mediaSourceCaller
mediaPeriod?.let { mediaSource.releasePeriod(it) }
mediaSource.releaseSource(mediaSourceCaller)
this.job = null
return true
}
else -> return false
}
}
private inner class MediaSourceCaller(private val data: JobData) :
MediaSource.MediaSourceCaller {
private val mediaPeriodCallback: MediaPeriodCallback =
MediaPeriodCallback(data.params.future)
private val allocator: Allocator =
DefaultAllocator(
/* trimOnReset= */ true,
/* individualAllocationSize= */ C.DEFAULT_BUFFER_SEGMENT_SIZE)
private var mediaPeriodCreated = false
override fun onSourceInfoRefreshed(source: MediaSource, timeline: Timeline) {
if (mediaPeriodCreated) {
// Ignore dynamic updates.
return
}
mediaPeriodCreated = true
val mediaPeriod =
source.createPeriod(
MediaSource.MediaPeriodId(timeline.getUidOfPeriod(/* periodIndex= */ 0)),
allocator,
/* startPositionUs= */ 0)
data.mediaPeriod = mediaPeriod
mediaPeriod.prepare(mediaPeriodCallback, /* positionUs= */ 0)
}
private inner class MediaPeriodCallback(
private val future: SettableFuture<TrackGroupArray>
) : MediaPeriod.Callback {
override fun onPrepared(mediaPeriod: MediaPeriod) {
future.set(mediaPeriod.getTrackGroups())
mediaSourceHandler.sendEmptyMessage(MESSAGE_RELEASE)
}
@Override
override fun onContinueLoadingRequested(source: MediaPeriod) {
mediaSourceHandler.sendEmptyMessage(MESSAGE_CONTINUE_LOADING)
}
}
}
}
@@ -1,210 +0,0 @@
/*
* Copyright (c) 2023 Auxio Project
* DeviceMusicImpl.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.auxio.musikr.model
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.cover.Cover
import org.oxycblt.auxio.musikr.tag.Date
import org.oxycblt.auxio.musikr.tag.interpret.PreAlbum
import org.oxycblt.auxio.musikr.tag.interpret.PreArtist
import org.oxycblt.auxio.musikr.tag.interpret.PreGenre
import org.oxycblt.auxio.musikr.tag.interpret.PreSong
import org.oxycblt.auxio.util.update
interface SongHandle {
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: SongHandle) : 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 mimeType = preSong.mimeType
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 = Cover.single(this)
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)"
}
interface AlbumHandle {
val preAlbum: PreAlbum
val songs: List<Song>
fun resolveArtists(): List<Artist>
}
/**
* Library-backed implementation of [Album].
*
* @author Alexander Capehart (OxygenCobalt)
*/
class AlbumImpl(private val handle: AlbumHandle) : Album {
private val preAlbum = handle.preAlbum
override val uid =
// Attempt to use a MusicBrainz ID first before falling back to a hashed UID.
preAlbum.musicBrainzId?.let { Music.UID.musicBrainz(MusicType.ALBUMS, it) }
?: Music.UID.auxio(MusicType.ALBUMS) {
// 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 = handle.songs.sumOf { it.durationMs }
override val dateAdded = handle.songs.minOf { it.dateAdded }
override val cover = Cover.multi(handle.songs)
override val dates: Date.Range? =
handle.songs.mapNotNull { it.date }.ifEmpty { null }?.run { Date.Range(min(), max()) }
override val artists: List<Artist>
get() = handle.resolveArtists()
override val songs = handle.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)"
}
interface ArtistHandle {
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 handle: ArtistHandle) : Artist {
override val uid =
// Attempt to use a MusicBrainz ID first before falling back to a hashed UID.
handle.preArtist.musicBrainzId?.let { Music.UID.musicBrainz(MusicType.ARTISTS, it) }
?: Music.UID.auxio(MusicType.ARTISTS) { update(handle.preArtist.rawName) }
override val name = handle.preArtist.name
override val songs = handle.songs
override var explicitAlbums = handle.albums
override var implicitAlbums = handle.songs.mapTo(mutableSetOf()) { it.album } - handle.albums
override val genres: List<Genre>
get() = handle.resolveGenres().toList()
override val durationMs = handle.songs.sumOf { it.durationMs }
override val cover = Cover.multi(handle.songs)
private val hashCode =
31 * (31 * uid.hashCode() + handle.preArtist.hashCode()) * handle.songs.hashCode()
override fun hashCode() = hashCode
override fun equals(other: Any?) =
other is ArtistImpl &&
uid == other.uid &&
handle.preArtist == other.handle.preArtist &&
songs == other.songs
override fun toString() = "Artist(uid=$uid, name=$name)"
}
interface GenreHandle {
val preGenre: PreGenre
val songs: Set<Song>
val artists: Set<Artist>
}
/**
* Library-backed implementation of [Genre].
*
* @author Alexander Capehart (OxygenCobalt)
*/
class GenreImpl(private val handle: GenreHandle) : Genre {
override val uid = Music.UID.auxio(MusicType.GENRES) { update(handle.preGenre.rawName) }
override val name = handle.preGenre.name
override val songs = mutableSetOf<Song>()
override val artists = mutableSetOf<Artist>()
override val durationMs = handle.songs.sumOf { it.durationMs }
override val cover = Cover.multi(handle.songs)
private val hashCode =
31 * (31 * uid.hashCode() + handle.preGenre.hashCode()) + songs.hashCode()
override fun hashCode() = hashCode
override fun equals(other: Any?) =
other is GenreImpl &&
uid == other.uid &&
handle.preGenre == other.handle.preGenre &&
songs == other.songs
override fun toString() = "Genre(uid=$uid, name=$name)"
}
@@ -1,158 +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.auxio.musikr.model
import javax.inject.Inject
import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Library
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.fs.Path
import org.oxycblt.auxio.musikr.graph.AlbumVertex
import org.oxycblt.auxio.musikr.graph.ArtistVertex
import org.oxycblt.auxio.musikr.graph.GenreVertex
import org.oxycblt.auxio.musikr.graph.MusicGraph
import org.oxycblt.auxio.musikr.graph.SongVertex
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
}
interface LibraryFactory {
fun create(graph: MusicGraph): MutableLibrary
}
class LibraryFactoryImpl @Inject constructor() : LibraryFactory {
override fun create(graph: MusicGraph): MutableLibrary {
val songs =
graph.songVertex.mapTo(mutableSetOf()) { vertex ->
SongImpl(SongVertexHandle(vertex)).also { vertex.tag = it }
}
val albums =
graph.albumVertex.mapTo(mutableSetOf()) { vertex ->
AlbumImpl(AlbumVertexHandle(vertex)).also { vertex.tag = it }
}
val artists =
graph.artistVertex.mapTo(mutableSetOf()) { vertex ->
ArtistImpl(ArtistVertexHandle(vertex)).also { vertex.tag = it }
}
val genres =
graph.genreVertex.mapTo(mutableSetOf()) { vertex ->
GenreImpl(GenreVertexHandle(vertex)).also { vertex.tag = it }
}
return LibraryImpl(songs, albums, artists, genres)
}
private class SongVertexHandle(private val vertex: SongVertex) : SongHandle {
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 AlbumVertexHandle(private val vertex: AlbumVertex) : AlbumHandle {
override val preAlbum = vertex.preAlbum
override val songs = vertex.songVertices.map { SongImpl(SongVertexHandle(it)) }
override fun resolveArtists() = vertex.artistVertices.map { it.tag as Artist }
}
private class ArtistVertexHandle(private val vertex: ArtistVertex) : ArtistHandle {
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 GenreVertexHandle(vertex: GenreVertex) : GenreHandle {
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 }
}
}
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,30 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* ModelModule.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.auxio.musikr.model
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface ModelModule {
@Binds fun libraryFactory(factory: LibraryFactoryImpl): LibraryFactory
}
@@ -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.auxio.musikr.model
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.musikr.cover.Cover
import org.oxycblt.auxio.musikr.playlist.PlaylistHandle
import org.oxycblt.auxio.musikr.tag.Name
import org.oxycblt.auxio.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,65 +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.auxio.musikr.pipeline
import javax.inject.Inject
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.auxio.music.Song
import org.oxycblt.auxio.musikr.graph.MusicGraph
import org.oxycblt.auxio.musikr.model.LibraryFactory
import org.oxycblt.auxio.musikr.model.MutableLibrary
import org.oxycblt.auxio.musikr.tag.Interpretation
import org.oxycblt.auxio.musikr.tag.interpret.TagInterpreter
interface EvaluateStep {
suspend fun evaluate(
interpretation: Interpretation,
extractedMusic: Flow<ExtractedMusic>
): MutableLibrary
}
class EvaluateStepImpl
@Inject
constructor(
private val tagInterpreter: TagInterpreter,
private val musicGraphFactory: MusicGraph.Factory,
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.file, it.tags, interpretation) }
.flowOn(Dispatchers.Main)
.buffer(Channel.UNLIMITED)
val graphBuilder = musicGraphFactory.builder()
preSongs.collect { graphBuilder.add(it) }
val graph = graphBuilder.build()
return libraryFactory.create(graph)
}
}
@@ -1,52 +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.auxio.musikr.pipeline
import android.net.Uri
import javax.inject.Inject
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.auxio.musikr.fs.DeviceFile
import org.oxycblt.auxio.musikr.fs.DeviceFiles
import org.oxycblt.auxio.musikr.playlist.m3u.M3U
interface ExploreStep {
fun explore(uris: List<Uri>): Flow<ExploreNode>
}
class ExploreStepImpl @Inject constructor(private val deviceFiles: DeviceFiles) : ExploreStep {
override fun explore(uris: List<Uri>) =
deviceFiles
.explore(uris.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,85 +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.auxio.musikr.pipeline
import javax.inject.Inject
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.merge
import org.oxycblt.auxio.musikr.fs.DeviceFile
import org.oxycblt.auxio.musikr.metadata.MetadataExtractor
import org.oxycblt.auxio.musikr.tag.cache.TagCache
import org.oxycblt.auxio.musikr.tag.parse.ParsedTags
import org.oxycblt.auxio.musikr.tag.parse.TagParser
interface ExtractStep {
fun extract(nodes: Flow<ExploreNode>): Flow<ExtractedMusic>
}
class ExtractStepImpl
@Inject
constructor(
private val tagCache: TagCache,
private val metadataExtractor: MetadataExtractor,
private val tagParser: TagParser
) : ExtractStep {
override fun extract(nodes: Flow<ExploreNode>): Flow<ExtractedMusic> {
val cacheResults =
nodes
.filterIsInstance<ExploreNode.Audio>()
.map {
val tags = tagCache.read(it.file)
MaybeCachedSong(it.file, tags)
}
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED)
val (cachedSongs, uncachedSongs) =
cacheResults.mapPartition {
it.tags?.let { tags -> ExtractedMusic.Song(it.file, tags) }
}
val split = uncachedSongs.distribute(8)
val extractedSongs =
Array(split.hot.size) { i ->
split.hot[i]
.map {
val metadata = metadataExtractor.extract(it.file)
val tags = tagParser.parse(it.file, metadata)
ExtractedMusic.Song(it.file, tags)
}
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED)
}
return merge<ExtractedMusic>(
cachedSongs,
split.cold,
*extractedSongs,
)
}
data class MaybeCachedSong(val file: DeviceFile, val tags: ParsedTags?)
}
sealed interface ExtractedMusic {
data class Song(val file: DeviceFile, val tags: ParsedTags) : ExtractedMusic
}
@@ -1,67 +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.auxio.musikr.pipeline
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.withIndex
data class HotCold<H, C>(val hot: H, val cold: Flow<C>)
inline fun <T, R> Flow<T>.mapPartition(crossinline predicate: (T) -> R?): HotCold<Flow<R>, T> {
val passChannel = Channel<R>(Channel.UNLIMITED)
val passFlow = passChannel.consumeAsFlow()
val failFlow = flow {
collect {
val result = predicate(it)
if (result != null) {
passChannel.send(result)
} else {
emit(it)
}
}
}
return HotCold(passFlow, failFlow)
}
/**
* 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): HotCold<Array<Flow<T>>, Nothing> {
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 HotCold(hotFlows, managerFlow)
}
@@ -1,34 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* PipelineModule.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.auxio.musikr.pipeline
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface InterpretModule {
@Binds fun exploreStep(step: ExploreStepImpl): ExploreStep
@Binds fun extractStep(step: ExtractStepImpl): ExtractStep
@Binds fun evaluateStep(step: EvaluateStepImpl): EvaluateStep
}
@@ -1,140 +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.auxio.musikr.playlist
import android.content.Context
import android.net.Uri
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.musikr.fs.Components
import org.oxycblt.auxio.musikr.fs.Path
import org.oxycblt.auxio.musikr.fs.contentResolverSafe
import org.oxycblt.auxio.musikr.fs.path.DocumentPathFactory
import org.oxycblt.auxio.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
}
/**
* 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
@Inject
constructor(
@ApplicationContext 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.auxio.musikr.playlist
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.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,33 +0,0 @@
/*
* Copyright (c) 2023 Auxio Project
* PlaylistModule.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.auxio.musikr.playlist
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface PlaylistModule {
@Binds
fun externalPlaylistManager(
externalPlaylistManager: ExternalPlaylistManagerImpl
): ExternalPlaylistManager
}
@@ -1,149 +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.auxio.musikr.playlist.db
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.RoomDatabase
import androidx.room.Transaction
import androidx.room.TypeConverters
import org.oxycblt.auxio.music.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() {
abstract fun playlistDao(): PlaylistDao
}
// 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
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.auxio.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.auxio.music.Music
/**
* Raw playlist information persisted to [PlaylistDatabase].
*
* @author Alexander Capehart (OxygenCobalt)
*/
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 data class PlaylistInfo(@PrimaryKey val playlistUid: Music.UID, val name: String)
/**
* Song information corresponding to a [RawPlaylist] entry.
*
* @author Alexander Capehart (OxygenCobalt)
*/
@Entity data class PlaylistSong(@PrimaryKey val songUid: Music.UID)
/**
* Links individual songs to a playlist entry.
*
* @author Alexander Capehart (OxygenCobalt)
*/
@Entity
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,36 +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.auxio.musikr.playlist.db
import javax.inject.Inject
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.auxio.musikr.playlist.PlaylistFile
interface StoredPlaylists {
fun read(): Flow<PlaylistFile>
}
class StoredPlaylistsImpl @Inject constructor(private val playlistDao: PlaylistDao) :
StoredPlaylists {
override fun read() = flow { emitAll(playlistDao.readRawPlaylists().asFlow().map { TODO() }) }
}
@@ -1,47 +0,0 @@
/*
* Copyright (c) 2023 Auxio Project
* UserModule.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.auxio.musikr.playlist.db
import android.content.Context
import androidx.room.Room
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface PlaylistModule {
@Binds fun storedPlaylists(impl: StoredPlaylistsImpl): StoredPlaylists
}
@Module
@InstallIn(SingletonComponent::class)
class PlaylistRoomModule {
@Provides fun playlistDao(database: PlaylistDatabase) = database.playlistDao()
@Provides
fun playlistDatabase(@ApplicationContext context: Context) =
Room.databaseBuilder(
context.applicationContext, PlaylistDatabase::class.java, "user_music.db")
.fallbackToDestructiveMigration()
.build()
}
@@ -1,291 +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.auxio.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 javax.inject.Inject
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.auxio.musikr.fs.Components
import org.oxycblt.auxio.musikr.fs.Path
import org.oxycblt.auxio.musikr.fs.Volume
import org.oxycblt.auxio.musikr.fs.VolumeManager
import org.oxycblt.auxio.musikr.playlist.ExportConfig
import org.oxycblt.auxio.musikr.playlist.ImportedPlaylist
import org.oxycblt.auxio.musikr.playlist.PossiblePaths
import org.oxycblt.auxio.musikr.tag.util.correctWhitespace
import org.oxycblt.auxio.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"
}
}
class M3UImpl
@Inject
constructor(
@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.resolve(context)}")
for (song in playlist.songs) {
writer.writeLine("#EXTINF:${song.durationMs},${song.name.resolve(context)}")
writer.writeLine("#EXTALB:${song.album.name.resolve(context)}")
writer.writeLine("#EXTART:${song.artists.resolveNames(context)}")
writer.writeLine("#EXTGEN:${song.genres.resolveNames(context)}")
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,30 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* M3UModule.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.auxio.musikr.playlist.m3u
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface PlaylistModule {
@Binds fun m3u(m3u: M3UImpl): M3U
}
@@ -1,261 +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.auxio.musikr.tag
import android.content.Context
import java.text.ParseException
import java.text.SimpleDateFormat
import kotlin.math.max
import org.oxycblt.auxio.R
import org.oxycblt.auxio.util.inRangeOrNull
import org.oxycblt.auxio.util.positiveOrNull
import timber.log.Timber as L
/**
* 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]
private val month = tokens.getOrNull(1)
private val day = tokens.getOrNull(2)
private val hour = tokens.getOrNull(3)
private val minute = tokens.getOrNull(4)
private val second = tokens.getOrNull(5)
/**
* Resolve this instance into a human-readable date.
*
* @param context [Context] required to get human-readable names.
* @return If the [Date] has a valid month and year value, a more fine-grained date (ex. "Jan
* 2020") will be returned. Otherwise, a plain year value (ex. "2020") is returned. Dates will
* be properly localized.
*/
fun resolve(context: Context) =
// Unable to create fine-grained date, just format as a year.
month?.let { resolveFineGrained() } ?: context.getString(R.string.fmt_number, year)
private fun resolveFineGrained(): String? {
// We can't directly load a date with our own
val format = (SimpleDateFormat.getDateInstance() as SimpleDateFormat)
format.applyPattern("yyyy-MM")
val date =
try {
format.parse("$year-$month")
} catch (e: ParseException) {
L.e("Unable to parse fine-grained date: $e")
return null
}
// Reformat as a readable month and year
format.applyPattern("MMM yyyy")
return format.format(date)
}
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" }
}
/**
* Resolve this instance into a human-readable date range.
*
* @param context [Context] required to get human-readable names.
* @return If the date has a maximum value, then a `min - max` formatted string will be
* returned with the formatted [Date]s of the minimum and maximum dates respectively.
* Otherwise, the formatted name of the minimum [Date] will be returned.
*/
fun resolveDate(context: Context) =
if (min != max) {
context.getString(
R.string.fmt_date_range, min.resolve(context), max.resolve(context))
} else {
min.resolve(context)
}
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)
}
}
}

Some files were not shown because too many files have changed in this diff Show More