feat: bootstrap MusicManager with scanner and Subsonic auth

- Gradle/Kotlin/Ktor project on JVM 21 with ShadowJar
- SQLite WAL, Flyway migrations and config-driven users/folders
- deterministic IDs, MP3 tag extraction, cover cache and delta scanner
- OpenSubsonic JSON envelope with token/password authentication
- system endpoints: ping, license, extensions, scan status
This commit is contained in:
TapTap committed 2026-11-13 11:42:57 +00:00
1 parent 961341b449
commit e194badefb
45 files changed
+4079 -126

No files matched your search

@@ -0,0 +1,125 @@
package win.taptap.musicmanager.scanner
import java.nio.file.Files
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.slf4j.LoggerFactory
import win.taptap.musicmanager.config.LibraryConfig
import win.taptap.musicmanager.config.MusicFolder
import win.taptap.musicmanager.db.MediaRepository
/**
* Recursive MP3 scanner with delta updates and orphan cleanup.
*
* Only one scan can run at a time. The file's `(mtime, size)` pair decides whether
* tags need to be re-read; unchanged files are skipped.
*/
class MediaScanner(
private val library: LibraryConfig,
private val coverArtService: CoverArtService,
private val tagExtractor: Mp3TagExtractor = Mp3TagExtractor(),
private val repository: MediaRepository = MediaRepository,
) {
private val log = LoggerFactory.getLogger(MediaScanner::class.java)
private val running = AtomicBoolean(false)
private val status = AtomicReference(ScanStatus(scanning = false, count = 0))
fun status(): ScanStatus = status.get()
/** Starts a scan in [scope]. Returns false when a scan is already running. */
fun start(scope: CoroutineScope): Boolean {
if (!running.compareAndSet(false, true)) return false
status.set(ScanStatus(scanning = true, count = 0))
scope.launch { runScan() }
return true
}
/** Blocking variant for tests and the startup scan. */
fun scanBlocking(): ScanStatus {
check(running.compareAndSet(false, true)) { "A scan is already running" }
status.set(ScanStatus(scanning = true, count = 0))
return runScan()
}
private fun runScan(): ScanStatus {
var count = 0L
val seenSongIds = mutableSetOf<String>()
var error: String? = null
try {
library.folders.forEach { folder ->
try {
scanFolder(folder, seenSongIds) {
count++
status.set(ScanStatus(scanning = true, count = count))
}
} catch (e: Exception) {
log.error("Could not scan folder ${folder.id} (${folder.path})", e)
}
}
repository.deleteSongsNotIn(seenSongIds)
repository.rebuildAggregates()
} catch (t: Throwable) {
error = t.message ?: t::class.simpleName
log.error("Library scan failed after $count files", t)
} finally {
running.set(false)
}
val finalStatus = ScanStatus(scanning = false, count = count, error = error)
status.set(finalStatus)
log.info("Library scan finished: {} files, error={}", count, error)
return finalStatus
}
private fun scanFolder(folder: MusicFolder, seenSongIds: MutableSet<String>, onFile: () -> Unit) {
Files.walk(folder.path).use { paths ->
paths.filter { Files.isRegularFile(it) }.forEach { file ->
if (!file.fileName.toString().endsWith(".mp3", ignoreCase = true)) {
log.debug("Skipping unsupported file: {}", file)
return@forEach
}
onFile()
val relativePath = folder.path.relativize(file).joinToString("/") { it.toString() }
val existing = repository.findExisting(folder.id, relativePath)
try {
val attributes = Files.readAttributes(file, java.nio.file.attribute.BasicFileAttributes::class.java)
val mtime = attributes.lastModifiedTime().toMillis()
val size = attributes.size()
if (existing != null && existing.fileMtime == mtime && existing.size == size) {
seenSongIds += existing.id
return@forEach
}
val track = tagExtractor.extract(folder.id, folder.path, file)
if (track == null) {
if (existing != null) seenSongIds += existing.id
log.warn("Could not read MP3 metadata: {}", file)
return@forEach
}
val coverBytes = track.coverBytes
?: coverArtService.findSidecarCover(file)?.let(coverArtService::readCover)
repository.upsertTrack(track)
if (coverBytes != null && coverArtService.saveCover(track.albumId, coverBytes)) {
repository.setAlbumCover(track.albumId)
}
seenSongIds += track.songId
} catch (e: Exception) {
if (existing != null) seenSongIds += existing.id
log.warn("Could not index file: $file", e)
}
}
}
}
}