feat: 提交0.4加速版二维码直传与自动配网优化
This commit is contained in:
@@ -0,0 +1,276 @@
|
||||
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
|
||||
|
||||
fun download(
|
||||
context: Context,
|
||||
resolver: ContentResolver,
|
||||
network: Network?,
|
||||
baseUrl: String,
|
||||
pairing: PairingPayload,
|
||||
deviceName: String,
|
||||
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()
|
||||
|
||||
var last: Exception? = null
|
||||
repeat(ATTEMPTS) { attempt ->
|
||||
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)
|
||||
}
|
||||
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
|
||||
} catch (e: Exception) {
|
||||
last = e
|
||||
Log.w(TAG, "attempt=${attempt + 1}/$ATTEMPTS failed partial=${partial.length()}/$expectedSize: ${failureDetail(e)}", e)
|
||||
if (attempt + 1 < ATTEMPTS) {
|
||||
try {
|
||||
Thread.sleep(250L * (attempt + 1))
|
||||
} catch (interrupted: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw IllegalStateException("从电脑下载失败,已重试 $ATTEMPTS 次:${failureDetail(last)}", last)
|
||||
}
|
||||
|
||||
private fun receiveAttempt(
|
||||
network: Network?,
|
||||
baseUrl: String,
|
||||
pairing: PairingPayload,
|
||||
deviceName: String,
|
||||
partial: File,
|
||||
expectedSize: Long,
|
||||
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) {
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
private fun verifySha256(file: File, expectedSha: String) {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
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)
|
||||
}
|
||||
}
|
||||
val actual = digest.digest().toHex()
|
||||
if (!actual.equals(expectedSha, ignoreCase = true)) {
|
||||
file.delete()
|
||||
error("文件校验失败,已清除不完整缓存;请重试")
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveToDownloads(
|
||||
resolver: ContentResolver,
|
||||
partial: File,
|
||||
expectedName: String,
|
||||
expectedSize: Long,
|
||||
): 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
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
if (n == 0) continue
|
||||
output.write(buffer, 0, n)
|
||||
copied += n.toLong()
|
||||
}
|
||||
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'))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user