修复传输问题
This commit is contained in:
@@ -25,6 +25,11 @@ object DownloadClient {
|
||||
private const val TAG = "QftDownload"
|
||||
private const val BUFFER_SIZE = 1024 * 1024
|
||||
private const val ATTEMPTS = 5
|
||||
/** 整份重下的轮数。仅在 SHA-256 不匹配(缓存已损坏)时才会用到第二轮。 */
|
||||
private const val VERIFY_ROUNDS = 2
|
||||
|
||||
/** 落盘阶段的失败与「下载失败」是两回事,用独立异常类型区分。 */
|
||||
class SaveFailure(message: String, cause: Throwable?) : Exception(message, cause)
|
||||
|
||||
fun download(
|
||||
context: Context,
|
||||
@@ -33,6 +38,11 @@ object DownloadClient {
|
||||
baseUrl: String,
|
||||
pairing: PairingPayload,
|
||||
deviceName: String,
|
||||
/** 返回非 null 表示应立刻中止(例如 QFT 临时网络已断开),并以该原因报错。 */
|
||||
abortReason: () -> String? = { null },
|
||||
/** 阶段提示。传输完成后还有校验与落盘两步,必须让 UI 有反馈,
|
||||
* 否则用户看到的就是「进度条停在 100% 然后报错」。 */
|
||||
onPhase: (String) -> Unit = {},
|
||||
onProgress: (received: Long, total: Long) -> Unit,
|
||||
): DownloadedFile {
|
||||
require(pairing.direction == TransferDirection.DOWNLOAD_TO_PHONE)
|
||||
@@ -43,24 +53,68 @@ object DownloadClient {
|
||||
partial.parentFile?.let { if (!it.exists() && !it.mkdirs()) error("无法创建接收缓存目录") }
|
||||
if (partial.length() > expectedSize) partial.delete()
|
||||
|
||||
// 落盘时缓存文件与目标文件同时存在,需要约 2 倍空间。
|
||||
// 不预检的话,这里会在下载 100% 之后才失败,用户看到的是「快结束时失败」。
|
||||
ensureSpaceForTransfer(partial, expectedSize)
|
||||
|
||||
repeat(VERIFY_ROUNDS) { round ->
|
||||
receiveUntilComplete(network, baseUrl, pairing, deviceName, partial,
|
||||
expectedSize, abortReason, onProgress)
|
||||
|
||||
onPhase("正在校验文件完整性…")
|
||||
val actual = sha256(partial, onProgress)
|
||||
if (actual.equals(expectedSha, ignoreCase = true)) {
|
||||
onPhase("正在保存到 Downloads/QFT…")
|
||||
ensureSpaceForSave(partial, expectedSize)
|
||||
val result = try {
|
||||
saveToDownloads(resolver, partial, expectedName, expectedSize, onProgress)
|
||||
} catch (e: Exception) {
|
||||
// 这一步失败与网络无关,重下多少次都没用,直接如实报错
|
||||
throw SaveFailure("文件已完整收到,但保存到 Downloads/QFT 失败:${failureDetail(e)}", e)
|
||||
}
|
||||
partial.delete()
|
||||
Log.i(TAG, "completed size=$expectedSize")
|
||||
return result
|
||||
}
|
||||
|
||||
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
|
||||
partial.delete()
|
||||
if (round + 1 >= VERIFY_ROUNDS) {
|
||||
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码")
|
||||
}
|
||||
onPhase("校验未通过,正在重新完整下载…")
|
||||
}
|
||||
error("下载未能完成")
|
||||
}
|
||||
|
||||
/** 传输阶段:断点续传 + 有限重试。只有这一段的失败才算「下载失败」。 */
|
||||
private fun receiveUntilComplete(
|
||||
network: Network?,
|
||||
baseUrl: String,
|
||||
pairing: PairingPayload,
|
||||
deviceName: String,
|
||||
partial: File,
|
||||
expectedSize: Long,
|
||||
abortReason: () -> String?,
|
||||
onProgress: (received: Long, total: Long) -> Unit,
|
||||
) {
|
||||
var last: Exception? = null
|
||||
repeat(ATTEMPTS) { attempt ->
|
||||
abortReason()?.let { throw IllegalStateException(it, last) }
|
||||
try {
|
||||
Log.i(TAG, "attempt=${attempt + 1}/$ATTEMPTS partial=${partial.length()}/$expectedSize endpoint=$baseUrl")
|
||||
if (partial.length() < expectedSize) {
|
||||
receiveAttempt(network, baseUrl, pairing, deviceName, partial, expectedSize, onProgress)
|
||||
receiveAttempt(network, baseUrl, pairing, deviceName, partial,
|
||||
expectedSize, abortReason, onProgress)
|
||||
}
|
||||
if (partial.length() != expectedSize) {
|
||||
error("下载提前结束:${partial.length()}/$expectedSize")
|
||||
}
|
||||
verifySha256(partial, expectedSha)
|
||||
val result = saveToDownloads(resolver, partial, expectedName, expectedSize)
|
||||
partial.delete()
|
||||
Log.i(TAG, "completed size=$expectedSize")
|
||||
return result
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
last = e
|
||||
Log.w(TAG, "attempt=${attempt + 1}/$ATTEMPTS failed partial=${partial.length()}/$expectedSize: ${failureDetail(e)}", e)
|
||||
abortReason()?.let { throw IllegalStateException(it, e) }
|
||||
if (attempt + 1 < ATTEMPTS) {
|
||||
try {
|
||||
Thread.sleep(250L * (attempt + 1))
|
||||
@@ -71,7 +125,28 @@ object DownloadClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
throw IllegalStateException("从电脑下载失败,已重试 $ATTEMPTS 次:${failureDetail(last)}", last)
|
||||
val progressed = partial.length()
|
||||
throw IllegalStateException(
|
||||
"从电脑下载失败,已重试 $ATTEMPTS 次(已收到 ${progressed}/$expectedSize 字节):${failureDetail(last)}",
|
||||
last,
|
||||
)
|
||||
}
|
||||
|
||||
/** 传输 + 落盘阶段合计需要的可用空间。 */
|
||||
private fun ensureSpaceForTransfer(partial: File, expectedSize: Long) {
|
||||
val root = partial.parentFile ?: return
|
||||
val needed = (expectedSize - partial.length()).coerceAtLeast(0L) + expectedSize
|
||||
val usable = root.usableSpace
|
||||
if (usable in 1 until needed) {
|
||||
error("存储空间不足:本次接收约需 ${needed / 1024 / 1024} MB(含保存时的临时副本),当前可用 ${usable / 1024 / 1024} MB")
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureSpaceForSave(partial: File, expectedSize: Long) {
|
||||
val usable = partial.parentFile?.usableSpace ?: return
|
||||
if (usable in 1 until expectedSize) {
|
||||
error("存储空间不足:保存副本还需 ${expectedSize / 1024 / 1024} MB,当前可用 ${usable / 1024 / 1024} MB")
|
||||
}
|
||||
}
|
||||
|
||||
private fun receiveAttempt(
|
||||
@@ -81,6 +156,7 @@ object DownloadClient {
|
||||
deviceName: String,
|
||||
partial: File,
|
||||
expectedSize: Long,
|
||||
abortReason: () -> String?,
|
||||
onProgress: (received: Long, total: Long) -> Unit,
|
||||
) {
|
||||
val requestedOffset = partial.length().coerceIn(0L, expectedSize)
|
||||
@@ -132,6 +208,9 @@ object DownloadClient {
|
||||
FileOutputStream(partial, offset > 0L).use { output ->
|
||||
val buffer = ByteArray(BUFFER_SIZE)
|
||||
while (true) {
|
||||
// 网络已断开时立刻收手:否则会在 readTimeout 上白等 12 秒,
|
||||
// 再乘以 5 次重试,用户等一分钟才看到错误。
|
||||
abortReason()?.let { error(it) }
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
if (n == 0) continue
|
||||
@@ -154,21 +233,30 @@ object DownloadClient {
|
||||
}
|
||||
}
|
||||
|
||||
private fun verifySha256(file: File, expectedSha: String) {
|
||||
/** 校验也要报进度:大文件读一整遍是好几秒,静默的话看起来就是卡在 100%。 */
|
||||
private fun sha256(file: File, onProgress: (Long, Long) -> Unit): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
val total = file.length()
|
||||
var done = 0L
|
||||
var lastReport = 0L
|
||||
FileInputStream(file).use { input ->
|
||||
val buffer = ByteArray(BUFFER_SIZE)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
if (n > 0) digest.update(buffer, 0, n)
|
||||
if (n > 0) {
|
||||
digest.update(buffer, 0, n)
|
||||
done += n.toLong()
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
if (now - lastReport >= 80L) {
|
||||
onProgress(done, total)
|
||||
lastReport = now
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val actual = digest.digest().toHex()
|
||||
if (!actual.equals(expectedSha, ignoreCase = true)) {
|
||||
file.delete()
|
||||
error("文件校验失败,已清除不完整缓存;请重试")
|
||||
}
|
||||
onProgress(total, total)
|
||||
return digest.digest().toHex()
|
||||
}
|
||||
|
||||
private fun saveToDownloads(
|
||||
@@ -176,6 +264,7 @@ object DownloadClient {
|
||||
partial: File,
|
||||
expectedName: String,
|
||||
expectedSize: Long,
|
||||
onProgress: (Long, Long) -> Unit,
|
||||
): DownloadedFile {
|
||||
var target: DownloadTarget? = null
|
||||
try {
|
||||
@@ -185,12 +274,18 @@ object DownloadClient {
|
||||
createdTarget.output.use { output ->
|
||||
val buffer = ByteArray(BUFFER_SIZE)
|
||||
var copied = 0L
|
||||
var lastReport = 0L
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
if (n == 0) continue
|
||||
output.write(buffer, 0, n)
|
||||
copied += n.toLong()
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
if (now - lastReport >= 80L) {
|
||||
onProgress(copied, expectedSize)
|
||||
lastReport = now
|
||||
}
|
||||
}
|
||||
output.flush()
|
||||
if (copied != expectedSize) error("保存下载文件时大小发生变化")
|
||||
|
||||
Reference in New Issue
Block a user