修复封面保存在cache路径里导致意外被清理的bug (#1169) @woruteyqi

修复封面保存在cache路径里导致意外被清理的bug
This commit is contained in:
aoi authored and GitHub committed 2026-05-26 00:49:05 +08:00
1 parent 2d6fc67ac7
commit 8205498f16
1 file changed
+13 -9
@@ -18,6 +18,7 @@ import io.legado.app.help.book.removeType
import io.legado.app.model.ReadBook import io.legado.app.model.ReadBook
import io.legado.app.utils.FileUtils import io.legado.app.utils.FileUtils
import io.legado.app.utils.MD5Utils import io.legado.app.utils.MD5Utils
import io.legado.app.utils.externalFiles
import io.legado.app.utils.inputStream import io.legado.app.utils.inputStream
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
@@ -157,20 +158,23 @@ class BookInfoEditViewModel(application: Application) : BaseViewModel(applicatio
fun coverChangeTo(context: Context, uri: Uri) { fun coverChangeTo(context: Context, uri: Uri) {
execute { execute {
runCatching { runCatching {
context.externalCacheDir?.let { externalCacheDir ->
val file = File(externalCacheDir, "covers")
val suffix = context.contentResolver.getType(uri)?.substringAfterLast("/") ?: "jpg" val suffix = context.contentResolver.getType(uri)?.substringAfterLast("/") ?: "jpg"
val fileName = uri.inputStream(context).getOrThrow().use { MD5Utils.md5Encode(it) } + ".$suffix" val coversDir = FileUtils.createFolderIfNotExist(context.externalFiles, "covers")
val coverFile = FileUtils.createFileIfNotExist(file, fileName) val tempFile = File(coversDir, "${System.currentTimeMillis()}.tmp")
context.contentResolver.openInputStream(uri)?.use { inputStream -> uri.inputStream(context).getOrThrow().use { inputStream ->
FileOutputStream(coverFile).use { outputStream -> FileOutputStream(tempFile).use { outputStream ->
inputStream.copyTo(outputStream) inputStream.copyTo(outputStream)
} }
} }
_uiState.value = _uiState.value.copy(coverUrl = coverFile.absolutePath) val md5 = tempFile.inputStream().use { MD5Utils.md5Encode(it) }
} ?: run { val coverFile = File(coversDir, "$md5.$suffix")
AppLog.put("External cache directory is null", Throwable("Null directory"), true) if (coverFile.exists()) {
tempFile.delete()
} else if (!tempFile.renameTo(coverFile)) {
tempFile.copyTo(coverFile, overwrite = true)
tempFile.delete()
} }
_uiState.value = _uiState.value.copy(coverUrl = coverFile.absolutePath)
}.onFailure { }.onFailure {
AppLog.put("书籍封面保存失败\n$it", it, true) AppLog.put("书籍封面保存失败\n$it", it, true)
} }