10 Commits

Author SHA1 Message Date
zhy a960ad91d8 合并 0.4.7 双向并发传输封版
# Conflicts:
#	README.md
#	android/app/src/main/java/com/qft/optical/DownloadClient.kt
#	android/app/src/main/java/com/qft/optical/UploadClient.kt
#	docs/PROTOCOL.md
#	windows/src/sender.rs
2026-08-11 14:27:30 +08:00
zhy 20ac4dc6c7 发布 0.4.7 双向并发传输封版 2026-08-11 13:49:27 +08:00
zhy200308 cb92397300 修正为仅打包Rust桌面端 2026-08-11 11:48:09 +08:00
zhy200308 dffee5365d Merge remote-tracking branch 'origin/main' 2026-08-11 11:31:44 +08:00
zhy200308 a4edf734b6 优化大文件稳定并发传输与打包流程 2026-08-11 11:27:40 +08:00
zhy e326611c82 发布 0.4.6 封版 2026-08-11 10:53:59 +08:00
kmcc f260ff4266 Merge pull request 'New test' (#1) from new-test into main
Reviewed-on: https://git.xskjhy.top/kmcc/QFT/pulls/1
2026-08-11 10:44:48 +08:00
zhy 34b8fdf050 合并直传接收与文件选择优化 2026-08-11 10:21:45 +08:00
zhy e9e51a4941 修复直传接收并优化文件选择提示 2026-08-11 10:21:37 +08:00
zhy200308 b444a39a63 修复传输问题 2026-08-11 09:44:26 +08:00
29 changed files with 1708 additions and 263 deletions
+2
View File
@@ -1,6 +1,8 @@
# Rust
/target
**/target
windows/target-*/
**/__pycache__/
# Android
.gradle/
**/build/
+13 -2
View File
@@ -1,4 +1,4 @@
# QFT v0.4.0-rc2 implementation status
# QFT v0.4.7 implementation status
## Windows → Android optical
@@ -44,13 +44,24 @@
- [x] local cleartext network security config
- [x] local/private IPv4 + session-token validation
- [x] Parallel v2 init/chunk/finish
- [x] adaptive 4/8/16 MiB chunks
- [x] adaptive 64 KiB–16 MiB chunks, targeting eight flows per file
- [x] up to 8 Android workers per file
- [x] Windows positioned concurrent writes
- [x] temporary `.qftpart`, final SHA-256 and rename
- [x] accepted sockets return to timeout-bound blocking I/O before file transfer
- [x] loopback UDP + HTTP + out-of-order parallel integration test
- [ ] physical Windows Wi-Fi Direct adapter / driver / firewall matrix
## Windows → Android local direct
- [x] direction-specific pairing QR starts automatic local download after scan
- [x] HTTP `Range` responses return the exact requested range (`206` + `Content-Range`)
- [x] Android parallel Range downloader targets eight workers per file
- [x] adaptive 64 KiB–16 MiB chunks
- [x] `.qftpart` completion ledger resumes only verified completed ranges
- [x] five retries per range, final SHA-256, then save to `Downloads/QFT`
- [x] regression test for delayed large download after nonblocking accept
## Android compatibility
- [x] minSdk 24 (Android 7.0)
+30 -8
View File
@@ -1,13 +1,20 @@
# QFT · 超速二维码文件传输 v0.4.0-rc2
# QFT · 超速二维码文件传输 v0.4.7
Windows + Android 双向候选版。v0.4 的核心目标不是继续堆“4 码理论吞吐”,而是解决 Android 端实际识别慢的问题:**删除 2×2/4 通道,改成一个大二维码 + 动态 ROI 锁定 + 高频局部解码**。
两个方向仍然采用不同链路:
v0.4.7 提供两套互不依赖的传输方式:
- **Windows → Android:纯光学**。文件数据只经过 Windows 屏幕 → Android 摄像头;Wi‑Fi、蓝牙、局域网和互联网都不参与文件数据传输。
- **Android → Windows:扫码本地直连**。Windows 选择保存目录并启动 QFT Direct/LAN 接收服务;Android 扫码、配网、自动发现电脑,然后并行分块上传,不经过外网。
- **电脑 → 手机(纯光学)**:文件数据只经过 Windows 屏幕 → Android 摄像头;Wi‑Fi、蓝牙、局域网和互联网都不参与文件数据传输。
- **扫码本地直传(双向)**:Windows 为“手机上传”和“电脑下发”分别生成方向明确的二维码。Android 扫码后连接 QFT 本地网络、通过 UDP/网关/子网探测定位电脑,并按二维码指定方向自动进入选文件上传或接收下载;文件数据不经过外网。
> rc2 已完成协议、图像合成解码、ROI、并行上传、UDP 发现、内存预算和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
### v0.4.7 直传稳定性与并发策略
- **双向均使用并行分块**:每个可分块文件以 8 路为目标并发数;分块大小根据文件大小自适应,范围为 **64 KiB–16 MiB**。小于一个最小分块的文件会自然只有一个请求。
- **手机 → 电脑**:Android 使用 offset 定位的 Parallel v2 上传;Windows 对每块进行定位写入,重复块与完成请求可安全重试,最终以 SHA-256 校验后原子改名。
- **电脑 → 手机**:Windows 支持精确的 HTTP `Range`(`206 Partial Content`);Android 对未完成块创建多个独立 Range 请求,并用 `.qftpart` 与完成位图恢复中断传输。每块最多重试 5 次,完成后校验 SHA-256 再保存至 `Downloads/QFT`。
- **连接稳定性**:Windows 监听器保持非阻塞以便及时停止服务,但已连接的文件套接字会切换为带读写超时的阻塞模式,避免 Windows `WSAEWOULDBLOCK (10035)` 造成大文件中途失败。
> v0.4.7 已完成协议、图像合成解码、ROI、双向并发传输、UDP 发现、内存预算和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
## v0.4 光学链路改动
@@ -93,7 +100,7 @@ Windows 光传页面已经改成“二维码优先”:
推荐初次真机测试从 **30 FPS** 开始,看 Android 的“新帧/s”,再切 45、60。目标不是 Windows 数字最大,而是 Android **实际新帧/s 最大**。
## Android → Windows
## 扫码本地直传(Android ↔ Windows)
v0.3 的稳定性优化继续保留:
@@ -103,8 +110,11 @@ v0.3 的稳定性优化继续保留:
- 扫码连接后 UDP `QFTDISC2` 快速发现;
- gateway / endpoint / 当前子网 fallback;
- HTTP 请求明确绑定扫码建立的 `Network`;
- 单文件最高 8 worker 并行;
- 4/8/16 MiB 自适应上传块;
- 配网请求在传输页持续持有,仅返回首页时释放;短暂网络波动会自动接入新的 `Network`;
- 手机上传和电脑下发均以 8 路为目标并发数;
- 64 KiB–16 MiB 自适应分块;
- 电脑下发使用精确 Range 响应,手机以 `.qftpart` + 位图断点续传;
- 手机上传使用定位写入和幂等完成确认;
- Windows positioned writes + `.qftpart` + SHA-256 + 最终 rename。
## Android 版本
@@ -139,6 +149,18 @@ APK:
`android/app/build/outputs/apk/debug/app-debug.apk`
## 一键打包
脚本只打包 `windows/` 下的 Rust 桌面端:执行 `cargo test` 和 `cargo build --release`,随后把 Rust 二进制、协议说明和 SHA-256 校验文件收集到带时间戳的 `dist/QFT-Rust-*` 目录并生成压缩包。脚本不检查、下载或调用 Android SDK、Java、Gradle:
```bat
package.bat
```
```bash
./package.sh
```
## 字体
Windows UI 优先读取 `windows/assets/qft-ui.ttf`,也可用 `QFT_FONT_PATH` 指向你自己的中文 TTF。仓库不附带第三方字体文件。
+5 -5
View File
@@ -1,4 +1,4 @@
# QFT v0.4.0-rc2 test report
# QFT v0.4.7 test report
Date: 2026-08-10
@@ -6,7 +6,7 @@ This report separates **tests actually executed in the current environment** fro
## What this RC changes
The rc2 optical path is deliberately simpler than v0.3:
The v0.4.7 optical path is deliberately simpler than v0.3:
- 2×2 / 4-channel QR removed;
- one large QR only;
@@ -152,7 +152,7 @@ The guard models the Windows single-QR 1024×1024 RGBA pre-render queue:
This is a design-budget check, not an OS-enforced RSS hard cap. GPU/runtime allocators can add platform-specific memory.
## Important implementation decisions validated during rc2
## Important implementation decisions validated during v0.4.7
### QFT2 uses Result.text, not ZXing rawBytes
@@ -160,7 +160,7 @@ The active path is Base45 text. Android reconstructs the QFT binary frame from `
### Duplicate camera hits are not duplicate assembler work
At 45/60 display FPS, a camera can observe the same displayed QR in multiple exposures. rc2 still counts every successful decode in diagnostics, but only a changed QFT2 text fingerprint is delivered to `SessionAssembler`.
At 45/60 display FPS, a camera can observe the same displayed QR in multiple exposures. v0.4.7 still counts every successful decode in diagnostics, but only a changed QFT2 text fingerprint is delivered to `SessionAssembler`.
### AF/AE does not run on a fixed periodic timer
@@ -170,7 +170,7 @@ The scanner performs initial focus/metering, then re-meters after first lock or
The current generation environment does not contain the Windows MSVC Rust toolchain, Android SDK, a physical Android camera, a Windows display or a Windows Wi-Fi Direct adapter. Therefore the following are **not claimed as passed here**:
1. Windows `cargo check/test/build --release` for rc2.
1. Windows `cargo check/test/build --release` for v0.4.7.
2. Android Gradle `:app:testDebugUnitTest :app:assembleDebug` against the real Android SDK.
3. Actual 30/45/60 displayed FPS → CameraX/ZXing effective new-frame throughput.
4. Lock acquisition/reacquisition timing on Android 7 and different phone camera pipelines.
+1 -1
View File
@@ -1,4 +1,4 @@
QFT v0.4.0-rc2 test results
QFT v0.4.7 test results
UTC 2026-08-10T08:45:56Z
== protocol_selftest.py ==
+1 -1
View File
@@ -1,7 +1,7 @@
$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Host "== QFT v0.4.0-rc2 Windows host verification ==" -ForegroundColor Cyan
Write-Host "== QFT v0.4.7 Windows host verification ==" -ForegroundColor Cyan
if (Get-Command python -ErrorAction SilentlyContinue) {
Write-Host "[1/4] Core protocol/selftests"
+3 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
versionCode = 16
versionName = "0.4.0-rc8"
versionCode = 19
versionName = "0.4.7"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -40,6 +40,7 @@ android {
dependencies {
implementation("androidx.activity:activity-ktx:1.10.1")
implementation("androidx.core:core-ktx:1.15.0")
implementation("androidx.camera:camera-core:1.4.2")
implementation("androidx.camera:camera-camera2:1.4.2")
implementation("androidx.camera:camera-lifecycle:1.4.2")
+9
View File
@@ -19,6 +19,15 @@
android:label="QFT"
android:supportsRtl="true"
android:theme="@style/QftTheme">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/qft_file_paths" />
</provider>
<activity
android:name=".MainActivity"
android:exported="true"
@@ -13,9 +13,14 @@ import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.OutputStream
import java.io.RandomAccessFile
import java.net.HttpURLConnection
import java.net.URL
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
data class DownloadedFile(val name: String, val size: Long, val uri: Uri?)
@@ -24,15 +29,121 @@ data class DownloadedFile(val name: String, val size: Long, val uri: Uri?)
object DownloadClient {
private const val TAG = "QftDownload"
private const val BUFFER_SIZE = 1024 * 1024
private const val ATTEMPTS = 5
private const val SERIAL_ATTEMPTS = 3
// Kept only for the old sequential compatibility path below. New direct
// sessions always use the concurrent Range downloader.
private const val PARALLEL_MIN_FILE_SIZE = 32L * 1024L * 1024L
private const val PARALLEL_CHUNK_SIZE = 16L * 1024L * 1024L
private const val MAX_WORKERS = 8
private const val RANGE_WORKERS = 8
private const val RANGE_ATTEMPTS = 5
private const val MIN_RANGE_CHUNK = 64L * 1024L
private const val MAX_RANGE_CHUNK = 16L * 1024L * 1024L
/** 整份重下的轮数。仅在 SHA-256 不匹配(缓存已损坏)时才会用到第二轮。 */
private const val VERIFY_ROUNDS = 2
/** 落盘阶段的失败与「下载失败」是两回事,用独立异常类型区分。 */
class SaveFailure(message: String, cause: Throwable?) : Exception(message, cause)
/** Persistent received-range map. The data file is preallocated, so its
* length is not used as a completion signal; only an atomically replaced
* map entry marks a range safe to resume. */
private class ChunkLedger private constructor(
private val partial: File,
private val map: File,
private val size: Long,
val chunkSize: Long,
val totalChunks: Int,
private val completed: BooleanArray,
) {
private val lock = Any()
fun isComplete(index: Int): Boolean = synchronized(lock) { completed[index] }
fun allComplete(): Boolean = synchronized(lock) { completed.all { it } }
fun bytesComplete(): Long = synchronized(lock) {
completed.indices.sumOf { index -> if (completed[index]) chunkLength(index) else 0L }
}
fun chunkOffset(index: Int): Long = index.toLong() * chunkSize
fun chunkLength(index: Int): Long = minOf(chunkSize, size - chunkOffset(index))
fun markComplete(index: Int) = synchronized(lock) {
if (!completed[index]) {
completed[index] = true
persistLocked()
}
}
fun discard() = synchronized(lock) {
partial.delete()
map.delete()
File("${map.path}.tmp").delete()
}
private fun persistLocked() {
val temp = File("${map.path}.tmp")
temp.bufferedWriter().use { writer ->
writer.appendLine("$size:$chunkSize:$totalChunks")
writer.write(buildString(totalChunks) {
completed.forEach { append(if (it) '1' else '0') }
})
}
if (map.exists()) map.delete()
if (!temp.renameTo(map)) {
temp.copyTo(map, overwrite = true)
temp.delete()
}
}
companion object {
fun open(partial: File, size: Long, chunkSize: Long): ChunkLedger {
val totalLong = if (size == 0L) 0L else (size + chunkSize - 1L) / chunkSize
require(totalLong <= Int.MAX_VALUE) { "文件分块数过大" }
val total = totalLong.toInt()
val map = File("${partial.path}.map")
val restored = runCatching {
val pieces = map.readText().split('\n', limit = 2)
val header = pieces.firstOrNull()?.split(':') ?: emptyList()
val bits = pieces.getOrNull(1).orEmpty()
if (
partial.length() == size && header.size == 3 &&
header[0].toLong() == size && header[1].toLong() == chunkSize &&
header[2].toInt() == total && bits.length >= total
) {
BooleanArray(total) { bits[it] == '1' }
} else {
null
}
}.getOrNull()
val ledger = ChunkLedger(partial, map, size, chunkSize, total, restored ?: BooleanArray(total))
if (restored == null) {
partial.parentFile?.let { if (!it.exists()) it.mkdirs() }
RandomAccessFile(partial, "rw").use { file ->
file.setLength(0L)
file.setLength(size)
}
ledger.persistLocked()
}
return ledger
}
}
}
fun download(
context: Context,
resolver: ContentResolver,
network: Network?,
networkProvider: () -> 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)
@@ -41,27 +152,78 @@ object DownloadClient {
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()
if (partial.length() > expectedSize) discardTransferState(partial)
// 落盘时缓存文件与目标文件同时存在,需要约 2 倍空间。
// 不预检的话,这里会在下载 100% 之后才失败,用户看到的是「快结束时失败」。
ensureSpaceForTransfer(partial, expectedSize)
repeat(VERIFY_ROUNDS) { round ->
receiveUntilComplete(networkProvider, 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)
}
discardTransferState(partial)
Log.i(TAG, "completed size=$expectedSize")
return result
}
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
discardTransferState(partial)
if (round + 1 >= VERIFY_ROUNDS) {
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码")
}
onPhase("校验未通过,正在重新完整下载…")
}
error("下载未能完成")
}
/** 传输阶段:断点续传 + 有限重试。只有这一段的失败才算「下载失败」。 */
@Suppress("unused")
private fun receiveSequentialCompatibility(
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
if (expectedSize >= PARALLEL_MIN_FILE_SIZE && expectedSize > 0L) {
receiveParallel(networkProvider, baseUrl, pairing, deviceName, partial,
expectedSize, abortReason, onProgress)
return
}
var last: Exception? = null
repeat(ATTEMPTS) { attempt ->
repeat(SERIAL_ATTEMPTS) { attempt ->
abortReason()?.let { throw IllegalStateException(it, last) }
try {
Log.i(TAG, "attempt=${attempt + 1}/$ATTEMPTS partial=${partial.length()}/$expectedSize endpoint=$baseUrl")
Log.i(TAG, "serial attempt=${attempt + 1}/$SERIAL_ATTEMPTS partial=${partial.length()}/$expectedSize endpoint=$baseUrl")
if (partial.length() < expectedSize) {
receiveAttempt(network, baseUrl, pairing, deviceName, partial, expectedSize, onProgress)
receiveAttempt(networkProvider(), 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)
if (attempt + 1 < ATTEMPTS) {
Log.w(TAG, "serial attempt=${attempt + 1}/$SERIAL_ATTEMPTS failed partial=${partial.length()}/$expectedSize: ${failureDetail(e)}", e)
abortReason()?.let { throw IllegalStateException(it, e) }
if (attempt + 1 < SERIAL_ATTEMPTS) {
try {
Thread.sleep(250L * (attempt + 1))
} catch (interrupted: InterruptedException) {
@@ -71,7 +233,226 @@ object DownloadClient {
}
}
}
throw IllegalStateException("从电脑下载失败,已重试 $ATTEMPTS 次:${failureDetail(last)}", last)
val progressed = partial.length()
throw IllegalStateException(
"从电脑下载失败(断点 ${progressed}/$expectedSize 字节):${failureDetail(last)}",
last,
)
}
/**
* 大文件并行直传。每个 worker 请求一个有界 HTTP Range,并写入预分配文件的
* 固定 offset。完成位图单独落盘,所以应用进程或某条 TCP 流中断后只补缺块,
* 不会把 1 GB 文件从头再传一遍。
*/
private fun receiveParallel(
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
val totalChunks = ((expectedSize + PARALLEL_CHUNK_SIZE - 1L) / PARALLEL_CHUNK_SIZE).toInt()
val mapFile = completionMapFile(partial)
val completed = loadCompletionMap(mapFile, totalChunks)
// A partial from the old sequential downloader has no bitmap. Preserve
// only complete chunks; an incomplete tail is safely downloaded again.
val oldLength = partial.length()
if (!mapFile.exists() && oldLength in 1 until expectedSize) {
for (index in completed.indices) {
val endExclusive = minOf(expectedSize, (index + 1L) * PARALLEL_CHUNK_SIZE)
if (endExclusive <= oldLength) completed[index] = true
}
}
RandomAccessFile(partial, "rw").use { it.setLength(expectedSize) }
persistCompletionMap(mapFile, completed)
val initialBytes = completed.indices.sumOf { index ->
if (completed[index]) chunkLength(index, expectedSize) else 0L
}
val received = AtomicLong(initialBytes)
val lastReport = AtomicLong(0L)
val next = AtomicInteger(0)
onProgress(initialBytes, expectedSize)
val workers = totalChunks.coerceAtMost(
Runtime.getRuntime().availableProcessors().coerceIn(2, MAX_WORKERS)
).coerceAtLeast(1)
Log.i(TAG, "parallel download chunks=$totalChunks workers=$workers completed=$initialBytes/$expectedSize")
val pool = Executors.newFixedThreadPool(workers)
val futures = (0 until workers).map {
pool.submit {
RandomAccessFile(partial, "rw").use { output ->
while (!Thread.currentThread().isInterrupted) {
abortReason()?.let { error(it) }
val index = next.getAndIncrement()
if (index >= totalChunks) break
if (completed[index]) continue
val start = index.toLong() * PARALLEL_CHUNK_SIZE
val length = chunkLength(index, expectedSize)
receiveRangeWithRetry(
networkProvider, baseUrl, pairing, deviceName,
output, index, start, length, expectedSize, abortReason,
)
// Data reaches stable storage before its completion bit.
// A crash can therefore only cause a harmless re-download.
output.fd.sync()
synchronized(completed) {
completed[index] = true
persistCompletionMap(mapFile, completed)
}
val done = received.addAndGet(length)
val now = android.os.SystemClock.elapsedRealtime()
val previous = lastReport.get()
if (now - previous >= 80L && lastReport.compareAndSet(previous, now)) {
onProgress(done.coerceAtMost(expectedSize), expectedSize)
}
}
}
}
}
val failures = mutableListOf<Throwable>()
try {
futures.forEach { future ->
try { future.get() } catch (e: Exception) { failures += (e.cause ?: e) }
}
} finally {
pool.shutdownNow()
}
if (failures.isNotEmpty()) throw IllegalStateException(
"并行直传中断,已完成 ${received.get()}/$expectedSize 字节;下次将只补传缺块:${failureDetail(failures.first())}",
failures.first(),
)
if (completed.any { !it }) error("并行直传结束但仍有缺块")
onProgress(expectedSize, expectedSize)
}
private fun receiveRangeWithRetry(
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
output: RandomAccessFile,
index: Int,
start: Long,
length: Long,
expectedSize: Long,
abortReason: () -> String?,
) {
var last: Exception? = null
repeat(RANGE_ATTEMPTS) { attempt ->
abortReason()?.let { error(it) }
try {
receiveRange(
networkProvider(), baseUrl, pairing, deviceName, output,
start, length, expectedSize, abortReason,
)
return
} catch (e: Exception) {
last = e
Log.w(TAG, "range=$index attempt=${attempt + 1}/$RANGE_ATTEMPTS failed: ${failureDetail(e)}")
if (attempt + 1 < RANGE_ATTEMPTS) {
try { Thread.sleep((200L shl attempt).coerceAtMost(3_000L)) }
catch (_: InterruptedException) {
Thread.currentThread().interrupt()
throw e
}
}
}
}
throw IllegalStateException("区段 $index 传输失败:${failureDetail(last)}", last)
}
private fun receiveRange(
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
output: RandomAccessFile,
start: Long,
length: Long,
expectedSize: Long,
abortReason: () -> String?,
) {
val end = start + length - 1L
val conn = open(network, URL("$baseUrl/qft/download"))
try {
conn.requestMethod = "GET"
conn.connectTimeout = 8_000
conn.readTimeout = 90_000
conn.useCaches = false
conn.setRequestProperty("Connection", "keep-alive")
conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8)))
conn.setRequestProperty("Range", "bytes=$start-$end")
val code = conn.responseCode
if (code != HttpURLConnection.HTTP_PARTIAL) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
error("电脑端不支持并行 Range(HTTP $code)${message?.let { ": $it" } ?: ""}")
}
val contentRange = conn.getHeaderField("Content-Range").orEmpty()
if (contentRange != "bytes $start-$end/$expectedSize") {
error("下载服务返回了无效区段:$contentRange")
}
if (conn.contentLengthLong >= 0L && conn.contentLengthLong != length) {
error("区段长度不匹配:${conn.contentLengthLong} != $length")
}
output.seek(start)
var remaining = length
conn.inputStream.use { input ->
val buffer = ByteArray(BUFFER_SIZE)
while (remaining > 0L) {
abortReason()?.let { error(it) }
val n = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
if (n < 0) error("区段提前结束:还缺 $remaining 字节")
if (n == 0) continue
output.write(buffer, 0, n)
remaining -= n.toLong()
}
}
} finally {
conn.disconnect()
}
}
private fun chunkLength(index: Int, total: Long): Long =
minOf(PARALLEL_CHUNK_SIZE, total - index.toLong() * PARALLEL_CHUNK_SIZE)
private fun completionMapFile(partial: File): File = File(partial.parentFile, partial.name + ".map")
private fun loadCompletionMap(file: File, count: Int): BooleanArray {
val result = BooleanArray(count)
val bytes = try { if (file.exists()) file.readBytes() else ByteArray(0) } catch (_: Exception) { ByteArray(0) }
if (bytes.size == count) bytes.indices.forEach { result[it] = bytes[it].toInt() == 1 }
return result
}
private fun persistCompletionMap(file: File, completed: BooleanArray) {
FileOutputStream(file, false).use { output ->
output.write(ByteArray(completed.size) { if (completed[it]) 1 else 0 })
output.fd.sync()
}
}
/** 传输 + 落盘阶段合计需要的可用空间。 */
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 +462,7 @@ object DownloadClient {
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
val requestedOffset = partial.length().coerceIn(0L, expectedSize)
@@ -88,13 +470,9 @@ object DownloadClient {
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.readTimeout = 60_000
conn.useCaches = false
conn.setRequestProperty("Connection", "close")
conn.setRequestProperty("Connection", "keep-alive")
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-")
@@ -132,6 +510,8 @@ object DownloadClient {
FileOutputStream(partial, offset > 0L).use { output ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
// 用户明确返回首页时才中止;普通 TCP 波动由 Range 续传恢复。
abortReason()?.let { error(it) }
val n = input.read(buffer)
if (n < 0) break
if (n == 0) continue
@@ -154,28 +534,217 @@ object DownloadClient {
}
}
private fun verifySha256(file: File, expectedSha: String) {
/** 校验也要报进度:大文件读一整遍是好几秒,静默的话看起来就是卡在 100%。 */
private fun receiveUntilComplete(
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
val ledger = ChunkLedger.open(partial, expectedSize, desiredRangeChunkSize(expectedSize))
val initial = ledger.bytesComplete()
onProgress(initial, expectedSize)
if (ledger.allComplete()) return
val workers = ledger.totalChunks.coerceAtMost(RANGE_WORKERS).coerceAtLeast(1)
Log.i(TAG, "parallel start: chunks=${ledger.totalChunks}, workers=$workers, completed=$initial/$expectedSize")
val pool = Executors.newFixedThreadPool(workers)
val next = AtomicInteger(0)
val futures = (0 until workers).map {
pool.submit {
while (!Thread.currentThread().isInterrupted) {
abortReason()?.let { error(it) }
val index = next.getAndIncrement()
if (index >= ledger.totalChunks) break
if (ledger.isComplete(index)) continue
receiveRangeWithRetry(
networkProvider,
baseUrl,
pairing,
deviceName,
partial,
expectedSize,
ledger,
index,
abortReason,
)
onProgress(ledger.bytesComplete(), expectedSize)
}
}
}
try {
futures.forEach { future -> future.get() }
} catch (e: Exception) {
futures.forEach { it.cancel(true) }
throw (e.cause ?: e)
} finally {
pool.shutdownNow()
}
if (!ledger.allComplete()) {
error("并行下载未完成:${ledger.bytesComplete()}/$expectedSize")
}
Log.i(TAG, "parallel complete: chunks=${ledger.totalChunks}, bytes=$expectedSize")
}
private fun receiveRangeWithRetry(
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
ledger: ChunkLedger,
index: Int,
abortReason: () -> String?,
) {
var last: Exception? = null
repeat(RANGE_ATTEMPTS) { attempt ->
abortReason()?.let { throw IllegalStateException(it, last) }
try {
receiveRange(
networkProvider(),
baseUrl,
pairing,
deviceName,
partial,
expectedSize,
ledger,
index,
)
ledger.markComplete(index)
return
} catch (e: Exception) {
last = e
Log.w(
TAG,
"range=$index/${ledger.totalChunks} attempt=${attempt + 1}/$RANGE_ATTEMPTS failed: ${failureDetail(e)}",
e,
)
if (attempt + 1 < RANGE_ATTEMPTS) {
try {
Thread.sleep(180L * (attempt + 1))
} catch (interrupted: InterruptedException) {
Thread.currentThread().interrupt()
throw e
}
}
}
}
throw IllegalStateException(
"分块 $index 下载失败,已重试 $RANGE_ATTEMPTS 次:${failureDetail(last)}",
last,
)
}
private fun receiveRange(
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
ledger: ChunkLedger,
index: Int,
) {
val offset = ledger.chunkOffset(index)
val length = ledger.chunkLength(index)
val end = offset + length - 1L
val conn = open(network, URL("$baseUrl/qft/download"))
try {
conn.requestMethod = "GET"
conn.connectTimeout = 5_000
conn.readTimeout = 20_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)))
conn.setRequestProperty("Range", "bytes=$offset-$end")
val code = conn.responseCode
if (code != HttpURLConnection.HTTP_PARTIAL) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
error("电脑下载服务未返回并行 Range(HTTP $code)${message?.let { ": $it" } ?: ""}")
}
val expectedRange = "bytes $offset-$end/$expectedSize"
if (conn.getHeaderField("Content-Range") != expectedRange) {
error("下载服务返回了无效范围:${conn.getHeaderField("Content-Range")}")
}
if (conn.contentLengthLong >= 0L && conn.contentLengthLong != length) {
error("分块 $index 长度不匹配:${conn.contentLengthLong} != $length")
}
var received = 0L
conn.inputStream.use { input ->
RandomAccessFile(partial, "rw").use { output ->
output.channel.use { channel ->
channel.position(offset)
val buffer = ByteArray(BUFFER_SIZE)
while (received < length) {
val n = input.read(buffer, 0, minOf(buffer.size.toLong(), length - received).toInt())
if (n < 0) break
if (n == 0) continue
val bytes = ByteBuffer.wrap(buffer, 0, n)
while (bytes.hasRemaining()) channel.write(bytes)
received += n.toLong()
}
channel.force(false)
}
}
}
if (received != length) error("分块 $index 提前结束:$received/$length")
Log.d(TAG, "range=$index/${ledger.totalChunks} complete bytes=$length")
} finally {
conn.disconnect()
}
}
private fun desiredRangeChunkSize(fileSize: Long): Long {
if (fileSize <= 0L) return MIN_RANGE_CHUNK
return ((fileSize + RANGE_WORKERS - 1L) / RANGE_WORKERS)
.coerceIn(MIN_RANGE_CHUNK, MAX_RANGE_CHUNK)
}
private fun discardTransferState(partial: File) {
partial.delete()
File("${partial.path}.map").delete()
File("${partial.path}.map.tmp").delete()
}
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(
resolver: ContentResolver,
partial: File,
expectedName: String,
expectedSize: Long,
onProgress: (Long, Long) -> Unit,
): DownloadedFile {
var target: DownloadTarget? = null
try {
@@ -185,12 +754,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("保存下载文件时大小发生变化")
@@ -76,9 +76,11 @@ class MainActivity : ComponentActivity() {
private lateinit var progress: ProgressBar
private var pendingPair: PairingPayload? = null
private var connectedNetwork: Network? = null
@Volatile private var connectedNetwork: Network? = null
private var connectedBaseUrl: String? = null
private val selectedFiles = mutableListOf<SelectedFile>()
private var managingFilesForPair: PairingPayload? = null
private var managingFilesForBaseUrl: String? = null
private var sendStatusText: TextView? = null
private var sendFilesText: TextView? = null
private var sendProgress: ProgressBar? = null
@@ -86,6 +88,9 @@ class MainActivity : ComponentActivity() {
private var connectingStatusText: TextView? = null
private var downloadStatusText: TextView? = null
@Volatile private var downloadRunning = false
/** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
@Volatile private var transferAbortReason: String? = null
@Volatile private var pairConnectionAttempt = 0L
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
@@ -112,13 +117,18 @@ class MainActivity : ComponentActivity() {
}
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
selectedFiles.clear()
var unknown = 0
for (uri in uris) {
val file = UploadClient.describeFile(contentResolver, uri)
if (file != null) selectedFiles += file else unknown++
if (file != null && selectedFiles.none { it.uri == file.uri }) selectedFiles += file else if (file == null) unknown++
}
renderSelectedFiles()
val pair = managingFilesForPair
val baseUrl = managingFilesForBaseUrl
if (pair != null && baseUrl != null) {
showFileSelection(pair, baseUrl)
return@registerForActivityResult
}
if (unknown > 0) {
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
} else if (selectedFiles.isNotEmpty()) {
@@ -136,6 +146,7 @@ class MainActivity : ComponentActivity() {
}
private fun showHome(message: String? = null) {
transferAbortReason = "已返回首页,传输已停止"
pairConnectionAttempt++
stopCamera()
scannerMode = ScannerMode.NONE
@@ -147,6 +158,8 @@ class MainActivity : ComponentActivity() {
downloadRunning = false
downloadStatusText = null
selectedFiles.clear()
managingFilesForPair = null
managingFilesForBaseUrl = null
val root = pageColumn()
root.addView(text("QFT", 30f, Color.WHITE, true))
@@ -172,9 +185,16 @@ class MainActivity : ComponentActivity() {
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
buttonLabel = "扫描电脑二维码",
) { requestScanner(ScannerMode.PAIR) })
root.addView(space(16))
root.addView(modeCard(
title = "接收文件柜",
badge = "Downloads/QFT · 图片/视频/PDF/Office/压缩包等",
body = "查看 QFT 已接收的文件;点击后将使用手机中可用的阅读器或播放器打开。",
buttonLabel = "打开文件柜",
) { showReceivedFiles() })
root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.4.0-rc2 · Android 7+ 到最新", 12f, MUTED))
root.addView(text("QFT v0.4.7 · Android 7+ 到最新", 12f, MUTED))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
@@ -583,6 +603,7 @@ class MainActivity : ComponentActivity() {
private fun connectPair(pair: PairingPayload) {
val attempt = ++pairConnectionAttempt
transferAbortReason = null
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
wifiConnector.connect(
pairing = pair,
@@ -592,6 +613,10 @@ class MainActivity : ComponentActivity() {
onAvailable = available@{ network ->
if (attempt != pairConnectionAttempt) return@available
connectedNetwork = network
// A retained WifiNetworkSpecifier request may deliver a fresh
// Network after a brief radio fluctuation. Do not restart the
// page or transfer; chunk retries will use this new handle.
if (connectedBaseUrl != null) return@available
transferExecutor.execute {
if (attempt != pairConnectionAttempt) return@execute
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
@@ -638,11 +663,11 @@ class MainActivity : ComponentActivity() {
},
onUnavailable = { message -> runOnUiThread {
if (attempt != pairConnectionAttempt) return@runOnUiThread
// Huawei can report onLost while a bound local-only HTTP
// socket is unwinding. Let DownloadClient surface its precise
// HTTP/timeout cause instead of replacing it with this generic
// message mid-retry.
// onLost is recovered inside WifiConnector. onUnavailable is
// terminal (system/user rejected the retained request), so it
// is the only network callback that aborts an active transfer.
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && downloadRunning) {
transferAbortReason = message
downloadStatusText?.apply {
text = "QFT 本地网络已断开,正在结束当前下载请求…"
setTextColor(WARNING)
@@ -682,8 +707,8 @@ class MainActivity : ComponentActivity() {
private fun showPairError(pair: PairingPayload?, message: String) {
// Do not unregister here: Android may still be displaying its
// Wi-Fi-selection sheet, and unregistering at that moment produces
// "the app cancelled the device selection request". The next attempt
// (or returning home) releases the previous request safely.
// "the app cancelled the device selection request". A retry reuses
// this retained request; returning home is what explicitly releases it.
pairConnectionAttempt++
connectedNetwork = null
connectedBaseUrl = null
@@ -695,7 +720,7 @@ class MainActivity : ComponentActivity() {
root.addView(button("重试连接").apply { setOnClickListener { ensureWifiPermissionThenConnect(pair) } })
root.addView(space(10))
}
root.addView(button("重新扫码").apply { setOnClickListener { requestScanner(ScannerMode.PAIR) } })
root.addView(button("返回首页重新扫码").apply { setOnClickListener { showHome() } })
root.addView(space(10))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
@@ -709,29 +734,32 @@ class MainActivity : ComponentActivity() {
root.addView(card().apply {
addView(text("连接状态", 14f, MUTED))
addView(text("● 本地直连已就绪", 17f, SUCCESS, true), matchWrap(top = 8))
addView(text(if (pair.version >= 2) "Parallel v2 · 自适应最高 8 路并发 · 4/8/16 MiB 自适应分块" else "兼容单流模式", 13f, ACCENT), matchWrap(top = 5))
addView(text(if (pair.version >= 2) "Parallel v2 · 目标 8 路并发 · 64 KiB–16 MiB 自适应分块" else "兼容单流模式", 13f, ACCENT), matchWrap(top = 5))
addView(text("目标:$baseUrl", 12f, MUTED), matchWrap(top = 6))
pair.wifi?.let { addView(text("QFT 临时网络:${it.ssid}", 12f, MUTED), matchWrap(top = 4)) }
})
root.addView(space(14))
root.addView(card().apply {
addView(text("选择文件", 17f, Color.WHITE, true))
sendFilesText = text("尚未选择文件", 14f, MUTED)
sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
addView(sendFilesText, matchWrap(top = 8))
addView(button("选择文件(可多选)").apply {
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
setOnClickListener { showFileSelection(pair, baseUrl) }
}, matchWrap(top = 12))
})
root.addView(space(14))
root.addView(card().apply {
addView(text("传输进度", 17f, Color.WHITE, true))
sendStatusText = text("选择文件后点击开始传输", 14f, MUTED)
sendStatusText = text("请先选择需要传输的文件,再点击“开始传输”", 14f, WARNING)
addView(sendStatusText, matchWrap(top = 8))
sendProgress = ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
addView(sendProgress, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
sendButton = button("开始传输").apply {
isEnabled = selectedFiles.isNotEmpty()
setOnClickListener { startUploads(pair, baseUrl) }
sendButton = button("选择传输文件").apply {
isEnabled = connectedBaseUrl != null
setOnClickListener {
if (selectedFiles.isEmpty()) showFileSelection(pair, baseUrl)
else startUploads(pair, baseUrl)
}
}
addView(sendButton, matchWrap(top = 14))
})
@@ -750,7 +778,13 @@ class MainActivity : ComponentActivity() {
root.addView(space(18))
root.addView(card().apply {
addView(text("扫码配置已完成", 17f, SUCCESS, true))
addView(text("电脑已自动确认会话,正在通过本地网络直接传输。", 14f, MUTED), matchWrap(top = 8))
addView(text(
if (total >= 32L * 1024L * 1024L)
"连接将保持到返回首页;正在通过本地网络进行最高 8 路并行直传。"
else
"连接将保持到返回首页;正在通过本地网络直接传输。",
14f, MUTED,
), matchWrap(top = 8))
addView(text(fileName, 15f, Color.WHITE), matchWrap(top = 12))
addView(text(humanBytes(total), 13f, MUTED), matchWrap(top = 4))
})
@@ -765,23 +799,33 @@ class MainActivity : ComponentActivity() {
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
downloadRunning = true
transferAbortReason = null
transferExecutor.execute {
// 「传输 / 校验 / 保存」三个阶段各自的速率含义不同,
// 每进入一个新阶段就重新计时,否则显示出来的速率毫无意义。
var phaseLabel = "正在接收"
var phaseStartedAt = android.os.SystemClock.elapsedRealtime()
try {
val startedAt = android.os.SystemClock.elapsedRealtime()
val saved = DownloadClient.download(
context = this@MainActivity,
resolver = contentResolver,
network = connectedNetwork,
networkProvider = { connectedNetwork },
baseUrl = baseUrl,
pairing = pair,
deviceName = receiverDeviceLabel,
abortReason = { transferAbortReason },
onPhase = { label ->
phaseLabel = label
phaseStartedAt = android.os.SystemClock.elapsedRealtime()
runOnUiThread { status.text = label }
},
) { received, expected ->
runOnUiThread {
val fraction = if (expected <= 0) 0 else ((received * 1000L) / expected).toInt().coerceIn(0, 1000)
val elapsed = (android.os.SystemClock.elapsedRealtime() - startedAt).coerceAtLeast(1L)
val elapsed = (android.os.SystemClock.elapsedRealtime() - phaseStartedAt).coerceAtLeast(1L)
val rate = received * 1000.0 / elapsed
bar.progress = fraction
status.text = "${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
status.text = "$phaseLabel ${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
}
}
runOnUiThread {
@@ -792,7 +836,9 @@ class MainActivity : ComponentActivity() {
} catch (e: Exception) {
runOnUiThread {
downloadRunning = false
showPairError(pair, "从电脑接收失败:${e.message}")
// 落盘失败时文件其实已经完整收到了,别再说「接收失败」误导用户
val prefix = if (e is DownloadClient.SaveFailure) "保存失败" else "从电脑接收失败"
showPairError(pair, "$prefix:${e.message}")
}
} finally {
downloadRunning = false
@@ -800,10 +846,118 @@ class MainActivity : ComponentActivity() {
}
}
private fun showReceivedFiles(message: String? = null) {
val root = pageColumn()
root.addView(text("接收文件柜", 28f, Color.WHITE, true))
root.addView(text("QFT 已保存到 Downloads/QFT 的文件", 14f, MUTED))
message?.let { root.addView(text(it, 13f, WARNING), matchWrap(top = 10)) }
root.addView(space(16))
val files = try {
ReceivedFileCabinet.list(this)
} catch (e: Exception) {
emptyList()
}
if (files.isEmpty()) {
root.addView(card().apply {
addView(text("文件柜为空", 17f, Color.WHITE, true))
addView(text("完成电脑下发或光学接收后,文件会自动出现在这里。", 14f, MUTED), matchWrap(top = 8))
})
} else {
root.addView(text("共 ${files.size} 个文件", 13f, ACCENT, true))
files.forEach { file ->
val entry = card()
entry.addView(text(file.name, 16f, Color.WHITE, true))
entry.addView(
text("${humanBytes(file.size)} · ${file.mimeType.ifBlank { "未知格式" }}", 12f, MUTED),
matchWrap(top = 5),
)
entry.addView(button("打开文件").apply {
setOnClickListener {
try {
ReceivedFileCabinet.open(this@MainActivity, file)
} catch (e: Exception) {
showReceivedFiles("无法打开 ${file.name}:请安装支持该格式的阅读器。")
}
}
}, matchWrap(top = 10))
root.addView(entry, matchWrap(bottom = 10))
}
}
root.addView(space(12))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun showFileSelection(pair: PairingPayload, baseUrl: String) {
managingFilesForPair = pair
managingFilesForBaseUrl = baseUrl
val root = pageColumn()
root.addView(text("选择发送文件", 28f, Color.WHITE, true))
root.addView(text("可多次添加文件,并在列表中单独移除。", 14f, MUTED))
root.addView(space(14))
val total = selectedFiles.sumOf { it.size }
root.addView(card().apply {
addView(text("已选 ${selectedFiles.size} 个 · ${humanBytes(total)}", 16f, ACCENT, true))
if (selectedFiles.isEmpty()) {
addView(text("请先选择需要传输的文件", 14f, WARNING), matchWrap(top = 8))
} else {
selectedFiles.toList().forEach { file ->
val row = LinearLayout(this@MainActivity).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
}
row.addView(
text("${file.name}\n${humanBytes(file.size)}", 14f, Color.WHITE),
LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) },
)
row.addView(button("移除").apply {
setOnClickListener {
selectedFiles.removeAll { it.uri == file.uri }
showFileSelection(pair, baseUrl)
}
}, LinearLayout.LayoutParams(dp(82), dp(44)))
addView(row, matchWrap(top = 10))
}
}
})
root.addView(space(14))
root.addView(button("添加文件(可多选)").apply {
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
})
if (selectedFiles.isNotEmpty()) {
root.addView(space(10))
root.addView(button("清空选择").apply {
setOnClickListener {
selectedFiles.clear()
showFileSelection(pair, baseUrl)
}
})
}
root.addView(space(10))
root.addView(button("完成并返回传输").apply {
isEnabled = selectedFiles.isNotEmpty()
setOnClickListener {
managingFilesForPair = null
managingFilesForBaseUrl = null
showSendReady(pair, baseUrl)
}
})
root.addView(space(10))
root.addView(button("取消并返回传输").apply {
setOnClickListener {
managingFilesForPair = null
managingFilesForBaseUrl = null
showSendReady(pair, baseUrl)
}
})
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun renderSelectedFiles() {
val total = selectedFiles.sumOf { it.size }
sendFilesText?.text = if (selectedFiles.isEmpty()) {
"尚未选择文件"
"请先选择需要传输的文件"
} else {
buildString {
selectedFiles.take(8).forEach { append("• ${it.name} ${humanBytes(it.size)}\n") }
@@ -811,11 +965,17 @@ class MainActivity : ComponentActivity() {
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
}.trim()
}
sendButton?.isEnabled = selectedFiles.isNotEmpty() && connectedBaseUrl != null
sendButton?.text = if (selectedFiles.isEmpty()) "选择传输文件" else "开始传输"
sendButton?.isEnabled = connectedBaseUrl != null
}
private fun startUploads(pair: PairingPayload, baseUrl: String) {
if (selectedFiles.isEmpty()) return
if (selectedFiles.isEmpty()) {
sendStatusText?.setTextColor(WARNING)
sendStatusText?.text = "请先选择需要传输的文件"
showFileSelection(pair, baseUrl)
return
}
val files = selectedFiles.toList()
sendButton?.isEnabled = false
transferExecutor.execute {
@@ -828,11 +988,12 @@ class MainActivity : ComponentActivity() {
}
UploadClient.upload(
resolver = contentResolver,
network = connectedNetwork,
networkProvider = { connectedNetwork },
baseUrl = baseUrl,
pairing = pair,
deviceName = receiverDeviceLabel,
file = file,
abortReason = { transferAbortReason },
) { sent, total ->
runOnUiThread {
val p = if (total == 0L) 1000 else ((sent.toDouble() / total) * 1000).toInt().coerceIn(0, 1000)
@@ -0,0 +1,102 @@
package com.qft.optical
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import java.io.File
data class ReceivedFile(
val uri: Uri,
val name: String,
val size: Long,
val mimeType: String,
val modifiedAtSeconds: Long,
)
/** Lists only the files QFT has finished writing to Downloads/QFT. */
object ReceivedFileCabinet {
private const val RELATIVE_QFT_PATH = "Download/QFT/"
fun list(context: Context): List<ReceivedFile> =
if (Build.VERSION.SDK_INT >= 29) listModern(context.contentResolver) else listLegacy(context)
fun open(context: Context, file: ReceivedFile) {
val resolvedMime = mimeFor(file.name, file.mimeType)
val intent = Intent(Intent.ACTION_VIEW)
.setDataAndType(file.uri, resolvedMime)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(Intent.createChooser(intent, "打开 ${file.name}"))
}
private fun listModern(resolver: ContentResolver): List<ReceivedFile> {
val projection = arrayOf(
MediaStore.Downloads._ID,
MediaStore.Downloads.DISPLAY_NAME,
MediaStore.Downloads.SIZE,
MediaStore.Downloads.MIME_TYPE,
MediaStore.Downloads.DATE_MODIFIED,
)
val out = mutableListOf<ReceivedFile>()
resolver.query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
projection,
"${MediaStore.Downloads.RELATIVE_PATH}=? AND ${MediaStore.Downloads.IS_PENDING}=0",
arrayOf(RELATIVE_QFT_PATH),
"${MediaStore.Downloads.DATE_MODIFIED} DESC",
)?.use { cursor ->
val idIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID)
val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.SIZE)
val mimeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.MIME_TYPE)
val timeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DATE_MODIFIED)
while (cursor.moveToNext()) {
val id = cursor.getLong(idIndex)
val name = cursor.getString(nameIndex).orEmpty().ifBlank { "未命名文件" }
out += ReceivedFile(
uri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, id),
name = name,
size = cursor.getLong(sizeIndex).coerceAtLeast(0L),
mimeType = cursor.getString(mimeIndex).orEmpty(),
modifiedAtSeconds = cursor.getLong(timeIndex),
)
}
}
return out
}
@Suppress("DEPRECATION")
private fun listLegacy(context: Context): List<ReceivedFile> {
val directory = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"QFT",
)
return directory.listFiles()
?.asSequence()
?.filter { it.isFile }
?.sortedByDescending { it.lastModified() }
?.map { file ->
ReceivedFile(
uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file),
name = file.name,
size = file.length().coerceAtLeast(0L),
mimeType = mimeFor(file.name, ""),
modifiedAtSeconds = file.lastModified() / 1000L,
)
}
?.toList()
.orEmpty()
}
private fun mimeFor(name: String, supplied: String): String {
if (supplied.isNotBlank() && supplied != "application/octet-stream") return supplied
val extension = name.substringAfterLast('.', "").lowercase()
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
}
}
@@ -5,6 +5,7 @@ import android.database.Cursor
import android.net.Network
import android.net.Uri
import android.provider.OpenableColumns
import android.util.Log
import org.json.JSONObject
import java.io.FileInputStream
import java.net.DatagramPacket
@@ -19,25 +20,27 @@ import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import java.util.UUID
data class SelectedFile(
val uri: Uri,
val name: String,
val size: Long,
val uploadKey: String = UUID.randomUUID().toString(),
)
object UploadClient {
private const val TAG = "QftUpload"
private const val DISCOVERY_PORT = 39392
private const val CHUNK_SMALL = 4L * 1024L * 1024L
private const val CHUNK_DEFAULT = 8L * 1024L * 1024L
private const val CHUNK_LARGE = 16L * 1024L * 1024L
private const val MAX_WORKERS = 8
private const val MIN_PARALLEL_CHUNK = 64L * 1024L
private const val MAX_PARALLEL_CHUNK = 16L * 1024L * 1024L
private const val STREAM_BUFFER = 1024 * 1024
// QFT Direct can briefly reset a TCP flow while the Android network route
// settles. Chunk PUTs and the init/finish control calls are safe to retry;
// the Windows receiver treats a repeated chunk as an idempotent success.
private const val LOCAL_REQUEST_ATTEMPTS = 3
private const val LOCAL_REQUEST_ATTEMPTS = 8
fun describeFile(resolver: ContentResolver, uri: Uri): SelectedFile? {
var name = "qft-upload.bin"
@@ -215,16 +218,17 @@ object UploadClient {
fun upload(
resolver: ContentResolver,
network: Network?,
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
abortReason: () -> String? = { null },
onProgress: (sent: Long, total: Long) -> Unit,
) {
if (pairing.version >= 2 && isSeekable(resolver, file)) {
try {
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
uploadParallel(resolver, networkProvider, baseUrl, pairing, deviceName, file, abortReason, onProgress)
return
} catch (e: Exception) {
// Never mask a transient v2 failure by immediately switching to a
@@ -236,50 +240,90 @@ object UploadClient {
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
}
}
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
Log.i(TAG, "using compatibility single-stream upload: size=${file.size}, endpoint=$baseUrl")
uploadLegacy(resolver, networkProvider(), baseUrl, pairing, deviceName, file, abortReason, onProgress)
}
private data class InitReply(val uploadId: String, val chunkSize: Long, val totalChunks: Int)
private data class InitReply(
val uploadId: String,
val chunkSize: Long,
val totalChunks: Int,
val pendingChunks: IntArray,
)
private fun <T> retryLocalRequest(label: String, block: () -> T): T {
private fun <T> retryLocalRequest(label: String, abortReason: () -> String?, block: () -> T): T {
var last: Throwable? = null
repeat(LOCAL_REQUEST_ATTEMPTS) { attempt ->
abortReason()?.let { throw IllegalStateException(it, last) }
try {
return block()
} catch (e: Throwable) {
last = e
Log.w(
TAG,
"$label: attempt=${attempt + 1}/$LOCAL_REQUEST_ATTEMPTS, ${failureSummary(e)}",
e,
)
if (attempt + 1 < LOCAL_REQUEST_ATTEMPTS) {
try { Thread.sleep(120L * (attempt + 1)) } catch (_: InterruptedException) {
try { Thread.sleep((250L shl attempt).coerceAtMost(3_000L)) } catch (_: InterruptedException) {
Thread.currentThread().interrupt()
throw e
}
}
}
}
throw IllegalStateException("$label after $LOCAL_REQUEST_ATTEMPTS attempts", last)
val failure = last ?: IllegalStateException("unknown local request failure")
throw IllegalStateException(
"$label,已重试 $LOCAL_REQUEST_ATTEMPTS 次:${failureSummary(failure)}",
failure,
)
}
private fun failureSummary(error: Throwable): String {
val chain = ArrayList<String>(3)
var current: Throwable? = error
while (current != null && chain.size < 3) {
val type = current.javaClass.simpleName.ifBlank { current.javaClass.name }
val detail = current.message?.replace(Regex("\\s+"), " ")?.take(240)
chain += if (detail.isNullOrBlank()) type else "$type: $detail"
current = current.cause
}
return chain.joinToString(" <- ")
}
private fun uploadParallel(
resolver: ContentResolver,
network: Network?,
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
abortReason: () -> String?,
onProgress: (sent: Long, total: Long) -> Unit,
) {
val init = initUpload(network, baseUrl, pairing, deviceName, file)
Log.i(TAG, "parallel init: size=${file.size}, endpoint=$baseUrl")
val init = initUpload(networkProvider, baseUrl, pairing, deviceName, file, file.uploadKey, abortReason)
Log.i(TAG, "parallel init complete: chunks=${init.totalChunks}, pending=${init.pendingChunks.size}, chunkSize=${init.chunkSize}")
if (init.totalChunks == 0) {
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
finishUpload(networkProvider, baseUrl, pairing, deviceName, init.uploadId, abortReason)
onProgress(0, 0)
return
}
val cpuWorkers = Runtime.getRuntime().availableProcessors().coerceIn(2, MAX_WORKERS)
val workerCount = init.totalChunks.coerceAtMost(cpuWorkers).coerceAtLeast(1)
// Upload workers are network/disk bound, not CPU bound. Large files
// therefore use all eight lanes even on a 4-core phone.
if (init.pendingChunks.isEmpty()) {
finishUpload(networkProvider, baseUrl, pairing, deviceName, init.uploadId, abortReason)
onProgress(file.size, file.size)
return
}
val workerCount = init.pendingChunks.size.coerceAtMost(MAX_WORKERS).coerceAtLeast(1)
val pool = Executors.newFixedThreadPool(workerCount)
val next = AtomicInteger(0)
val sent = AtomicLong(0)
val pendingBytes = init.pendingChunks.sumOf { index ->
minOf(init.chunkSize, file.size - index.toLong() * init.chunkSize)
}
val sent = AtomicLong((file.size - pendingBytes).coerceAtLeast(0L))
val lastReport = AtomicLong(0)
val failures = mutableListOf<Throwable>()
val futures = (0 until workerCount).map {
@@ -289,13 +333,15 @@ object UploadClient {
val channel = input.channel
val buffer = ByteBuffer.allocate(STREAM_BUFFER)
while (!Thread.currentThread().isInterrupted) {
val index = next.getAndIncrement()
if (index >= init.totalChunks) break
abortReason()?.let { error(it) }
val pendingIndex = next.getAndIncrement()
if (pendingIndex >= init.pendingChunks.size) break
val index = init.pendingChunks[pendingIndex]
val offset = index.toLong() * init.chunkSize
val length = minOf(init.chunkSize, file.size - offset)
sendChunk(
network, baseUrl, pairing, deviceName,
init.uploadId, index, channel, offset, length, buffer,
networkProvider, baseUrl, pairing, deviceName,
init.uploadId, index, channel, offset, length, buffer, abortReason,
)
val totalSent = sent.addAndGet(length)
val now = android.os.SystemClock.elapsedRealtime()
@@ -316,22 +362,25 @@ object UploadClient {
pool.shutdownNow()
}
if (failures.isNotEmpty()) throw failures.first()
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
finishUpload(networkProvider, baseUrl, pairing, deviceName, init.uploadId, abortReason)
onProgress(file.size, file.size)
}
private fun desiredChunkSize(fileSize: Long): Long = when {
fileSize < 32L * 1024L * 1024L -> CHUNK_SMALL
fileSize >= 512L * 1024L * 1024L -> CHUNK_LARGE
else -> CHUNK_DEFAULT
private fun desiredChunkSize(fileSize: Long): Long {
if (fileSize <= 0L) return MIN_PARALLEL_CHUNK
// Aim for eight independent HTTP flows on every transferable file.
// The floor keeps QR Direct overhead reasonable for tiny files, while
// the ceiling protects memory and TCP fairness on very large files.
return ((fileSize + MAX_WORKERS - 1) / MAX_WORKERS)
.coerceIn(MIN_PARALLEL_CHUNK, MAX_PARALLEL_CHUNK)
}
private fun initUpload(
network: Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, file: SelectedFile,
): InitReply = retryLocalRequest("本地上传初始化失败") {
val conn = open(network, URL("$baseUrl/qft/upload/init"))
networkProvider: () -> Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, file: SelectedFile, requestKey: String, abortReason: () -> String?,
): InitReply = retryLocalRequest("本地上传初始化失败", abortReason) {
val conn = open(networkProvider(), URL("$baseUrl/qft/upload/init"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
@@ -342,15 +391,27 @@ object UploadClient {
conn.setRequestProperty("X-QFT-Filename", b64(file.name))
conn.setRequestProperty("X-QFT-Size", file.size.toString())
conn.setRequestProperty("X-QFT-Chunk-Size", desiredChunkSize(file.size).toString())
conn.setRequestProperty("X-QFT-Upload-Key", requestKey)
conn.outputStream.close()
val code = conn.responseCode
if (code != 200) error("初始化并行上传失败 HTTP $code")
val body = conn.inputStream.bufferedReader().use { it.readText() }
val obj = JSONObject(body)
val totalChunks = obj.getInt("total_chunks")
val missing = obj.optJSONArray("missing")
val pending = if (missing == null) {
IntArray(totalChunks) { it }
} else {
IntArray(missing.length()) { missing.getInt(it) }
}
if (pending.any { it !in 0 until totalChunks } || pending.distinct().size != pending.size) {
error("电脑返回了无效的缺块列表")
}
InitReply(
uploadId = obj.getString("upload_id"),
chunkSize = obj.getLong("chunk_size"),
totalChunks = obj.getInt("total_chunks"),
totalChunks = totalChunks,
pendingChunks = pending,
)
} finally {
conn.disconnect()
@@ -358,16 +419,17 @@ object UploadClient {
}
private fun sendChunk(
network: Network?, baseUrl: String, pairing: PairingPayload, deviceName: String,
networkProvider: () -> Network?, baseUrl: String, pairing: PairingPayload, deviceName: String,
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
buffer: ByteBuffer,
) = retryLocalRequest("分块 $index 上传失败") {
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
buffer: ByteBuffer, abortReason: () -> String?,
) = retryLocalRequest("分块 $index 上传失败", abortReason) {
Log.d(TAG, "chunk start: index=$index, bytes=$length, endpoint=$baseUrl")
val conn = open(networkProvider(), URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 4_000
conn.readTimeout = 15_000
conn.connectTimeout = 8_000
conn.readTimeout = 90_000
conn.setFixedLengthStreamingMode(length)
conn.setRequestProperty("Content-Type", "application/octet-stream")
commonHeaders(conn, pairing, deviceName)
@@ -376,6 +438,7 @@ object UploadClient {
var remaining = length
val array = buffer.array()
while (remaining > 0) {
abortReason()?.let { error(it) }
buffer.clear()
buffer.limit(minOf(array.size.toLong(), remaining).toInt())
val n = channel.read(buffer)
@@ -391,16 +454,17 @@ object UploadClient {
error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
}
try { conn.inputStream.close() } catch (_: Exception) {}
Log.d(TAG, "chunk complete: index=$index, bytes=$length")
} finally {
conn.disconnect()
}
}
private fun finishUpload(
network: Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, uploadId: String,
) = retryLocalRequest("本地上传完成确认失败") {
val conn = open(network, URL("$baseUrl/qft/upload/finish/$uploadId"))
networkProvider: () -> Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, uploadId: String, abortReason: () -> String?,
) = retryLocalRequest("本地上传完成确认失败", abortReason) {
val conn = open(networkProvider(), URL("$baseUrl/qft/upload/finish/$uploadId"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
@@ -427,6 +491,7 @@ object UploadClient {
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
abortReason: () -> String?,
onProgress: (sent: Long, total: Long) -> Unit,
) {
val conn = open(network, URL("$baseUrl/qft/upload"))
@@ -447,6 +512,7 @@ object UploadClient {
var sent = 0L
var lastReport = 0L
while (true) {
abortReason()?.let { error(it) }
val n = input.read(buf)
if (n <= 0) break
output.write(buf, 0, n)
@@ -489,7 +555,7 @@ object UploadClient {
private fun commonHeaders(conn: HttpURLConnection, pairing: PairingPayload, deviceName: String) {
conn.useCaches = false
conn.setRequestProperty("Connection", "close")
conn.setRequestProperty("Connection", "keep-alive")
conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", b64(deviceName))
}
@@ -26,53 +26,91 @@ class WifiConnector(context: Context) {
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
private val handler = Handler(Looper.getMainLooper())
private var callback: ConnectivityManager.NetworkCallback? = null
@Volatile private var currentNetwork: Network? = null
private var generation = 0
private var legacyPreviousNetworkId: Int? = null
private var legacyTargetNetworkId: Int? = null
/**
* 回调经由这个可替换的收件人转发,而不是被 NetworkCallback 闭包捕获。
* 这样「用户点重试」时可以直接换掉 UI 回调、继续复用那个还挂着的
* WifiNetworkSpecifier 请求,不必 unregister —— 在系统选网弹窗还开着的
* 时候 unregister,Android 会弹「该应用已取消选择设备的请求」。
*/
private class Listener(
val onStatus: (String) -> Unit,
val onAvailable: (Network?) -> Unit,
val onUnavailable: (String) -> Unit,
)
private var listener: Listener? = null
private var pendingSsid: String? = null
private var pendingDelivered: AtomicBoolean? = null
private var pendingTerminal: AtomicBoolean? = null
private var pendingStartedAt = 0L
// 所有对外回调都只走这三个入口。直接调用捕获来的闭包会在「复用挂起请求」
// 时通知到上一次的界面,是很难查的一类 bug。
private fun notifyStatus(message: String) { listener?.onStatus?.invoke(message) }
private fun notifyAvailable(network: Network?) { listener?.onAvailable?.invoke(network) }
private fun notifyUnavailable(message: String) { listener?.onUnavailable?.invoke(message) }
fun connect(
pairing: PairingPayload,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
val wifi = pairing.wifi
// 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可,
// 千万不要 unregister 再重新 requestNetwork。
if (wifi != null && callback != null && pendingSsid == wifi.ssid &&
pendingTerminal?.get() == false) {
Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}")
listener = Listener(onStatus, onAvailable, onUnavailable)
val active = currentNetwork
if (active != null) {
notifyStatus("QFT 本地网络仍保持连接")
notifyAvailable(active)
} else {
notifyStatus("系统配网请求仍在进行中,正在自动恢复连接…")
scheduleWaitHints(generation, wifi.ssid)
}
return
}
release(restoreLegacy = false)
generation++
val run = generation
val wifi = pairing.wifi
listener = Listener(onStatus, onAvailable, onUnavailable)
if (wifi == null) {
onStatus("正在使用当前局域网发现电脑…")
notifyStatus("正在使用当前局域网发现电脑…")
val wifiNetwork = bestWifiNetwork()
onAvailable(wifiNetwork ?: connectivity.activeNetwork)
currentNetwork = wifiNetwork ?: connectivity.activeNetwork
notifyAvailable(currentNetwork)
return
}
if (Build.VERSION.SDK_INT >= 29) {
connectModern(run, wifi, onStatus, onAvailable, onUnavailable)
connectModern(run, wifi)
} else {
connectLegacy(run, wifi, onStatus, onAvailable, onUnavailable)
connectLegacy(run, wifi)
}
}
@RequiresApi(29)
@Suppress("MissingPermission")
private fun connectModern(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("正在请求连接 ${wifi.ssid}…")
private fun connectModern(run: Int, wifi: WifiCredentials) {
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
onStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
notifyStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
val specifier = try {
WifiNetworkSpecifier.Builder()
.setSsid(wifi.ssid)
.setWpa2Passphrase(wifi.passphrase)
.build()
} catch (e: Exception) {
onUnavailable("配网参数无效:${e.message}")
notifyUnavailable("配网参数无效:${e.message}")
return
}
val request = NetworkRequest.Builder()
@@ -86,39 +124,66 @@ class WifiConnector(context: Context) {
// launching a duplicate probe/download for the same Wi-Fi connection.
val delivered = AtomicBoolean(false)
val terminal = AtomicBoolean(false)
pendingSsid = wifi.ssid
pendingDelivered = delivered
pendingTerminal = terminal
pendingStartedAt = SystemClock.elapsedRealtime()
val startedAt = pendingStartedAt
val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (run != generation || terminal.get()) return
currentNetwork = network
Log.i(TAG, "attempt=$run framework onAvailable network=$network")
onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, onStatus) {
if (run == generation && !terminal.get() && delivered.compareAndSet(false, true)) {
notifyStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, ::notifyStatus) {
if (run == generation && !terminal.get() && currentNetwork == network &&
delivered.compareAndSet(false, true)) {
Log.i(TAG, "attempt=$run route ready network=$network")
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT 本地网络已就绪,正在快速发现电脑…")
notifyAvailable(network)
}
}
}
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
if (run != generation || terminal.get() || delivered.get()) return
if (run != generation || terminal.get() || delivered.get() || currentNetwork != network) return
if (hasIpv4(linkProperties) && delivered.compareAndSet(false, true)) {
currentNetwork = network
Log.i(TAG, "attempt=$run IPv4 ready network=$network")
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT 本地网络已就绪,正在快速发现电脑…")
notifyAvailable(network)
}
}
override fun onUnavailable() {
if (run != generation || !terminal.compareAndSet(false, true)) return
Log.w(TAG, "attempt=$run framework onUnavailable")
if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。")
currentNetwork = null
val waited = SystemClock.elapsedRealtime() - startedAt
Log.w(TAG, "attempt=$run framework onUnavailable after ${waited}ms")
// Android 不区分「用户点了取消」和「始终没扫到这个热点」,
// 只能用等待时长推断,给出真正能指导用户下一步的提示。
notifyUnavailable(
if (waited < 4_000L) {
"已取消系统配网。请重新点击「重试连接」,并在系统弹窗里选择 ${wifi.ssid} 后点连接。"
} else {
"系统始终没有搜索到热点 ${wifi.ssid}。请确认:" +
"① 电脑上 QFT 接收页仍开着且显示 Direct 已启动;" +
"② 手机 Wi-Fi 列表里能看到这个名字;" +
"③ 电脑与手机距离不要太远。"
}
)
}
override fun onLost(network: Network) {
if (run != generation || !delivered.get() || !terminal.compareAndSet(false, true)) return
if (run != generation || terminal.get() || currentNetwork != network) return
Log.w(TAG, "attempt=$run network lost network=$network")
if (run == generation && delivered.get()) onUnavailable("QFT 临时网络已断开")
currentNetwork = null
delivered.set(false)
// requestNetwork stays registered. Android can therefore
// deliver a replacement Network without another system picker;
// range/chunk retries wait for and then use that new handle.
notifyStatus("QFT 网络短暂波动,正在保持会话并自动恢复…")
}
}
callback = cb
@@ -130,26 +195,37 @@ class WifiConnector(context: Context) {
// system sheet; otherwise keep this request alive while our page
// continues to show connection progress.
connectivity.requestNetwork(request, cb)
handler.postDelayed({
if (run == generation && !terminal.get() && !delivered.get()) {
onStatus("仍在等待系统完成配网…")
}
}, 8_000)
scheduleWaitHints(run, wifi.ssid)
} catch (e: Exception) {
callback = null
onUnavailable("系统配网请求失败:${e.message}")
pendingSsid = null
notifyUnavailable("系统配网请求失败:${e.message}")
}
}
/**
* 弹窗久久不出结果时逐级给出更具体的提示。
* 截图里那种「弹窗一直转圈」的情况,光说「仍在等待系统完成配网」
* 完全没有指导意义——真正的原因通常是电脑侧热点没起来。
*/
private fun scheduleWaitHints(run: Int, ssid: String) {
fun pending(): Boolean =
run == generation && pendingTerminal?.get() == false && pendingDelivered?.get() == false
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…")
}, 8_000)
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke(
"系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," +
"多半是电脑侧热点没启动——请检查 Windows 上 QFT 接收页是否显示 Direct 已就绪。"
)
}, 20_000)
}
@Suppress("DEPRECATION", "MissingPermission")
private fun connectLegacy(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
private fun connectLegacy(run: Int, wifi: WifiCredentials) {
notifyStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
try {
if (!wifiManager.isWifiEnabled) {
wifiManager.isWifiEnabled = true
@@ -168,13 +244,13 @@ class WifiConnector(context: Context) {
wifiManager.addNetwork(config)
}
if (targetId < 0) {
onUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
notifyUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
return
}
legacyTargetNetworkId = targetId
wifiManager.disconnect()
if (!wifiManager.enableNetwork(targetId, true)) {
onUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
notifyUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
return
}
wifiManager.reconnect()
@@ -186,20 +262,21 @@ class WifiConnector(context: Context) {
if (matches) {
val network = bestWifiNetwork()
if (network != null && hasIpv4(connectivity.getLinkProperties(network))) {
onStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
currentNetwork = network
notifyAvailable(network)
return
}
}
if (SystemClock.elapsedRealtime() - started > 15_000) {
onUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
notifyUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
} else {
handler.postDelayed({ poll() }, 250)
}
}
handler.postDelayed({ poll() }, 250)
} catch (e: Exception) {
onUnavailable("Android 7~9 配网失败:${e.message}")
notifyUnavailable("Android 7~9 配网失败:${e.message}")
}
}
@@ -316,6 +393,11 @@ class WifiConnector(context: Context) {
try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {}
}
callback = null
currentNetwork = null
listener = null
pendingSsid = null
pendingDelivered = null
pendingTerminal = null
handler.removeCallbacksAndMessages(null)
if (restoreLegacy && Build.VERSION.SDK_INT < 29) {
val previous = legacyPreviousNetworkId
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="qft_downloads" path="Download/QFT/" />
</paths>
+16 -4
View File
@@ -1,4 +1,4 @@
# QFT protocol notes — v0.4.0-rc2
# QFT protocol notes — v0.4.7
## 1. Windows → Android optical: QFT2
@@ -36,7 +36,7 @@ senderLen 2 u16 BE
senderDevice N UTF-8
```
### Optical parameters in rc2
### Optical parameters in v0.4.7
- one QR per display frame;
- DATA payload: **450 B**;
@@ -75,7 +75,7 @@ The overlay is derived from the same ROI used by the decoder, so the green/yello
Discovery order includes QR hint, UDP `QFTDISC2`, gateway/direct candidates and bounded current-subnet fallback.
## 4. Android → Windows upload
## 4. 扫码本地直传(Android ↔ Windows)
Parallel v2 flow:
@@ -85,4 +85,16 @@ POST /qft/upload/chunk (parallel, offset based)
POST /qft/upload/finish
```
Windows preallocates a `.qftpart`, writes chunks at explicit offsets, verifies SHA-256, then renames to the final file. Per-file worker count is capped at 8; chunk size is selected from 4/8/16 MiB by file size.
Windows preallocates a `.qftpart`, writes chunks at explicit offsets, verifies SHA-256, then renames to the final file. Uploads target 8 workers per file (bounded by the usable chunks and device capacity); the requested chunk size is derived from the file size and clamped to **64 KiB–16 MiB**. Repeated `init` requests carrying the same `X-QFT-Upload-Key` resume the matching active upload session; repeated chunk and finish requests are idempotent so a lost response can be retried safely. Chunk completion is recorded only after the positioned write reaches stable storage.
## 5. Windows → Android download
The same QFTPAIR2 local session can declare the download direction. Android discovers and verifies the Windows sender, then downloads `GET /qft/download` with exact single-range requests:
```text
Range: bytes=<start>-<end>
```
The sender returns `206 Partial Content`, the matching `Content-Range`, and the exact requested body length. Android splits the file toward 8 workers with **64 KiB–16 MiB** chunks, stores each completed chunk in a `.qftpart.map` ledger, and resumes only missing chunks after a reconnect. Each range retries with the currently available `Network`; the complete partial file must pass SHA-256 before it is published to `Downloads/QFT`.
For both direct-transfer directions, the Windows listener may accept connections non-blockingly for shutdown responsiveness, but each accepted file socket is switched to blocking I/O with explicit timeouts before reading or writing request bodies. This prevents `WSAEWOULDBLOCK (10035)` from turning an in-progress parallel transfer into an HTTP 500 failure.
+76 -64
View File
@@ -7,35 +7,35 @@
objects = {
/* Begin PBXBuildFile section */
0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */; };
38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5459D124A555B0E4121361E5 /* PairingProtocol.swift */; };
4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */; };
554512A1FC8A6F66E2784787 /* QFTApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 453B172D654B3AEDE4E36D1E /* QFTApp.swift */; };
6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */; };
78FD5CF5E04D7E2483B90BAA /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */; };
978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAA81C375609633BD8DB42F3 /* DownloadClient.swift */; };
A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD16686BB19417EDC0B611A /* PeerLink.swift */; };
BDCF0D82F0BD0328770A8ABD /* ScannerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3B15455554D7647B44D5038 /* ScannerView.swift */; };
C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C628A05E9C83375781E165EB /* Assets.xcassets */; };
E26487D1146FDF6DD5F92D80 /* TransferModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3017489412A6FCAE8995B32E /* TransferModel.swift */; };
EE5510DAC5BBB7F9D41A8F26 /* Base64URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848334DC6B2D30622C7E2A45 /* Base64URL.swift */; };
38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5459D124A555B0E4121361E5 /* PairingProtocol.swift */; };
6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */; };
978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAA81C375609633BD8DB42F3 /* DownloadClient.swift */; };
0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */; };
4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */; };
A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD16686BB19417EDC0B611A /* PeerLink.swift */; };
C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C628A05E9C83375781E165EB /* Assets.xcassets */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
928818DCDA72C62B2D8288D5 /* QFT.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = QFT.app; sourceTree = BUILT_PRODUCTS_DIR; };
453B172D654B3AEDE4E36D1E /* QFTApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QFTApp.swift; sourceTree = "<group>"; };
0B6863D13BC7270D7FCE21E7 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
F3B15455554D7647B44D5038 /* ScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScannerView.swift; sourceTree = "<group>"; };
3017489412A6FCAE8995B32E /* TransferModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransferModel.swift; sourceTree = "<group>"; };
848334DC6B2D30622C7E2A45 /* Base64URL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Base64URL.swift; sourceTree = "<group>"; };
5459D124A555B0E4121361E5 /* PairingProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingProtocol.swift; sourceTree = "<group>"; };
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDiscovery.swift; sourceTree = "<group>"; };
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadClient.swift; sourceTree = "<group>"; };
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadClient.swift; sourceTree = "<group>"; };
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerPairing.swift; sourceTree = "<group>"; };
8DD16686BB19417EDC0B611A /* PeerLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerLink.swift; sourceTree = "<group>"; };
C628A05E9C83375781E165EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
0B6863D13BC7270D7FCE21E7 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
3017489412A6FCAE8995B32E /* TransferModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransferModel.swift; sourceTree = "<group>"; };
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDiscovery.swift; sourceTree = "<group>"; };
453B172D654B3AEDE4E36D1E /* QFTApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QFTApp.swift; sourceTree = "<group>"; };
5459D124A555B0E4121361E5 /* PairingProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingProtocol.swift; sourceTree = "<group>"; };
7E4A60F8CA5D515103446ED3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
848334DC6B2D30622C7E2A45 /* Base64URL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Base64URL.swift; sourceTree = "<group>"; };
8DD16686BB19417EDC0B611A /* PeerLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerLink.swift; sourceTree = "<group>"; };
928818DCDA72C62B2D8288D5 /* QFT.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = QFT.app; sourceTree = BUILT_PRODUCTS_DIR; };
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadClient.swift; sourceTree = "<group>"; };
C628A05E9C83375781E165EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadClient.swift; sourceTree = "<group>"; };
F3B15455554D7647B44D5038 /* ScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScannerView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -60,20 +60,6 @@
path = App;
sourceTree = "<group>";
};
EC599E8CF455428A5E3179CE /* Core */ = {
isa = PBXGroup;
children = (
848334DC6B2D30622C7E2A45 /* Base64URL.swift */,
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */,
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */,
5459D124A555B0E4121361E5 /* PairingProtocol.swift */,
8DD16686BB19417EDC0B611A /* PeerLink.swift */,
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */,
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */,
);
path = Core;
sourceTree = "<group>";
};
36EDFB66685EBD501D3910CE /* QFT */ = {
isa = PBXGroup;
children = (
@@ -101,12 +87,26 @@
name = Products;
sourceTree = "<group>";
};
EC599E8CF455428A5E3179CE /* Core */ = {
isa = PBXGroup;
children = (
848334DC6B2D30622C7E2A45 /* Base64URL.swift */,
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */,
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */,
5459D124A555B0E4121361E5 /* PairingProtocol.swift */,
8DD16686BB19417EDC0B611A /* PeerLink.swift */,
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */,
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */,
);
path = Core;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
497CBF7ECF21FFA362230876 /* QFT */ = {
isa = PBXNativeTarget;
buildConfigurationList = A886B50DF087AEF7B87CDC65;
buildConfigurationList = A886B50DF087AEF7B87CDC65 /* Build configuration list for PBXNativeTarget "QFT" */;
buildPhases = (
C2511B36F0F0E810A9E46328 /* Sources */,
019BAB185F97B56993A7087D /* Frameworks */,
@@ -136,7 +136,7 @@
};
};
};
buildConfigurationList = 26E84C2B3712F7DFAC8AD93F;
buildConfigurationList = 26E84C2B3712F7DFAC8AD93F /* Build configuration list for PBXProject "QFT" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
@@ -188,6 +188,29 @@
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
032222C0BAA33BC7119DFAF1 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 47;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = QFT/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.4.7;
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
70DCC1EB255A5F3C8D9ED349 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -203,8 +226,11 @@
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1 $(inherited)";
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -215,25 +241,6 @@
};
name = Debug;
};
DB189EBE9D4E38495C3C7EF5 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = QFT/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 0.1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
C3DCEEC1E0EB17A5583B8E94 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -248,9 +255,10 @@
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_VERSION = 5.0;
@@ -258,29 +266,33 @@
};
name = Release;
};
032222C0BAA33BC7119DFAF1 /* Release */ = {
DB189EBE9D4E38495C3C7EF5 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 47;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = QFT/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 0.1.0;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.4.7;
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
name = Debug;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
26E84C2B3712F7DFAC8AD93F = {
26E84C2B3712F7DFAC8AD93F /* Build configuration list for PBXProject "QFT" */ = {
isa = XCConfigurationList;
buildConfigurations = (
70DCC1EB255A5F3C8D9ED349 /* Debug */,
@@ -289,7 +301,7 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A886B50DF087AEF7B87CDC65 = {
A886B50DF087AEF7B87CDC65 /* Build configuration list for PBXNativeTarget "QFT" */ = {
isa = XCConfigurationList;
buildConfigurations = (
DB189EBE9D4E38495C3C7EF5 /* Debug */,
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
+1 -1
View File
@@ -1,4 +1,4 @@
# QFT iOS 客户端 v0.1.0
# QFT iOS 客户端 v0.4.7
三种传输方式:
+2 -2
View File
@@ -19,7 +19,7 @@ IOS_ROOT = os.path.dirname(HERE)
APP_NAME = "QFT"
BUNDLE_ID = "com.qft.transfer"
DEPLOYMENT_TARGET = "17.0"
MARKETING_VERSION = "0.1.0"
MARKETING_VERSION = "0.4.7"
SOURCES = [
"QFT/App/QFTApp.swift",
@@ -280,7 +280,7 @@ def generate():
"ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon",
"ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor",
"CODE_SIGN_STYLE = Automatic",
"CURRENT_PROJECT_VERSION = 1",
"CURRENT_PROJECT_VERSION = 47",
"ENABLE_PREVIEWS = YES",
"GENERATE_INFOPLIST_FILE = NO",
"INFOPLIST_FILE = QFT/Info.plist",
+46
View File
@@ -0,0 +1,46 @@
@echo off
setlocal EnableExtensions
cd /d "%~dp0"
echo == QFT Rust one-click package ==
where cargo >nul 2>nul
if errorlevel 1 (
echo ERROR: Rust cargo was not found in PATH.
exit /b 1
)
echo [1/3] Testing and building the Rust Windows release...
pushd windows
cargo test
if errorlevel 1 (popd & exit /b 1)
cargo build --release
if errorlevel 1 (popd & exit /b 1)
popd
for /f "tokens=3" %%V in ('findstr /R /C:"^version =" "windows\Cargo.toml"') do set "QFT_VERSION=%%~V"
for /f "usebackq delims=" %%T in (`powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss"`) do set "QFT_STAMP=%%T"
if not defined QFT_VERSION set "QFT_VERSION=unknown"
set "QFT_PACKAGE=QFT-Rust-%QFT_VERSION%-%QFT_STAMP%-windows"
set "QFT_PACKAGE_DIR=%CD%\dist\%QFT_PACKAGE%"
echo [2/3] Collecting Rust artifacts...
mkdir "%QFT_PACKAGE_DIR%" || exit /b 1
copy /y "windows\target\release\qft-windows.exe" "%QFT_PACKAGE_DIR%\QFT-Windows.exe" >nul || exit /b 1
copy /y "README.md" "%QFT_PACKAGE_DIR%\README.md" >nul || exit /b 1
copy /y "TEST_REPORT.md" "%QFT_PACKAGE_DIR%\TEST_REPORT.md" >nul || exit /b 1
copy /y "docs\PROTOCOL.md" "%QFT_PACKAGE_DIR%\PROTOCOL.md" >nul || exit /b 1
echo [3/3] Writing SHA-256 checksums and ZIP archive...
powershell -NoProfile -Command ^
"$dir = [IO.Path]::GetFullPath('%QFT_PACKAGE_DIR%');" ^
"$lines = Get-ChildItem -LiteralPath $dir -File ^| Sort-Object Name ^| ForEach-Object { '{0} {1}' -f (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLower(), $_.Name };" ^
"[IO.File]::WriteAllLines((Join-Path $dir 'SHA256SUMS.txt'), $lines, [Text.UTF8Encoding]::new($false));" ^
"Compress-Archive -LiteralPath $dir -DestinationPath ($dir + '.zip') -Force"
if errorlevel 1 exit /b 1
echo.
echo PACKAGE COMPLETE
echo Folder: %QFT_PACKAGE_DIR%
echo ZIP: %QFT_PACKAGE_DIR%.zip
exit /b 0
Executable
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env sh
set -eu
QFT_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$QFT_ROOT"
echo "== QFT Rust one-click package =="
command -v cargo >/dev/null 2>&1 || { echo "ERROR: Rust cargo was not found in PATH." >&2; exit 1; }
echo "[1/3] Testing and building the Rust desktop release..."
(
cd windows
cargo test
cargo build --release
)
QFT_VERSION=$(awk -F'"' '/^\[package\]/{package=1; next} package && /^version[[:space:]]*=/{print $2; exit} /^\[/{package=0}' windows/Cargo.toml)
[ -n "$QFT_VERSION" ] || QFT_VERSION=unknown
QFT_STAMP=$(date '+%Y%m%d-%H%M%S')
QFT_PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
QFT_PACKAGE="QFT-Rust-${QFT_VERSION}-${QFT_STAMP}-${QFT_PLATFORM}"
QFT_PACKAGE_DIR="$QFT_ROOT/dist/$QFT_PACKAGE"
echo "[2/3] Collecting Rust artifacts..."
mkdir -p "$QFT_PACKAGE_DIR"
if [ -f "windows/target/release/qft-windows.exe" ]; then
cp "windows/target/release/qft-windows.exe" "$QFT_PACKAGE_DIR/QFT-Windows.exe"
elif [ -f "windows/target/release/qft-windows" ]; then
cp "windows/target/release/qft-windows" "$QFT_PACKAGE_DIR/QFT-Desktop"
else
echo "ERROR: desktop release binary was not produced." >&2
exit 1
fi
cp README.md TEST_REPORT.md "$QFT_PACKAGE_DIR/"
cp docs/PROTOCOL.md "$QFT_PACKAGE_DIR/PROTOCOL.md"
echo "[3/3] Writing SHA-256 checksums and archive..."
(
cd "$QFT_PACKAGE_DIR"
if command -v sha256sum >/dev/null 2>&1; then
sha256sum ./* > SHA256SUMS.txt
else
shasum -a 256 ./* > SHA256SUMS.txt
fi
)
tar -C "$QFT_ROOT/dist" -czf "$QFT_PACKAGE_DIR.tar.gz" "$QFT_PACKAGE"
echo
echo "PACKAGE COMPLETE"
echo "Folder: $QFT_PACKAGE_DIR"
echo "Archive: $QFT_PACKAGE_DIR.tar.gz"
+3
View File
@@ -4,6 +4,7 @@ import re
ROOT=Path(__file__).resolve().parents[1]
gradle=(ROOT/'android/app/build.gradle.kts').read_text(); manifest=(ROOT/'android/app/src/main/AndroidManifest.xml').read_text()
wifi=(ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_text(); upload=(ROOT/'android/app/src/main/java/com/qft/optical/UploadClient.kt').read_text()
download=(ROOT/'android/app/src/main/java/com/qft/optical/DownloadClient.kt').read_text()
main=(ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text(); analyzer=(ROOT/'android/app/src/main/java/com/qft/optical/QrAnalyzer.kt').read_text()
gray=(ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text(); protocol=(ROOT/'android/app/src/main/java/com/qft/optical/Protocol.kt').read_text(); base45=(ROOT/'android/app/src/main/java/com/qft/optical/Base45.kt').read_text(); overlay=(ROOT/'android/app/src/main/java/com/qft/optical/QrLockOverlay.kt').read_text(); security=(ROOT/'android/app/src/main/res/xml/network_security_config.xml').read_text()
assert re.search(r'minSdk\s*=\s*24',gradle)
@@ -12,6 +13,8 @@ assert 'ACCESS_FINE_LOCATION" android:maxSdkVersion="32"' in manifest and 'NEARB
assert 'networkSecurityConfig="@xml/network_security_config"' in manifest and 'cleartextTrafficPermitted="true"' in security
assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi and 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload
assert 'MAX_WORKERS = 8' in download and 'bytes=$start-$end' in download and 'completionMapFile' in download
assert 'requestNetwork(request, cb)' in wifi and 'delivered.set(false)' in wifi
assert 'val targetSize = Size(640, 480)' in main and 'Size(960, 540)' not in main
assert 'Camera2Interop.Extender' in main and 'CONTROL_AE_TARGET_FPS_RANGE' in main and 'STRATEGY_KEEP_ONLY_LATEST' in main
assert '设备拒绝显式高帧率请求' in main and 'fallbackAnalysis' in main
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Bounded Range + retry + out-of-order positioned-write download self-test."""
import hashlib
import http.client
import random
import tempfile
import threading
from concurrent.futures import ThreadPoolExecutor
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
SIZE = 64 * 1024 * 1024 + 12345
CHUNK = 16 * 1024 * 1024
WORKERS = 8
TOKEN = "parallel_download_test"
def digest(path):
value = hashlib.sha256()
with open(path, "rb", buffering=0) as stream:
while block := stream.read(4 * 1024 * 1024):
value.update(block)
return value.hexdigest()
def main():
assert (1024 * 1024 * 1024 + CHUNK - 1) // CHUNK == 64
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
source = root / "source.bin"
target = root / "target.qftpart"
pattern = bytes((index * 73 + 19) & 0xFF for index in range(1024 * 1024))
with source.open("wb", buffering=0) as stream:
remaining = SIZE
while remaining:
block = pattern[:min(len(pattern), remaining)]
stream.write(block)
remaining -= len(block)
with target.open("wb") as stream:
stream.truncate(SIZE)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
if self.path != "/qft/download" or self.headers.get("X-QFT-Token") != TOKEN:
self.send_error(403)
return
value = self.headers.get("Range", "")
assert value.startswith("bytes=") and "-" in value
start_text, end_text = value[6:].split("-", 1)
start, end = int(start_text), int(end_text)
assert 0 <= start <= end < SIZE
length = end - start + 1
self.send_response(206)
self.send_header("Content-Length", str(length))
self.send_header("Content-Range", f"bytes {start}-{end}/{SIZE}")
self.end_headers()
with source.open("rb", buffering=0) as stream:
stream.seek(start)
remaining = length
while remaining:
block = stream.read(min(1024 * 1024, remaining))
assert block
self.wfile.write(block)
remaining -= len(block)
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
host, port = server.server_address
indices = list(range((SIZE + CHUNK - 1) // CHUNK))
random.Random(42).shuffle(indices)
def receive(index):
start = index * CHUNK
end = min(SIZE, start + CHUNK) - 1
connection = http.client.HTTPConnection(host, port, timeout=10)
connection.request("GET", "/qft/download", headers={
"X-QFT-Token": TOKEN,
"Range": f"bytes={start}-{end}",
})
response = connection.getresponse()
assert response.status == 206
assert response.getheader("Content-Range") == f"bytes {start}-{end}/{SIZE}"
offset = start
with target.open("r+b", buffering=0) as output:
output.seek(start)
while block := response.read(1024 * 1024):
assert output.write(block) == len(block)
offset += len(block)
connection.close()
assert offset == end + 1
try:
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
list(pool.map(receive, indices))
finally:
server.shutdown()
server.server_close()
assert digest(source) == digest(target)
print(f"PASS parallel download: {SIZE} bytes, 16 MiB bounded ranges, {WORKERS} workers, SHA-256 identical; 1 GiB maps to 64 resumable ranges")
if __name__ == "__main__":
main()
+1
View File
@@ -7,6 +7,7 @@ scripts = [
'optical_image_decode_selftest.py',
'pairing_selftest.py',
'parallel_upload_selftest.py',
'parallel_download_selftest.py',
'udp_discovery_selftest.py',
'local_transfer_integration_selftest.py',
'memory_budget_selftest.py',
+1 -1
View File
@@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qft-windows"
version = "0.4.0-rc6"
version = "0.4.7"
dependencies = [
"anyhow",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "qft-windows"
version = "0.4.0-rc6"
version = "0.4.7"
edition = "2024"
rust-version = "1.95"
+2 -2
View File
@@ -23,7 +23,7 @@ use std::{
// a nominally larger page that is only decoded 10~18 times per second.
const DEFAULT_CHUNK_SIZE: u16 = 320;
const UI_FONT_NAME: &str = "qft-ui";
const APP_VERSION: &str = "0.4.0-rc6";
const APP_VERSION: &str = "0.4.7";
fn main() -> eframe::Result {
let options = eframe::NativeOptions {
@@ -446,7 +446,7 @@ impl QftApp {
ui.horizontal_wrapped(|ui| {
ui.heading("Android → 电脑 · 扫码直连");
ui.separator();
ui.label("UDP 快速发现 · 4/8/16 MiB 自适应分块 · 最高 8 路并行 · 不经过外网");
ui.label("UDP 快速发现 · 64 KiB–16 MiB 自适应分块 · 目标 8 路并行 · 不经过外网");
});
ui.add_space(10.0);
let running = self.receive.server.is_some();
+97 -3
View File
@@ -21,6 +21,8 @@ use std::{
pub const PREFERRED_PORT: u16 = 39393;
pub const DISCOVERY_PORT: u16 = 39392;
pub const PARALLEL_CHUNK_SIZE: u64 = 8 * 1024 * 1024;
const MIN_PARALLEL_CHUNK_SIZE: u64 = 64 * 1024;
const MAX_PARALLEL_CHUNK_SIZE: u64 = 16 * 1024 * 1024;
const IO_BUFFER: usize = 1024 * 1024;
#[derive(Clone, Debug)]
@@ -34,6 +36,7 @@ pub enum ReceiverEvent {
#[derive(Debug)]
struct UploadSession {
upload_key: Option<String>,
device: String,
file_name: String,
size: u64,
@@ -169,6 +172,11 @@ fn handle_client(
sessions: &SessionMap,
completed: &CompletedMap,
) -> Result<()> {
// The listener is non-blocking so the UI can poll for shutdown. On
// Windows an accepted socket may retain that mode, which made a body read
// race the next Wi-Fi Direct packet and fail with WSAEWOULDBLOCK (10035).
// File requests must instead wait under the explicit socket timeouts.
stream.set_nonblocking(false)?;
stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(Duration::from_secs(120)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
@@ -244,14 +252,39 @@ fn init_parallel_upload(
.parse().context("X-QFT-Size 无效")?;
let chunk_size = headers.get("x-qft-chunk-size")
.and_then(|v| v.parse::<u64>().ok())
.map(|v| v.clamp(1024 * 1024, 16 * 1024 * 1024))
.map(|v| v.clamp(MIN_PARALLEL_CHUNK_SIZE, MAX_PARALLEL_CHUNK_SIZE))
.unwrap_or(PARALLEL_CHUNK_SIZE);
let total_chunks_u64 = if size == 0 { 0 } else { (size + chunk_size - 1) / chunk_size };
if total_chunks_u64 > u32::MAX as u64 { bail!("文件分块数过大") }
let total_chunks = total_chunks_u64 as u32;
let upload_key = headers.get("x-qft-upload-key")
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty() && value.len() <= 128);
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
// init is idempotent: if the response packet was lost, the Android client
// may repeat init. Return the existing session so already received chunks
// and the preallocated file are preserved instead of leaking a second part.
for (existing_id, existing) in map.iter() {
if let Ok(session) = existing.lock() {
if upload_key.is_some() && session.upload_key == upload_key {
let missing: Vec<usize> = session.received.iter().enumerate()
.filter_map(|(index, received)| if *received { None } else { Some(index) })
.collect();
let body = json!({
"ok": true,
"upload_id": existing_id,
"chunk_size": session.chunk_size,
"total_chunks": session.total_chunks,
"resumed": true,
"missing": missing,
}).to_string();
return write_response(stream, 200, "application/json", body.as_bytes());
}
}
}
let upload_id = random_id();
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
let final_path = unique_path_reserved(save_dir, &file_name, map.values());
let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin");
let part_path = final_path.with_file_name(format!("{final_name}.{upload_id}.qftpart"));
@@ -261,6 +294,7 @@ fn init_parallel_upload(
drop(part);
let session = UploadSession {
upload_key,
device: device.to_owned(),
file_name: file_name.clone(),
size,
@@ -333,7 +367,7 @@ fn receive_parallel_chunk(
let mut out = OpenOptions::new().write(true).open(&part_path)?;
out.seek(SeekFrom::Start(offset))?;
copy_exact(reader, &mut out, content_len)?;
out.flush()?;
out.sync_data()?;
let received = {
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
@@ -572,3 +606,63 @@ fn hex(bytes: &[u8]) -> String {
for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); }
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::{
io::{Read, Write},
net::TcpListener,
sync::mpsc,
time::{SystemTime, UNIX_EPOCH},
};
#[test]
fn legacy_upload_waits_for_a_delayed_body_on_a_nonblocking_accepted_socket() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let dir = std::env::temp_dir().join(format!(
"qft-receiver-test-{}-{}",
std::process::id(),
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(),
));
fs::create_dir_all(&dir).unwrap();
let dir_for_server = dir.clone();
let (events, _updates) = mpsc::channel();
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
let completed: CompletedMap = Arc::new(Mutex::new(HashMap::new()));
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
// This matches the Windows mode inheritance that previously made
// the body read return WSAEWOULDBLOCK between TCP packets.
stream.set_nonblocking(true).unwrap();
handle_client(
&mut stream,
&dir_for_server,
"session",
&events,
&sessions,
&completed,
)
});
let mut client = TcpStream::connect(address).unwrap();
client
.write_all(
b"POST /qft/upload HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\nContent-Length: 4\r\nX-QFT-Size: 4\r\n\r\n",
)
.unwrap();
client.flush().unwrap();
thread::sleep(Duration::from_millis(50));
client.write_all(b"qft!").unwrap();
client.flush().unwrap();
let mut response = String::new();
client.read_to_string(&mut response).unwrap();
server.join().unwrap().unwrap();
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
assert_eq!(fs::read(dir.join("qft-upload.bin")).unwrap(), b"qft!");
let _ = fs::remove_dir_all(dir);
}
}
+99 -22
View File
@@ -128,6 +128,11 @@ fn handle_client(
token: &str,
events: &Sender<SenderEvent>,
) -> Result<()> {
// The listener is non-blocking so its owner can poll for shutdown. On
// Windows an accepted socket can retain that mode, causing a large Range
// response to fail with WSAEWOULDBLOCK (10035) between write calls.
// Downloads must wait under the explicit read/write timeouts instead.
stream.set_nonblocking(false)?;
stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(Duration::from_secs(20)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
@@ -168,18 +173,19 @@ fn handle_client(
if input.metadata()?.len() != size {
bail!("发送文件在二维码生成后发生变化,请重新选择文件并生成二维码")
}
let offset = parse_range_start(headers.get("range"), size)?;
let remaining = size.saturating_sub(offset);
let range = parse_range(headers.get("range"), size)?;
let offset = range.start;
let end = range.end;
let remaining = if size == 0 { 0 } else { end.saturating_sub(offset).saturating_add(1) };
let _ = events.send(SenderEvent::DownloadStarted { device: device.clone(), file_name: file_name.to_owned(), size });
if offset == 0 {
if headers.get("range").is_none() {
write!(stream,
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
)?;
} else {
write!(stream,
"HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nContent-Range: bytes {offset}-{}/{}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
size - 1,
"HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nContent-Range: bytes {offset}-{end}/{}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
size,
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
)?;
@@ -187,10 +193,13 @@ fn handle_client(
use std::io::{Seek, SeekFrom};
input.seek(SeekFrom::Start(offset))?;
let mut buf = vec![0u8; IO_BUFFER];
loop {
let n = input.read(&mut buf)?;
if n == 0 { break }
let mut left = remaining;
while left > 0 {
let want = left.min(buf.len() as u64) as usize;
let n = input.read(&mut buf[..want])?;
if n == 0 { bail!("发送文件读取提前结束:还缺 {left} 字节") }
stream.write_all(&buf[..n])?;
left -= n as u64;
}
stream.flush()?;
let _ = events.send(SenderEvent::DownloadCompleted { device, file_name: file_name.to_owned() });
@@ -210,33 +219,53 @@ fn decode_header(value: Option<&String>) -> Option<String> {
String::from_utf8(bytes).ok()
}
fn parse_range_start(value: Option<&String>, size: u64) -> Result<u64> {
let Some(value) = value else { return Ok(0) };
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ByteRange {
start: u64,
end: u64,
}
fn parse_range(value: Option<&String>, size: u64) -> Result<ByteRange> {
if size == 0 {
if value.is_some() { bail!("空文件没有可下载的字节范围") }
return Ok(ByteRange { start: 0, end: 0 });
}
let Some(value) = value else { return Ok(ByteRange { start: 0, end: size - 1 }) };
let suffix = value.trim().strip_prefix("bytes=").context("Range 格式无效")?;
let start = suffix.strip_suffix('-').context("只支持单段 Range")?
.parse::<u64>().context("Range 起点无效")?;
if start >= size { bail!("Range 超出文件范围") }
Ok(start)
let (start_text, end_text) = suffix.split_once('-').context("Range 格式无效")?;
if start_text.is_empty() { bail!("不支持后缀 Range") }
let start = start_text.parse::<u64>().context("Range 起点无效")?;
let end = if end_text.is_empty() {
size - 1
} else {
end_text.parse::<u64>().context("Range 终点无效")?
};
if start >= size || end >= size || end < start { bail!("Range 超出文件范围") }
Ok(ByteRange { start, end })
}
#[cfg(test)]
mod tests {
use super::{handle_client, parse_range_start, SenderEvent};
use super::{handle_client, parse_range, ByteRange, SenderEvent};
use std::{
fs,
io::{Read, Write},
net::{TcpListener, TcpStream},
sync::mpsc,
thread,
time::Duration,
};
#[test]
fn accepts_only_a_valid_resumable_byte_range() {
assert_eq!(parse_range_start(None, 10).unwrap(), 0);
assert_eq!(parse_range_start(Some(&"bytes=4-".to_owned()), 10).unwrap(), 4);
assert!(parse_range_start(Some(&"bytes=10-".to_owned()), 10).is_err());
assert!(parse_range_start(Some(&"bytes=-4".to_owned()), 10).is_err());
assert!(parse_range_start(Some(&"items=4-".to_owned()), 10).is_err());
fn accepts_open_and_bounded_byte_ranges() {
assert_eq!(parse_range(None, 10).unwrap(), ByteRange { start: 0, end: 9 });
assert_eq!(parse_range(None, 0).unwrap(), ByteRange { start: 0, end: 0 });
assert_eq!(parse_range(Some(&"bytes=4-".to_owned()), 10).unwrap(), ByteRange { start: 4, end: 9 });
assert_eq!(parse_range(Some(&"bytes=2-6".to_owned()), 10).unwrap(), ByteRange { start: 2, end: 6 });
assert!(parse_range(Some(&"bytes=10-".to_owned()), 10).is_err());
assert!(parse_range(Some(&"bytes=6-2".to_owned()), 10).is_err());
assert!(parse_range(Some(&"bytes=-4".to_owned()), 10).is_err());
assert!(parse_range(Some(&"items=4-".to_owned()), 10).is_err());
}
#[test]
@@ -248,7 +277,7 @@ mod tests {
let (events, _receiver) = mpsc::channel::<SenderEvent>();
let path_for_server = path.clone();
let server = thread::spawn(move || {
for _ in 0..2 {
for _ in 0..3 {
let (mut stream, _) = listener.accept().unwrap();
handle_client(&mut stream, &path_for_server, "range.bin", 6, "session", &events).unwrap();
}
@@ -260,11 +289,59 @@ mod tests {
assert_response(&resumed, "HTTP/1.1 206 Partial Content", "cdef");
let header = String::from_utf8_lossy(&resumed[..header_end(&resumed)]);
assert!(header.contains("Content-Range: bytes 2-5/6"));
let bounded = request(address, Some("bytes=2-4"));
assert_response(&bounded, "HTTP/1.1 206 Partial Content", "cde");
let header = String::from_utf8_lossy(&bounded[..header_end(&bounded)]);
assert!(header.contains("Content-Range: bytes 2-4/6"));
server.join().unwrap();
fs::remove_file(path).unwrap();
}
#[test]
fn large_download_waits_for_the_client_after_a_nonblocking_accept() {
let path = std::env::temp_dir().join(format!(
"qft-sender-{}-nonblocking.bin",
std::process::id(),
));
let payload = vec![0x5Au8; 2 * 1024 * 1024];
fs::write(&path, &payload).unwrap();
let file_size = payload.len() as u64;
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let (events, _receiver) = mpsc::channel::<SenderEvent>();
let path_for_server = path.clone();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
// Reproduce the Windows mode inheritance that caused Range
// writes to fail with WSAEWOULDBLOCK (10035).
stream.set_nonblocking(true).unwrap();
handle_client(
&mut stream,
&path_for_server,
"large.bin",
file_size,
"session",
&events,
)
});
let mut client = TcpStream::connect(address).unwrap();
client.write_all(
b"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\n\r\n",
).unwrap();
client.flush().unwrap();
thread::sleep(Duration::from_millis(50));
let mut response = Vec::new();
client.read_to_end(&mut response).unwrap();
server.join().unwrap().unwrap();
let body_start = header_end(&response);
assert!(String::from_utf8_lossy(&response[..body_start]).starts_with("HTTP/1.1 200 OK"));
assert_eq!(&response[body_start..], payload.as_slice());
fs::remove_file(path).unwrap();
}
fn request(address: std::net::SocketAddr, range: Option<&str>) -> Vec<u8> {
let mut stream = TcpStream::connect(address).unwrap();
write!(