DownloadWorker: Use tmp filenames while downloading
Signed-off-by: Aayush Gupta <aayushgupta219@gmail.com>
This commit is contained in:
@@ -275,31 +275,36 @@ class DownloadWorker @AssistedInject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val isNewFile = request.file.createNewFile()
|
// Download as a temporary file to avoid installing corrupted files
|
||||||
|
val tmpFileSuffix = ".tmp"
|
||||||
|
val tmpFile = File(request.file.absolutePath + tmpFileSuffix)
|
||||||
|
val isNewFile = tmpFile.createNewFile()
|
||||||
|
|
||||||
val okHttpClient = httpClient as HttpClient
|
val okHttpClient = httpClient as HttpClient
|
||||||
val headers = mutableMapOf<String, String>()
|
val headers = mutableMapOf<String, String>()
|
||||||
|
|
||||||
if (!isNewFile) {
|
if (!isNewFile) {
|
||||||
Log.i(TAG, "${request.file} has an unfinished download, resuming!")
|
Log.i(TAG, "$tmpFile has an unfinished download, resuming!")
|
||||||
downloadedBytes += request.file.length()
|
downloadedBytes += tmpFile.length()
|
||||||
headers["Range"] = "bytes=${request.file.length()}-"
|
headers["Range"] = "bytes=${tmpFile.length()}-"
|
||||||
}
|
}
|
||||||
|
|
||||||
okHttpClient.call(request.url, headers).body?.byteStream()?.use { input ->
|
okHttpClient.call(request.url, headers).body?.byteStream()?.use { input ->
|
||||||
FileOutputStream(request.file, !isNewFile).use {
|
FileOutputStream(tmpFile, !isNewFile).use {
|
||||||
input.copyTo(it, request.size).collect { p -> onProgress(p) }
|
input.copyTo(it, request.size).collect { p -> onProgress(p) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure downloaded file matches expected sha
|
// Ensure downloaded file matches expected sha
|
||||||
if (validSha(request.file, expectedSha, algorithm)) {
|
if (!validSha(tmpFile, expectedSha, algorithm)) {
|
||||||
return@withContext Result.success()
|
throw Exception("Incorrect hash for $tmpFile")
|
||||||
} else {
|
|
||||||
Log.e(TAG, "Incorrect hash for ${request.file}")
|
|
||||||
throw Exception("Incorrect hash")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!tmpFile.renameTo(request.file)) {
|
||||||
|
throw Exception("Failed to remove .tmp extension from $tmpFile")
|
||||||
|
}
|
||||||
|
|
||||||
|
return@withContext Result.success()
|
||||||
} catch (exception: Exception) {
|
} catch (exception: Exception) {
|
||||||
Log.e(TAG, "Failed to download ${request.file}!", exception)
|
Log.e(TAG, "Failed to download ${request.file}!", exception)
|
||||||
notifyStatus(DownloadStatus.FAILED)
|
notifyStatus(DownloadStatus.FAILED)
|
||||||
|
|||||||
Reference in New Issue
Block a user