372 lines
16 KiB
Kotlin
372 lines
16 KiB
Kotlin
package com.qft.optical
|
|
|
|
import android.content.ContentResolver
|
|
import android.content.ContentValues
|
|
import android.content.Context
|
|
import android.net.Network
|
|
import android.net.Uri
|
|
import android.os.Build
|
|
import android.os.Environment
|
|
import android.provider.MediaStore
|
|
import android.util.Log
|
|
import java.io.File
|
|
import java.io.FileInputStream
|
|
import java.io.FileOutputStream
|
|
import java.io.OutputStream
|
|
import java.net.HttpURLConnection
|
|
import java.net.URL
|
|
import java.security.MessageDigest
|
|
|
|
data class DownloadedFile(val name: String, val size: Long, val uri: Uri?)
|
|
|
|
/** PC → Android client. It persists an encrypted-app-private partial file so a
|
|
* short Direct-AP loss resumes with HTTP Range instead of restarting the file. */
|
|
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,
|
|
resolver: ContentResolver,
|
|
network: Network?,
|
|
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)
|
|
val expectedName = requireNotNull(pairing.fileName)
|
|
val expectedSize = requireNotNull(pairing.fileSize)
|
|
val expectedSha = requireNotNull(pairing.sha256)
|
|
val partial = partialFile(context, pairing.session)
|
|
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, abortReason, onProgress)
|
|
}
|
|
if (partial.length() != expectedSize) {
|
|
error("下载提前结束:${partial.length()}/$expectedSize")
|
|
}
|
|
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))
|
|
} catch (interrupted: InterruptedException) {
|
|
Thread.currentThread().interrupt()
|
|
throw e
|
|
}
|
|
}
|
|
}
|
|
}
|
|
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(
|
|
network: Network?,
|
|
baseUrl: String,
|
|
pairing: PairingPayload,
|
|
deviceName: String,
|
|
partial: File,
|
|
expectedSize: Long,
|
|
abortReason: () -> String?,
|
|
onProgress: (received: Long, total: Long) -> Unit,
|
|
) {
|
|
val requestedOffset = partial.length().coerceIn(0L, expectedSize)
|
|
val conn = open(network, URL("$baseUrl/qft/download"))
|
|
try {
|
|
conn.requestMethod = "GET"
|
|
conn.connectTimeout = 5_000
|
|
// A QFT LAN transfer should start immediately. The old 120-second
|
|
// read timeout let Huawei tear down a local-only Wi-Fi request
|
|
// before a retry could occur. A short timeout safely resumes from
|
|
// the persisted Range offset and finishes all retries sooner.
|
|
conn.readTimeout = 12_000
|
|
conn.useCaches = false
|
|
conn.setRequestProperty("Connection", "close")
|
|
conn.setRequestProperty("X-QFT-Token", pairing.session)
|
|
conn.setRequestProperty("X-QFT-Device", Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8)))
|
|
if (requestedOffset > 0L) conn.setRequestProperty("Range", "bytes=$requestedOffset-")
|
|
|
|
val code = conn.responseCode
|
|
Log.i(TAG, "response code=$code requestedOffset=$requestedOffset contentLength=${conn.contentLengthLong} range=${conn.getHeaderField("Content-Range")}")
|
|
val resumed = code == HttpURLConnection.HTTP_PARTIAL
|
|
if (code != HttpURLConnection.HTTP_OK && !resumed) {
|
|
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
|
|
error("电脑下载服务返回 HTTP $code${message?.let { ": $it" } ?: ""}")
|
|
}
|
|
|
|
// Older desktop binaries return 200 even with Range. Restart only
|
|
// that request from zero, while current binaries return 206 and
|
|
// continue from the private partial file.
|
|
val offset = if (resumed) {
|
|
val range = conn.getHeaderField("Content-Range").orEmpty()
|
|
if (!range.startsWith("bytes $requestedOffset-")) {
|
|
error("下载服务返回了无效的断点范围:$range")
|
|
}
|
|
requestedOffset
|
|
} else {
|
|
0L
|
|
}
|
|
val expectedRemaining = expectedSize - offset
|
|
val contentLength = conn.contentLengthLong
|
|
if (contentLength >= 0L && contentLength != expectedRemaining) {
|
|
error("下载大小不匹配:$contentLength != $expectedRemaining")
|
|
}
|
|
onProgress(offset, expectedSize)
|
|
|
|
var received = offset
|
|
var lastReport = android.os.SystemClock.elapsedRealtime()
|
|
conn.inputStream.use { input ->
|
|
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
|
|
output.write(buffer, 0, n)
|
|
received += n.toLong()
|
|
if (received > expectedSize) error("下载数据超过二维码中的文件大小")
|
|
val now = android.os.SystemClock.elapsedRealtime()
|
|
if (now - lastReport >= 80L || received == expectedSize) {
|
|
onProgress(received, expectedSize)
|
|
lastReport = now
|
|
}
|
|
}
|
|
output.flush()
|
|
}
|
|
}
|
|
if (received != expectedSize) error("下载提前结束:$received/$expectedSize")
|
|
Log.i(TAG, "response complete received=$received/$expectedSize")
|
|
} finally {
|
|
conn.disconnect()
|
|
}
|
|
}
|
|
|
|
/** 校验也要报进度:大文件读一整遍是好几秒,静默的话看起来就是卡在 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)
|
|
done += n.toLong()
|
|
val now = android.os.SystemClock.elapsedRealtime()
|
|
if (now - lastReport >= 80L) {
|
|
onProgress(done, total)
|
|
lastReport = now
|
|
}
|
|
}
|
|
}
|
|
}
|
|
onProgress(total, total)
|
|
return digest.digest().toHex()
|
|
}
|
|
|
|
private fun saveToDownloads(
|
|
resolver: ContentResolver,
|
|
partial: File,
|
|
expectedName: String,
|
|
expectedSize: Long,
|
|
onProgress: (Long, Long) -> Unit,
|
|
): DownloadedFile {
|
|
var target: DownloadTarget? = null
|
|
try {
|
|
val createdTarget = createTarget(resolver, expectedName)
|
|
target = createdTarget
|
|
FileInputStream(partial).use { input ->
|
|
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("保存下载文件时大小发生变化")
|
|
}
|
|
}
|
|
target.commit()
|
|
return DownloadedFile(expectedName, expectedSize, target.uri)
|
|
} catch (e: Exception) {
|
|
target?.abort()
|
|
throw e
|
|
}
|
|
}
|
|
|
|
private fun partialFile(context: Context, session: String): File {
|
|
val root = context.getExternalFilesDir("qft") ?: context.cacheDir
|
|
return File(root, "$session.qftpart")
|
|
}
|
|
|
|
private fun createTarget(resolver: ContentResolver, name: String): DownloadTarget {
|
|
if (Build.VERSION.SDK_INT >= 29) {
|
|
val values = ContentValues().apply {
|
|
put(MediaStore.Downloads.DISPLAY_NAME, name)
|
|
put(MediaStore.Downloads.MIME_TYPE, "application/octet-stream")
|
|
put(MediaStore.Downloads.RELATIVE_PATH, "${Environment.DIRECTORY_DOWNLOADS}/QFT")
|
|
put(MediaStore.Downloads.IS_PENDING, 1)
|
|
}
|
|
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
|
?: error("无法创建 Downloads/QFT 文件")
|
|
val output = resolver.openOutputStream(uri, "w") ?: run {
|
|
resolver.delete(uri, null, null)
|
|
error("无法写入 Downloads/QFT 文件")
|
|
}
|
|
return DownloadTarget(
|
|
uri,
|
|
output,
|
|
commit = { resolver.update(uri, ContentValues().apply { put(MediaStore.Downloads.IS_PENDING, 0) }, null, null) },
|
|
abort = { resolver.delete(uri, null, null) },
|
|
)
|
|
}
|
|
@Suppress("DEPRECATION")
|
|
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "QFT")
|
|
if (!dir.exists() && !dir.mkdirs()) error("无法创建 Downloads/QFT")
|
|
val path = uniqueFile(dir, name)
|
|
return DownloadTarget(null, path.outputStream(), commit = {}, abort = { path.delete() })
|
|
}
|
|
|
|
private fun uniqueFile(dir: File, original: String): File {
|
|
val clean = original.replace(Regex("[\\\\/:*?\"<>|]"), "_").take(180).ifBlank { "qft-download.bin" }
|
|
val dot = clean.lastIndexOf('.')
|
|
val stem = if (dot > 0) clean.substring(0, dot) else clean
|
|
val ext = if (dot > 0) clean.substring(dot) else ""
|
|
var candidate = File(dir, clean)
|
|
var n = 1
|
|
while (candidate.exists()) {
|
|
candidate = File(dir, "$stem ($n)$ext")
|
|
n++
|
|
}
|
|
return candidate
|
|
}
|
|
|
|
private fun failureDetail(error: Throwable?): String {
|
|
if (error == null) return "未知错误"
|
|
return generateSequence(error) { it.cause }
|
|
.take(3)
|
|
.joinToString(" ← ") { cause ->
|
|
cause.message?.takeIf { it.isNotBlank() } ?: cause.javaClass.simpleName
|
|
}
|
|
}
|
|
|
|
private fun open(network: Network?, url: URL): HttpURLConnection =
|
|
(network?.openConnection(url) ?: url.openConnection()) as HttpURLConnection
|
|
|
|
private data class DownloadTarget(
|
|
val uri: Uri?,
|
|
val output: OutputStream,
|
|
val commit: () -> Unit,
|
|
val abort: () -> Unit,
|
|
)
|
|
|
|
private fun ByteArray.toHex(): String = buildString(size * 2) {
|
|
for (byte in this@toHex) append((byte.toInt() and 0xFF).toString(16).padStart(2, '0'))
|
|
}
|
|
}
|