fix: possible issues with renaming files when caching

* Write files to cache directly (previously first to .tmp, then rename, which may've led to issues on some devices)
This commit is contained in:
Acclorite 2025-12-27 14:35:22 +02:00
parent 7f234a0ba1
commit c7cae413f7
No known key found for this signature in database
GPG key ID: 6E54C611F6EE8593

View file

@ -174,25 +174,16 @@ class CachedFile(
*/ */
private fun storeInCache(): File? { private fun storeInCache(): File? {
if (isDirectory) return null if (isDirectory) return null
val cacheFile = File(context.cacheDir, UUID.randomUUID().toString())
val cacheDir = context.cacheDir
val fileName = path.replace("_", "-").replace("/", "_").take(80) + "_${path.length}"
val cacheFile = File(cacheDir, fileName)
val tempFile = File(cacheDir, "$fileName.tmp")
try { try {
context.contentResolver.openInputStream(uri)?.use { input -> context.contentResolver.openInputStream(uri)?.use { input ->
BufferedOutputStream(FileOutputStream(tempFile)).use { output -> BufferedOutputStream(FileOutputStream(cacheFile)).use { output ->
input.copyTo(output) input.copyTo(output)
} }
} ?: throw IllegalStateException("Failed to open InputStream.") } ?: throw IllegalStateException("Failed to open InputStream.")
if (!tempFile.renameTo(cacheFile)) {
throw IllegalStateException("Failed to rename .tmp file.")
}
} catch (e: Exception) { } catch (e: Exception) {
e.printStackTrace() e.printStackTrace()
tempFile.delete()
return null return null
} }