Use bounded independent Android cache files for each attachment
This commit is contained in:
1 parent
fd3fc971fa
commit
add016894b
2 files changed
+21
-8
No files matched your search
@@ -1130,16 +1130,29 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
fun copyUriToCache(context: Context, uri: Uri, fileName: String): String? {
|
||||
var cacheFile: File? = null
|
||||
try {
|
||||
val cacheDir = File(context.cacheDir, "attachments")
|
||||
cacheDir.mkdirs()
|
||||
val cacheFile = File(cacheDir, fileName)
|
||||
val name = fileName.substringAfterLast('/').substringAfterLast('\\')
|
||||
require(name.isNotBlank() && name != "." && name != "..") { "Неверное имя файла" }
|
||||
val cacheDir = File(context.cacheDir, "attachments/${java.util.UUID.randomUUID()}")
|
||||
check(cacheDir.mkdirs()) { "Не удалось создать каталог вложения" }
|
||||
val outputFile = File(cacheDir, name)
|
||||
cacheFile = outputFile
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
FileOutputStream(cacheFile).use { output -> input.copyTo(output) }
|
||||
} ?: return null
|
||||
LogManager.addLog("INFO", "VM", "copied attachment to cache: ${cacheFile.absolutePath}")
|
||||
return cacheFile.absolutePath
|
||||
FileOutputStream(outputFile).use { output ->
|
||||
val buffer = ByteArray(65536); var size = 0L
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
size += n; check(size <= 1024L * 1024 * 1024) { "Файл больше 1 ГиБ" }
|
||||
output.write(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
} ?: throw IllegalStateException("Не удалось открыть вложение")
|
||||
LogManager.addLog("INFO", "VM", "copied attachment to cache: ${outputFile.absolutePath}")
|
||||
return outputFile.absolutePath
|
||||
} catch (e: Exception) {
|
||||
cacheFile?.delete(); cacheFile?.parentFile?.delete()
|
||||
LogManager.addLog("ERROR", "VM", "copyUriToCache failed: ${e.message}")
|
||||
return null
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user