all: cleanup code issues

This commit is contained in:
Alexander Capehart
2026-08-29 17:15:48 -06:00
parent 46caecec6a
commit 0c4dc21e02
60 changed files with 380 additions and 615 deletions
@@ -19,7 +19,6 @@
package org.oxycblt.musikr
import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
@@ -115,7 +114,6 @@ private class MusikrImpl(
) : Musikr {
override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope {
onProgress(IndexingProgress.Songs(0, 0))
val start = System.currentTimeMillis()
var explored = 0
var loaded = 0
val exploredChannel = Channel<Explored>(Channel.UNLIMITED)
@@ -143,7 +141,6 @@ private class MusikrImpl(
}
val library = evaluateStep.evaluate(trackedExtractedChannel)
merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await()
Log.d("Musikr", "Indexing took ${System.currentTimeMillis() - start}ms")
LibraryResultImpl(config, library)
}
}
@@ -43,7 +43,7 @@ interface CoverIdentifier {
}
}
private class MD5CoverIdentifier() : CoverIdentifier {
private class MD5CoverIdentifier : CoverIdentifier {
@OptIn(ExperimentalStdlibApi::class)
override suspend fun identify(data: ByteArray): String {
val digest =
@@ -56,7 +56,7 @@ private constructor(
@OptIn(ExperimentalCoroutinesApi::class)
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.IO) {
tryAsyncWith(files, Dispatchers.IO) { _ ->
val projection = BASE_PROJECTION + pathInterpreterFactory.projection
var selector = BASE_SELECTOR
val args = mutableListOf<String>()
@@ -22,6 +22,7 @@ import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import androidx.core.net.toUri
import java.io.File
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
@@ -129,8 +130,8 @@ private class DocumentPathFactoryImpl(
private val POSSIBLE_CONTENT_URI_PREFIXES =
arrayOf(
Uri.parse("content://downloads/public_downloads"),
Uri.parse("content://downloads/my_downloads"),
"content://downloads/public_downloads".toUri(),
"content://downloads/my_downloads".toUri(),
)
}
}
@@ -26,7 +26,7 @@ import android.os.Looper
internal class LocationObserver(
private val context: Context,
private val uri: Uri,
uri: Uri,
private val onUpdate: () -> Unit,
) : ContentObserver(Handler(Looper.getMainLooper())), Runnable {
private val handler = Handler(Looper.getMainLooper())
@@ -285,10 +285,10 @@ private class MusicGraphBuilderImpl : MusicGraph.Builder {
val canon = cluster.maxBy { it.songVertices.size }.preAlbum
val same = cluster.all { it.preAlbum == canon }
if (!same) {
val noMbidPreAlbum = canon
// canon is the no-mbid pre-album
val simpleMbidVertex =
albumVertices.getOrPut(noMbidPreAlbum) {
AlbumVertex(noMbidPreAlbum, mutableListOf())
albumVertices.getOrPut(canon) {
AlbumVertex(canon, mutableListOf())
}
for (album in cluster) {
meldAlbumVertices(album, simpleMbidVertex)
@@ -46,7 +46,7 @@ internal interface LibraryFactory {
}
}
private class LibraryFactoryImpl() : LibraryFactory {
private class LibraryFactoryImpl : LibraryFactory {
override fun create(
graph: MusicGraph,
storedPlaylists: StoredPlaylists,
@@ -19,7 +19,6 @@
package org.oxycblt.musikr.pipeline
import android.content.Context
import android.util.Log
import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.BuildConfig
import org.oxycblt.musikr.Config
@@ -69,7 +68,6 @@ private class EvaluateStepImpl(
if (BuildConfig.DEBUG) {
val fileName = "music_graph_debug.dot"
graph.renderToGraphviz(context, fileName)
val filePath = context.filesDir.resolve(fileName).absolutePath
}
return libraryFactory.create(graph, storedPlaylists, playlistInterpreter)
@@ -18,50 +18,8 @@
package org.oxycblt.musikr.pipeline
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.flattenMerge
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.withIndex
/**
* 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.
*/
@OptIn(ExperimentalCoroutinesApi::class)
internal fun <T, R> Flow<T>.distributedMap(
n: Int,
on: CoroutineContext = Dispatchers.Main,
buffer: Int = Channel.UNLIMITED,
block: suspend (T) -> R,
): Flow<R> {
val posChannels = List(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()
}
}
.buffer()
return (posChannels.map { it.receiveAsFlow() } + managerFlow)
.asFlow()
.map { it.tryMap(block).flowOn(on).buffer(buffer) }
.flattenMerge(concurrency = n + 1)
}
internal fun <T, R> Flow<T>.tryMap(transform: suspend (T) -> R): Flow<R> = flow {
collect { value ->
@@ -72,15 +30,3 @@ internal fun <T, R> Flow<T>.tryMap(transform: suspend (T) -> R): Flow<R> = flow
}
}
}
internal suspend fun <T, A> Flow<T>.tryFold(initial: A, operation: suspend (A, T) -> A): A {
var accumulator = initial
collect { value ->
try {
accumulator = operation(accumulator, value)
} catch (e: Exception) {
throw PipelineException(value, e)
}
}
return accumulator
}
@@ -264,17 +264,17 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
var relativeComponents = Components.parseUnix(".")
// TODO: Simplify this logic
when {
commonIndex == components.size && commonIndex == workingDirectory.components.size -> {
when (commonIndex) {
components.size if commonIndex == workingDirectory.components.size -> {
// The paths are the same. This shouldn't occur.
}
commonIndex == components.size -> {
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 -> {
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))
@@ -91,7 +91,7 @@ private data class IntelligentKnownName(override val raw: String, override val s
// Replace punctuation with spaces to create token boundaries, improving
// sorting of names like "15-9" vs "15-10".
.replace(punctRegex, " ")
.let { if (it.isBlank()) name else it }
.let { it.ifBlank { name } }
.run {
// Strip any english articles like "the" or "an" from the start, as music
// sorting should ignore such when possible.
@@ -316,6 +316,6 @@ private fun Metadata.parseId3v23Date(): Date? {
}
} else {
// Unable to parse month/day, just return a year
return Date.from(year)
Date.from(year)
}
}
@@ -34,14 +34,15 @@ import org.oxycblt.musikr.tag.Date
fun CoroutineScope.tryAsync(
context: CoroutineContext,
block: suspend () -> Unit,
): Deferred<Result<Unit>> = async {
try {
block()
Result.success(Unit)
} catch (e: Throwable) {
Result.failure(e)
): Deferred<Result<Unit>> =
async(context = context) {
try {
block()
Result.success(Unit)
} catch (e: Throwable) {
Result.failure(e)
}
}
}
fun <T> CoroutineScope.tryAsyncWith(
channel: Channel<T>,
@@ -70,7 +71,6 @@ fun <T, R> CoroutineScope.map(
block(item)?.let { output.send(it) }
}
output.close()
Unit
}
}