修复封面保存在cache路径里导致意外被清理的bug (#1169) @woruteyqi
修复封面保存在cache路径里导致意外被清理的bug
This commit is contained in:
1 file changed
+16
-12
@@ -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 suffix = context.contentResolver.getType(uri)?.substringAfterLast("/") ?: "jpg"
|
||||||
val file = File(externalCacheDir, "covers")
|
val coversDir = FileUtils.createFolderIfNotExist(context.externalFiles, "covers")
|
||||||
val suffix = context.contentResolver.getType(uri)?.substringAfterLast("/") ?: "jpg"
|
val tempFile = File(coversDir, "${System.currentTimeMillis()}.tmp")
|
||||||
val fileName = uri.inputStream(context).getOrThrow().use { MD5Utils.md5Encode(it) } + ".$suffix"
|
uri.inputStream(context).getOrThrow().use { inputStream ->
|
||||||
val coverFile = FileUtils.createFileIfNotExist(file, fileName)
|
FileOutputStream(tempFile).use { outputStream ->
|
||||||
context.contentResolver.openInputStream(uri)?.use { inputStream ->
|
inputStream.copyTo(outputStream)
|
||||||
FileOutputStream(coverFile).use { outputStream ->
|
|
||||||
inputStream.copyTo(outputStream)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_uiState.value = _uiState.value.copy(coverUrl = coverFile.absolutePath)
|
|
||||||
} ?: run {
|
|
||||||
AppLog.put("External cache directory is null", Throwable("Null directory"), true)
|
|
||||||
}
|
}
|
||||||
|
val md5 = tempFile.inputStream().use { MD5Utils.md5Encode(it) }
|
||||||
|
val coverFile = File(coversDir, "$md5.$suffix")
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user