Skip to content

Commit

Permalink
Merge pull request #3656 from SpiritCroc/broken_downloads
Browse files Browse the repository at this point in the history
Avoid incomplete downloads in cache
  • Loading branch information
bmarty authored Jul 19, 2021
2 parents f517691 + 512e1b3 commit 2e64f89
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog.d/3656.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Avoid incomplete downloads in cache
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,14 @@ internal class DefaultFileService @Inject constructor(
Timber.v("Response size ${response.body?.contentLength()} - Stream available: ${!source.exhausted()}")

// Write the file to cache (encrypted version if the file is encrypted)
writeToFile(source.inputStream(), cachedFiles.file)
// Write to a tmp file first, so if we abort before done, we don't have a broken cached file
val tmpFile = File(cachedFiles.file.parentFile, "${cachedFiles.file.name}.tmp")
if (tmpFile.exists()) {
Timber.v("## FileService: discard aborted tmp file ${tmpFile.path}")
}
writeToFile(source.inputStream(), tmpFile)
response.close()
tmpFile.renameTo(cachedFiles.file)
} else {
Timber.v("## FileService: cache hit for $url")
}
Expand All @@ -145,15 +151,21 @@ internal class DefaultFileService @Inject constructor(
Timber.v("## FileService: decrypt file")
// Ensure the parent folder exists
cachedFiles.decryptedFile.parentFile?.mkdirs()
// Write to a tmp file first, so if we abort before done, we don't have a broken cached file
val tmpFile = File(cachedFiles.decryptedFile.parentFile, "${cachedFiles.decryptedFile.name}.tmp")
if (tmpFile.exists()) {
Timber.v("## FileService: discard aborted tmp file ${tmpFile.path}")
}
val decryptSuccess = cachedFiles.file.inputStream().use { inputStream ->
cachedFiles.decryptedFile.outputStream().buffered().use { outputStream ->
tmpFile.outputStream().buffered().use { outputStream ->
MXEncryptedAttachments.decryptAttachment(
inputStream,
elementToDecrypt,
outputStream
)
}
}
tmpFile.renameTo(cachedFiles.decryptedFile)
if (!decryptSuccess) {
throw IllegalStateException("Decryption error")
}
Expand Down

0 comments on commit 2e64f89

Please sign in to comment.