package win.taptap.musicmanager.db import java.time.Instant import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.insertIgnore import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.update import win.taptap.musicmanager.scanner.ArtistRef import win.taptap.musicmanager.scanner.ExtractedTrack import win.taptap.musicmanager.util.IdGenerator import win.taptap.musicmanager.util.SortNames data class ExistingSong( val id: String, val fileMtime: Long, val size: Long, ) /** Persistence for the scanner. Per-user state is never touched when metadata is updated. */ object MediaRepository { fun findExisting(folderId: Int, relativePath: String): ExistingSong? = transaction { SongsTable.selectAll() .where { (SongsTable.folderId eq folderId) and (SongsTable.relativePath eq relativePath) } .singleOrNull() ?.let { ExistingSong( id = it[SongsTable.id], fileMtime = it[SongsTable.fileMtime], size = it[SongsTable.size], ) } } fun upsertTrack(track: ExtractedTrack) { val now = Instant.now().toString() transaction { (track.albumArtists + track.artists).distinctBy { it.id }.forEach(::upsertArtist) val albumSearch = IdGenerator.normalize( "${track.albumTitle} ${track.albumArtists.joinToString(" ") { it.name }}", ) val albumExists = AlbumsTable.selectAll() .where { AlbumsTable.id eq track.albumId } .any() if (albumExists) { AlbumsTable.update({ AlbumsTable.id eq track.albumId }) { it[name] = track.albumTitle if (track.year != null) it[year] = track.year it[searchText] = albumSearch } } else { AlbumsTable.insert { it[id] = track.albumId it[name] = track.albumTitle it[year] = track.year it[createdAt] = now it[searchText] = albumSearch } } AlbumArtistsTable.deleteWhere { it.run { AlbumArtistsTable.albumId eq track.albumId } } track.albumArtists.forEachIndexed { index, artist -> AlbumArtistsTable.insertIgnore { it[albumId] = track.albumId it[artistId] = artist.id it[position] = index } } val existingByPath = SongsTable.selectAll() .where { (SongsTable.folderId eq track.folderId) and (SongsTable.relativePath eq track.relativePath) } .singleOrNull() val existingId = existingByPath?.get(SongsTable.id) if (existingId != null && existingId != track.songId) { SongsTable.deleteWhere { it.run { SongsTable.id eq existingId } } } val songExists = existingId == track.songId || SongsTable.selectAll().where { SongsTable.id eq track.songId }.any() if (songExists) { SongsTable.update({ SongsTable.id eq track.songId }) { it[albumId] = track.albumId it[folderId] = track.folderId it[title] = track.title it[displayArtist] = track.displayArtist it[albumName] = track.albumTitle it[trackNumber] = track.trackNumber it[discNumber] = track.discNumber it[year] = track.year it[duration] = track.durationSeconds it[bitRate] = track.bitRate it[size] = track.size it[suffix] = track.suffix it[contentType] = track.contentType it[relativePath] = track.relativePath it[fileMtime] = track.fileMtime it[searchText] = track.searchText it[updatedAt] = now it[lyrics] = track.lyrics } } else { SongsTable.insert { it[id] = track.songId it[albumId] = track.albumId it[folderId] = track.folderId it[title] = track.title it[displayArtist] = track.displayArtist it[albumName] = track.albumTitle it[trackNumber] = track.trackNumber it[discNumber] = track.discNumber it[year] = track.year it[duration] = track.durationSeconds it[bitRate] = track.bitRate it[size] = track.size it[suffix] = track.suffix it[contentType] = track.contentType it[relativePath] = track.relativePath it[fileMtime] = track.fileMtime it[createdAt] = now it[searchText] = track.searchText it[updatedAt] = now it[lyrics] = track.lyrics } } SongArtistsTable.deleteWhere { it.run { SongArtistsTable.songId eq track.songId } } track.artists.forEachIndexed { index, artist -> SongArtistsTable.insertIgnore { it[songId] = track.songId it[artistId] = artist.id it[position] = index } } SongGenresTable.deleteWhere { it.run { SongGenresTable.songId eq track.songId } } track.genres.forEach { genre -> SongGenresTable.insertIgnore { it[songId] = track.songId it[this.genre] = genre } } } } fun setAlbumCover(albumId: String) { transaction { AlbumsTable.update({ AlbumsTable.id eq albumId }) { it[coverArt] = albumId } } } fun deleteSongsNotIn(seenSongIds: Set) { transaction { val obsolete = SongsTable.selectAll() .map { it[SongsTable.id] } .filterNot { it in seenSongIds } val now = Instant.now().toString() obsolete.forEach { songId -> LibraryTombstonesTable.insertIgnore { it[entity] = "song" it[entityId] = songId it[deletedAt] = now } SongsTable.deleteWhere { it.run { SongsTable.id eq songId } } } exec("DELETE FROM albums WHERE id NOT IN (SELECT DISTINCT album_id FROM songs)") exec( """ DELETE FROM artists WHERE id NOT IN ( SELECT artist_id FROM song_artists UNION SELECT artist_id FROM album_artists ) """.trimIndent(), ) } } /** Recomputes album/artist genre aggregates from the song-level tags. */ fun rebuildAggregates() { transaction { exec("DELETE FROM album_genres") exec( """ INSERT INTO album_genres (album_id, genre) SELECT DISTINCT s.album_id, sg.genre FROM song_genres sg JOIN songs s ON s.id = sg.song_id """.trimIndent(), ) exec("DELETE FROM artist_genres") exec( """ INSERT INTO artist_genres (artist_id, genre) SELECT DISTINCT sa.artist_id, sg.genre FROM song_artists sa JOIN song_genres sg ON sg.song_id = sa.song_id UNION SELECT DISTINCT aa.artist_id, ag.genre FROM album_artists aa JOIN album_genres ag ON ag.album_id = aa.album_id """.trimIndent(), ) } } fun countSongs(): Long = transaction { SongsTable.selectAll().count() } private fun upsertArtist(artist: ArtistRef) { ArtistsTable.insertIgnore { it[id] = artist.id it[name] = artist.name it[sortName] = SortNames.of(artist.name) it[searchText] = IdGenerator.normalize(artist.name) } ArtistsTable.update({ ArtistsTable.id eq artist.id }) { it[name] = artist.name it[sortName] = SortNames.of(artist.name) it[searchText] = IdGenerator.normalize(artist.name) } } }