Improved tag editor code

This commit is contained in:
Valeri Gokadze 2024-12-07 17:28:42 +04:00
parent 4e5ff47324
commit e62ff2696e

View file

@ -74,9 +74,16 @@ class TagWriter {
val audioFile = AudioFileIO.read(File(filePath)) val audioFile = AudioFileIO.read(File(filePath))
val tag = audioFile.tagOrCreateAndSetDefault val tag = audioFile.tagOrCreateAndSetDefault
if (info.fieldKeyValueMap != null) { if (info.fieldKeyValueMap != null) {
for ((key, value) in info.fieldKeyValueMap) { for ((key, newValue) in info.fieldKeyValueMap) {
try { try {
tag.setField(key, value) val currentValue = tag.getFirst(key)
if (currentValue != newValue) {
if (newValue.isEmpty()) {
tag.deleteField(key)
} else {
tag.setField(key, newValue)
}
}
} catch (e: FieldDataInvalidException) { } catch (e: FieldDataInvalidException) {
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
context.showToast(R.string.could_not_write_tags_to_file) context.showToast(R.string.could_not_write_tags_to_file)
@ -127,6 +134,7 @@ class TagWriter {
val cacheFiles = mutableListOf<File>() val cacheFiles = mutableListOf<File>()
var artwork: Artwork? = null var artwork: Artwork? = null
var albumArtFile: File? = null var albumArtFile: File? = null
if (info.artworkInfo?.artwork != null) { if (info.artworkInfo?.artwork != null) {
try { try {
albumArtFile = createAlbumArtFile(context).canonicalFile albumArtFile = createAlbumArtFile(context).canonicalFile
@ -140,24 +148,36 @@ class TagWriter {
e.printStackTrace() e.printStackTrace()
} }
} }
var wroteArtwork = false var wroteArtwork = false
var deletedArtwork = false var deletedArtwork = false
for (filePath in info.filePaths!!) { for (filePath in info.filePaths!!) {
try { try {
val originFile = File(filePath) val originFile = File(filePath)
val cacheFile = File(context.cacheDir, originFile.name) val cacheFile = File(context.cacheDir, originFile.name)
cacheFiles.add(cacheFile) cacheFiles.add(cacheFile)
originFile.inputStream().use { input -> originFile.inputStream().use { input ->
cacheFile.outputStream().use { output -> cacheFile.outputStream().use { output ->
input.copyTo(output) input.copyTo(output)
} }
} }
val audioFile = AudioFileIO.read(cacheFile) val audioFile = AudioFileIO.read(cacheFile)
val tag = audioFile.tagOrCreateAndSetDefault val tag = audioFile.tagOrCreateAndSetDefault
if (info.fieldKeyValueMap != null) { if (info.fieldKeyValueMap != null) {
for ((key, value) in info.fieldKeyValueMap) { for ((key, newValue) in info.fieldKeyValueMap) {
try { try {
tag.setField(key, value) val currentValue = tag.getFirst(key)
if (currentValue != newValue) {
if (newValue.isEmpty()) {
tag.deleteField(key)
} else {
tag.setField(key, newValue)
}
}
} catch (e: FieldDataInvalidException) { } catch (e: FieldDataInvalidException) {
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
context.showToast(R.string.could_not_write_tags_to_file) context.showToast(R.string.could_not_write_tags_to_file)