feat: add Android to Android phone sharing

This commit is contained in:
zhy200308
2026-08-12 15:17:34 +08:00
parent f248deac17
commit d3e840ff0a
15 changed files with 953 additions and 44 deletions
+13
View File
@@ -16,6 +16,19 @@ v0.4.16 提供两套互不依赖的传输方式:
> v0.4.16 已完成协议、图像合成解码、ROI、双向并发传输、专用 Wi-Fi 快速发现、队列拖动稳定性和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。 > v0.4.16 已完成协议、图像合成解码、ROI、双向并发传输、专用 Wi-Fi 快速发现、队列拖动稳定性和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
## v0.5.0-dev1:Android → Android 手机互传
当前开发版新增 Android 手机之间的扫码直传闭环:
- 发送手机选择多个文件、删除或拖动调整顺序,然后生成 `QFTPHONE2` 二维码;
- Android 8+ 优先创建系统 LocalOnlyHotspot,接收手机扫码后自动加入;
- Android 7 或临时热点不可用时,自动回落到两台手机当前同一 Wi-Fi;
- 二维码只携带一次性会话和网络身份,文件队列通过会话认证后读取,避免多文件让二维码过密;
- 每个文件复用现有最高 8 路 HTTP Range、断点位图和 SHA-256 校验,按发送队列顺序保存到 `Downloads/QFT`;
- 发送页面必须保持打开,返回首页会立即关闭发送服务和临时热点。
此阶段只实现 Android → Android;Android ↔ iOS 尚未接入。
## v0.4.8:跨平台桌面端 + 电脑 ↔ 电脑互传 ## v0.4.8:跨平台桌面端 + 电脑 ↔ 电脑互传
### macOS:请用 QFT超速文件传输.app 启动,不要直接跑裸二进制 ### macOS:请用 QFT超速文件传输.app 启动,不要直接跑裸二进制
+2 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical" applicationId = "com.qft.optical"
minSdk = 24 minSdk = 24
targetSdk = 35 targetSdk = 35
versionCode = 23 versionCode = 24
versionName = "0.4.16" versionName = "0.5.0-dev1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
@@ -150,7 +150,7 @@ object DownloadClient {
val expectedName = requireNotNull(pairing.fileName) val expectedName = requireNotNull(pairing.fileName)
val expectedSize = requireNotNull(pairing.fileSize) val expectedSize = requireNotNull(pairing.fileSize)
val expectedSha = requireNotNull(pairing.sha256) val expectedSha = requireNotNull(pairing.sha256)
val partial = partialFile(context, pairing.session) val partial = partialFile(context, pairing.session, pairing.downloadPath)
partial.parentFile?.let { if (!it.exists() && !it.mkdirs()) error("无法创建接收缓存目录") } partial.parentFile?.let { if (!it.exists() && !it.mkdirs()) error("无法创建接收缓存目录") }
if (partial.length() > expectedSize) discardTransferState(partial) if (partial.length() > expectedSize) discardTransferState(partial)
@@ -379,7 +379,7 @@ object DownloadClient {
abortReason: () -> String?, abortReason: () -> String?,
) { ) {
val end = start + length - 1L val end = start + length - 1L
val conn = open(network, URL("$baseUrl/qft/download")) val conn = open(network, URL(baseUrl + pairing.downloadPath))
try { try {
conn.requestMethod = "GET" conn.requestMethod = "GET"
conn.connectTimeout = 8_000 conn.connectTimeout = 8_000
@@ -466,7 +466,7 @@ object DownloadClient {
onProgress: (received: Long, total: Long) -> Unit, onProgress: (received: Long, total: Long) -> Unit,
) { ) {
val requestedOffset = partial.length().coerceIn(0L, expectedSize) val requestedOffset = partial.length().coerceIn(0L, expectedSize)
val conn = open(network, URL("$baseUrl/qft/download")) val conn = open(network, URL(baseUrl + pairing.downloadPath))
try { try {
conn.requestMethod = "GET" conn.requestMethod = "GET"
conn.connectTimeout = 5_000 conn.connectTimeout = 5_000
@@ -482,7 +482,7 @@ object DownloadClient {
val resumed = code == HttpURLConnection.HTTP_PARTIAL val resumed = code == HttpURLConnection.HTTP_PARTIAL
if (code != HttpURLConnection.HTTP_OK && !resumed) { if (code != HttpURLConnection.HTTP_OK && !resumed) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null } val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
error("电脑下载服务返回 HTTP $code${message?.let { ": $it" } ?: ""}") error("发送端下载服务返回 HTTP $code${message?.let { ": $it" } ?: ""}")
} }
// Older desktop binaries return 200 even with Range. Restart only // Older desktop binaries return 200 even with Range. Restart only
@@ -658,7 +658,7 @@ object DownloadClient {
val offset = ledger.chunkOffset(index) val offset = ledger.chunkOffset(index)
val length = ledger.chunkLength(index) val length = ledger.chunkLength(index)
val end = offset + length - 1L val end = offset + length - 1L
val conn = open(network, URL("$baseUrl/qft/download")) val conn = open(network, URL(baseUrl + pairing.downloadPath))
try { try {
conn.requestMethod = "GET" conn.requestMethod = "GET"
conn.connectTimeout = 5_000 conn.connectTimeout = 5_000
@@ -672,7 +672,7 @@ object DownloadClient {
val code = conn.responseCode val code = conn.responseCode
if (code != HttpURLConnection.HTTP_PARTIAL) { if (code != HttpURLConnection.HTTP_PARTIAL) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null } val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
error("电脑下载服务未返回并行 Range(HTTP $code)${message?.let { ": $it" } ?: ""}") error("发送端下载服务未返回并行 Range(HTTP $code)${message?.let { ": $it" } ?: ""}")
} }
val expectedRange = "bytes $offset-$end/$expectedSize" val expectedRange = "bytes $offset-$end/$expectedSize"
if (conn.getHeaderField("Content-Range") != expectedRange) { if (conn.getHeaderField("Content-Range") != expectedRange) {
@@ -783,9 +783,13 @@ object DownloadClient {
} }
} }
private fun partialFile(context: Context, session: String): File { private fun partialFile(context: Context, session: String, downloadPath: String): File {
val root = context.getExternalFilesDir("qft") ?: context.cacheDir val root = context.getExternalFilesDir("qft") ?: context.cacheDir
return File(root, "$session.qftpart") val suffix = MessageDigest.getInstance("SHA-256")
.digest(downloadPath.toByteArray(Charsets.UTF_8))
.take(6)
.joinToString("") { byte -> "%02x".format(byte.toInt() and 0xFF) }
return File(root, "$session-$suffix.qftpart")
} }
private fun createTarget(resolver: ContentResolver, name: String): DownloadTarget { private fun createTarget(resolver: ContentResolver, name: String): DownloadTarget {
@@ -21,6 +21,7 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.Button import android.widget.Button
import android.widget.FrameLayout import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout import android.widget.LinearLayout
import android.widget.ProgressBar import android.widget.ProgressBar
import android.widget.ScrollView import android.widget.ScrollView
@@ -48,6 +49,7 @@ class MainActivity : ComponentActivity() {
private val cameraExecutor = Executors.newSingleThreadExecutor() private val cameraExecutor = Executors.newSingleThreadExecutor()
private val transferExecutor = Executors.newSingleThreadExecutor() private val transferExecutor = Executors.newSingleThreadExecutor()
private val wifiConnector by lazy { WifiConnector(this) } private val wifiConnector by lazy { WifiConnector(this) }
private val phoneHotspot by lazy { PhoneHotspotController(this) }
private lateinit var assembler: SessionAssembler private lateinit var assembler: SessionAssembler
private var cameraProvider: ProcessCameraProvider? = null private var cameraProvider: ProcessCameraProvider? = null
@@ -91,6 +93,9 @@ class MainActivity : ComponentActivity() {
private var downloadStatusText: TextView? = null private var downloadStatusText: TextView? = null
@Volatile private var downloadRunning = false @Volatile private var downloadRunning = false
@Volatile private var uploadRunning = false @Volatile private var uploadRunning = false
@Volatile private var phoneShareRunning = false
private var phoneShareServer: PhoneShareServer? = null
private var phoneShareStatusText: TextView? = null
/** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。 /** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */ * 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
@Volatile private var transferAbortReason: String? = null @Volatile private var transferAbortReason: String? = null
@@ -102,8 +107,10 @@ class MainActivity : ComponentActivity() {
private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
val pair = pendingPair val pair = pendingPair
if (granted && pair?.direction == TransferDirection.DOWNLOAD_TO_PHONE) { val receivingFromNetwork = pair?.direction == TransferDirection.DOWNLOAD_TO_PHONE ||
connectPair(pair) pair?.direction == TransferDirection.PHONE_TO_PHONE
if (granted && receivingFromNetwork && pair != null) {
ensureWifiPermissionThenConnect(pair)
return@registerForActivityResult return@registerForActivityResult
} }
if (granted) requestScanner(pendingScannerMode) else showHome("Android 7~9 需要存储权限才能把光学接收文件保存到 Downloads/QFT") if (granted) requestScanner(pendingScannerMode) else showHome("Android 7~9 需要存储权限才能把光学接收文件保存到 Downloads/QFT")
@@ -119,6 +126,12 @@ class MainActivity : ComponentActivity() {
} }
} }
private val requestPhoneHotspotPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
if (result.values.all { it }) startPhoneShare() else {
phoneShareStatusText?.text = "需要附近 Wi-Fi/位置权限才能自动创建手机直连网络"
}
}
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uploadRunning) { if (uploadRunning) {
sendStatusText?.text = "传输已经开始,当前队列已锁定" sendStatusText?.text = "传输已经开始,当前队列已锁定"
@@ -134,6 +147,7 @@ class MainActivity : ComponentActivity() {
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过" sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
} else if (selectedFiles.isNotEmpty()) { } else if (selectedFiles.isNotEmpty()) {
sendStatusText?.text = "已选择 ${selectedFiles.size} 个文件,点击“开始传输”" sendStatusText?.text = "已选择 ${selectedFiles.size} 个文件,点击“开始传输”"
phoneShareStatusText?.text = "已选择 ${selectedFiles.size} 个文件,可以创建发送二维码"
} }
} }
@@ -154,6 +168,9 @@ class MainActivity : ComponentActivity() {
pairConsumed.set(false) pairConsumed.set(false)
wifiConnector.releaseHighPerfLock() wifiConnector.releaseHighPerfLock()
wifiConnector.release() wifiConnector.release()
phoneShareServer?.close()
phoneShareServer = null
phoneHotspot.close()
pendingPair = null pendingPair = null
connectedNetwork = null connectedNetwork = null
connectedBaseUrl = null connectedBaseUrl = null
@@ -161,6 +178,8 @@ class MainActivity : ComponentActivity() {
downloadStatusText = null downloadStatusText = null
selectedFiles.clear() selectedFiles.clear()
uploadRunning = false uploadRunning = false
phoneShareRunning = false
phoneShareStatusText = null
sendFilesContainer = null sendFilesContainer = null
sendAddButton = null sendAddButton = null
sendClearButton = null sendClearButton = null
@@ -189,11 +208,18 @@ class MainActivity : ComponentActivity() {
root.addView(space(16)) root.addView(space(16))
root.addView(modeCard( root.addView(modeCard(
title = "扫码直传", title = "扫码直传",
badge = "手机上传 / 电脑下发 · 自动配网 · 快速发现", badge = "电脑互传 / 手机互传 · 自动配网 · 快速发现",
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。", body = "扫描电脑或另一台 Android 手机的二维码后自动连接 QFT 本地网络。电脑接收码会进入选文件上传;电脑/手机发送码会自动下载到 Downloads/QFT。",
buttonLabel = "扫描电脑二维码", buttonLabel = "扫描接收二维码",
) { requestScanner(ScannerMode.PAIR) }) ) { requestScanner(ScannerMode.PAIR) })
root.addView(space(16)) root.addView(space(16))
root.addView(modeCard(
title = "手机 → 手机",
badge = "Android 互传 · 临时热点 · 多文件队列",
body = "本机选择文件并创建二维码;另一台 Android 扫码后自动连接临时网络,按队列顺序并行接收。Android 7 或热点不可用时自动回落到当前同一 Wi-Fi。",
buttonLabel = "选择文件并发送",
) { showPhoneShareSetup() })
root.addView(space(16))
root.addView(modeCard( root.addView(modeCard(
title = "接收文件柜", title = "接收文件柜",
badge = "Downloads/QFT · 图片/视频/PDF/Office/压缩包等", badge = "Downloads/QFT · 图片/视频/PDF/Office/压缩包等",
@@ -202,7 +228,7 @@ class MainActivity : ComponentActivity() {
) { showReceivedFiles() }) ) { showReceivedFiles() })
root.addView(space(22)) root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED)) root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.4.16 · Android 7+ 到最新", 12f, MUTED)) root.addView(text("QFT v0.5.0-dev1 · Android 7+ 到最新", 12f, MUTED))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) }) setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
} }
@@ -529,7 +555,7 @@ class MainActivity : ComponentActivity() {
} }
val back = button("‹ 返回").apply { setOnClickListener { showHome() } } val back = button("‹ 返回").apply { setOnClickListener { showHome() } }
top.addView(back) top.addView(back)
titleText = text(if (mode == ScannerMode.OPTICAL) "电脑 → 手机" else "扫码连接电脑", 19f, Color.WHITE, true) titleText = text(if (mode == ScannerMode.OPTICAL) "电脑 → 手机" else "扫码连接设备", 19f, Color.WHITE, true)
top.addView(titleText, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(10) }) top.addView(titleText, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(10) })
root.addView(top, FrameLayout.LayoutParams(-1, -2, Gravity.TOP)) root.addView(top, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
@@ -540,12 +566,12 @@ class MainActivity : ComponentActivity() {
} }
deviceText = text( deviceText = text(
if (mode == ScannerMode.OPTICAL) "接收设备:$receiverDeviceLabel\n发送设备:等待 QFT2 MANIFEST…" if (mode == ScannerMode.OPTICAL) "接收设备:$receiverDeviceLabel\n发送设备:等待 QFT2 MANIFEST…"
else "目标:等待 QFTPAIR2 配对二维码", else "目标:等待电脑或 Android 配对二维码",
14f, Color.WHITE 14f, Color.WHITE
) )
statusText = text( statusText = text(
if (mode == ScannerMode.OPTICAL) "让电脑的单个大二维码占取景框 50% 以上,识别后会自动锁定区域" if (mode == ScannerMode.OPTICAL) "让电脑的单个大二维码占取景框 50% 以上,识别后会自动锁定区域"
else "扫描 Windows“手机传电脑”页面上的二维码", else "扫描电脑或另一台 Android 显示的 QFT 配对二维码",
14f, MUTED 14f, MUTED
) )
progress = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 } progress = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
@@ -586,7 +612,7 @@ class MainActivity : ComponentActivity() {
runOnUiThread { runOnUiThread {
stopCamera() stopCamera()
showConnecting(pair, "二维码已识别,正在准备本地连接…") showConnecting(pair, "二维码已识别,正在准备本地连接…")
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && Build.VERSION.SDK_INT <= 28 && if (pair.direction in setOf(TransferDirection.DOWNLOAD_TO_PHONE, TransferDirection.PHONE_TO_PHONE) && Build.VERSION.SDK_INT <= 28 &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
) { ) {
requestLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) requestLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
@@ -655,8 +681,8 @@ class MainActivity : ComponentActivity() {
// 不使用二维码地址,也不猜测 192.168.137/49 网段。 // 不使用二维码地址,也不猜测 192.168.137/49 网段。
runOnUiThread { runOnUiThread {
updateConnectingStatus( updateConnectingStatus(
if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证网关和电脑…" if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证发送设备…"
else "网络已就绪 · 正在连接同网段电脑…" else "网络已就绪 · 正在连接同网段发送设备…"
) )
} }
val direct = if (dedicatedWifi) { val direct = if (dedicatedWifi) {
@@ -683,7 +709,7 @@ class MainActivity : ComponentActivity() {
runOnUiThread { runOnUiThread {
updateConnectingStatus( updateConnectingStatus(
if (dedicatedWifi) "专用网关正在初始化 · 仅在 QFT 子网内自动发现…" if (dedicatedWifi) "专用网关正在初始化 · 仅在 QFT 子网内自动发现…"
else "同网段地址未应答 · 正在 UDP 快速发现电脑…" else "同网段地址未应答 · 正在 UDP 快速发现发送设备…"
) )
} }
discovered = UploadClient.discoverUdp( discovered = UploadClient.discoverUdp(
@@ -699,8 +725,8 @@ class MainActivity : ComponentActivity() {
} }
runOnUiThread { runOnUiThread {
updateConnectingStatus( updateConnectingStatus(
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…" if (discovered != null) "已通过 UDP 找到发送设备 · 正在验证服务…"
else "仅在当前连接的 QFT 子网内并行查找电脑…" else "仅在当前连接的 QFT 子网内并行查找发送设备…"
) )
} }
} }
@@ -724,26 +750,34 @@ class MainActivity : ComponentActivity() {
val diagnosis = buildString { val diagnosis = buildString {
append( append(
if (dedicatedWifi) { if (dedicatedWifi) {
"QFT 专用 Wi-Fi 已连接,但在该专用网络的实际网关和子网内未找到服务。\n\n" "QFT 专用 Wi-Fi 已连接,但在该专用网络的实际网关和子网内未找到发送服务。\n\n"
} else { } else {
"Wi-Fi 已连接,但在当前局域网内未找到 QFT 服务。\n\n" "Wi-Fi 已连接,但在当前局域网内未找到 QFT 服务。\n\n"
} }
) )
append("手机侧:").append(wifiConnector.describeNetwork(network)).append("\n") append("手机侧:").append(wifiConnector.describeNetwork(network)).append("\n")
append("连接模式:") append("连接模式:")
append(if (dedicatedWifi) "QFT 专用 Wi-Fi(不使用二维码/电脑本地网卡地址)" else "当前局域网备用模式") append(if (dedicatedWifi) "QFT 专用 Wi-Fi(不使用二维码内的旧网卡地址)" else "当前局域网备用模式")
append("\n探测过的网关地址:") append("\n探测过的网关地址:")
append(gateways.joinToString("、").ifEmpty { "(无)" }) append(gateways.joinToString("、").ifEmpty { "(无)" })
append("\n子网扫描范围:").append(subnet.size).append(" 个地址\n\n") append("\n子网扫描范围:").append(subnet.size).append(" 个地址\n\n")
if (pair.direction == TransferDirection.PHONE_TO_PHONE) {
append("请对照检查:① 发送手机是否仍停留在二维码页面;")
append("② 两台手机是否仍连接二维码内的 QFT 临时网络;")
append("③ 发送手机是否关闭了省电/热点。")
} else {
append("请对照检查:① Windows 上 QFT Direct 是否仍显示已就绪;") append("请对照检查:① Windows 上 QFT Direct 是否仍显示已就绪;")
append("② 防火墙是否放行 qft-desktop.exe 的当前专用网络类型;") append("② 防火墙是否放行 qft-desktop.exe 的当前专用网络类型;")
append("③ 手机是否仍连接二维码内的 QFT 专用网络。") append("③ 手机是否仍连接二维码内的 QFT 专用网络。")
} }
}
showPairError(pair, diagnosis) showPairError(pair, diagnosis)
} else { } else {
connectedBaseUrl = base connectedBaseUrl = base
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) { if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
startDownloadFromPc(pair, base) startDownloadFromPc(pair, base)
} else if (pair.direction == TransferDirection.PHONE_TO_PHONE) {
startDownloadsFromPhone(pair, base)
} else { } else {
showSendReady(pair, base) showSendReady(pair, base)
} }
@@ -756,7 +790,7 @@ class MainActivity : ComponentActivity() {
// onLost is recovered inside WifiConnector. onUnavailable is // onLost is recovered inside WifiConnector. onUnavailable is
// terminal (system/user rejected the retained request), so it // terminal (system/user rejected the retained request), so it
// is the only network callback that aborts an active transfer. // is the only network callback that aborts an active transfer.
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && downloadRunning) { if (pair.direction != TransferDirection.UPLOAD_TO_PC && downloadRunning) {
transferAbortReason = message transferAbortReason = message
downloadStatusText?.apply { downloadStatusText?.apply {
text = "QFT 本地网络已断开,正在结束当前下载请求…" text = "QFT 本地网络已断开,正在结束当前下载请求…"
@@ -771,12 +805,13 @@ class MainActivity : ComponentActivity() {
private fun showConnecting(pair: PairingPayload, message: String) { private fun showConnecting(pair: PairingPayload, message: String) {
val root = pageColumn() val root = pageColumn()
root.addView(text("正在连接电脑", 28f, Color.WHITE, true)) val peerKind = if (pair.direction == TransferDirection.PHONE_TO_PHONE) "发送手机" else "电脑"
root.addView(text("正在连接$peerKind", 28f, Color.WHITE, true))
root.addView(text(pair.pcName, 18f, ACCENT)) root.addView(text(pair.pcName, 18f, ACCENT))
root.addView(space(22)) root.addView(space(22))
root.addView(card().apply { root.addView(card().apply {
addView(text("配对信息", 15f, MUTED)) addView(text("配对信息", 15f, MUTED))
addView(text("电脑:${pair.pcName}", 16f, Color.WHITE), matchWrap(top = 8)) addView(text("设备:${pair.pcName}", 16f, Color.WHITE), matchWrap(top = 8))
addView(text("网络:${pair.wifi?.ssid ?: "当前局域网"}", 14f, Color.WHITE), matchWrap(top = 5)) addView(text("网络:${pair.wifi?.ssid ?: "当前局域网"}", 14f, Color.WHITE), matchWrap(top = 5))
addView(text("会话:${pair.session.take(10)}…", 12f, MUTED), matchWrap(top = 5)) addView(text("会话:${pair.session.take(10)}…", 12f, MUTED), matchWrap(top = 5))
}) })
@@ -816,6 +851,242 @@ class MainActivity : ComponentActivity() {
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) }) setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
} }
private fun showPhoneShareSetup() {
phoneShareServer?.close()
phoneShareServer = null
phoneHotspot.close()
selectedFiles.clear()
phoneShareRunning = false
uploadRunning = false
val root = pageColumn()
root.addView(text("Android → Android", 28f, Color.WHITE, true))
root.addView(text("选择文件后创建一次性配对二维码", 15f, ACCENT))
root.addView(space(16))
root.addView(card().apply {
addView(text("发送队列", 17f, Color.WHITE, true))
sendFilesText = text("尚未选择文件", 14f, WARNING)
addView(sendFilesText, matchWrap(top = 8))
sendFilesContainer = LinearLayout(this@MainActivity).apply { orientation = LinearLayout.VERTICAL }
addView(sendFilesContainer, matchWrap(top = 6))
val actions = LinearLayout(this@MainActivity).apply { orientation = LinearLayout.HORIZONTAL }
sendAddButton = button("添加文件").apply { setOnClickListener { pickFiles.launch(arrayOf("*/*")) } }
sendClearButton = button("清空").apply {
setOnClickListener {
if (!phoneShareRunning) {
selectedFiles.clear()
renderSelectedFiles()
}
}
}
actions.addView(sendAddButton, LinearLayout.LayoutParams(0, dp(48), 1f).apply { marginEnd = dp(8) })
actions.addView(sendClearButton, LinearLayout.LayoutParams(dp(96), dp(48)))
addView(actions, matchWrap(top = 12))
addView(text("传输开始前可以删除或拖动排序;二维码创建后队列锁定。", 12f, MUTED), matchWrap(top = 8))
})
root.addView(space(14))
root.addView(card().apply {
phoneShareStatusText = text("先添加需要发送的文件", 14f, MUTED)
addView(phoneShareStatusText)
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 = false
setOnClickListener { ensurePhoneHotspotPermissionThenStart() }
}
addView(sendButton, matchWrap(top = 12))
})
root.addView(space(14))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
renderSelectedFiles()
}
private fun ensurePhoneHotspotPermissionThenStart() {
if (Build.VERSION.SDK_INT < 26) {
startPhoneShare()
return
}
val required = if (Build.VERSION.SDK_INT >= 33) {
arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES)
} else {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
val missing = required.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (missing.isEmpty()) startPhoneShare() else requestPhoneHotspotPermissions.launch(missing.toTypedArray())
}
private fun startPhoneShare() {
if (phoneShareRunning || selectedFiles.isEmpty()) return
phoneShareRunning = true
uploadRunning = true // Reuse the queue lock and drag/remove guards.
sendButton?.isEnabled = false
sendAddButton?.isEnabled = false
sendClearButton?.isEnabled = false
phoneShareStatusText?.text = "正在读取文件并计算完整性校验…"
val files = selectedFiles.toList()
val sessionBytes = ByteArray(24).also { java.security.SecureRandom().nextBytes(it) }
val session = Base64Url.encode(sessionBytes)
transferExecutor.execute {
try {
val server = PhoneShareServer.create(
resolver = contentResolver,
session = session,
deviceName = receiverDeviceLabel,
selected = files,
onHashProgress = { done, total, name -> runOnUiThread {
sendProgress?.progress = if (total == 0) 0 else done * 1000 / total
phoneShareStatusText?.text = if (done >= total) "文件清单已就绪,正在创建手机直连网络…"
else "正在校验 ${done + 1}/$total:$name"
} },
onPeer = { peer -> runOnUiThread {
phoneShareStatusText?.text = "$peer 已连接,正在接收队列文件…"
} },
)
phoneShareServer = server
runOnUiThread {
phoneHotspot.start(
onStarted = { wifi -> showPhoneShareQr(server, wifi, null) },
onFailed = { reason ->
val endpoints = PhoneShareServer.localEndpoints(server.port)
if (endpoints.isEmpty()) {
phoneShareServer?.close()
phoneShareServer = null
phoneShareRunning = false
uploadRunning = false
phoneShareStatusText?.apply {
text = "$reason;当前也没有可用的局域网地址"
setTextColor(WARNING)
}
sendAddButton?.isEnabled = true
sendClearButton?.isEnabled = true
renderSelectedFiles()
} else {
showPhoneShareQr(server, null, "$reason,已回落到当前同一 Wi-Fi")
}
},
)
}
} catch (e: Exception) {
runOnUiThread {
phoneShareRunning = false
uploadRunning = false
phoneShareStatusText?.apply {
text = "创建发送会话失败:${e.message ?: e.javaClass.simpleName}"
setTextColor(WARNING)
}
sendAddButton?.isEnabled = true
sendClearButton?.isEnabled = true
renderSelectedFiles()
}
}
}
}
private fun showPhoneShareQr(server: PhoneShareServer, wifi: WifiCredentials?, note: String?) {
if (phoneShareServer !== server) return
val endpoints = PhoneShareServer.localEndpoints(server.port)
val encoded = try { server.pairingText(wifi, endpoints) } catch (e: Exception) {
phoneShareStatusText?.text = "无法生成配对二维码:${e.message}"
return
}
val qr = PhoneQr.render(encoded, 720)
val root = pageColumn()
root.addView(text("等待另一台 Android 扫码", 27f, Color.WHITE, true))
root.addView(text("$receiverDeviceLabel · ${selectedFiles.size} 个文件", 15f, ACCENT))
root.addView(space(12))
root.addView(ImageView(this).apply {
setImageBitmap(qr)
adjustViewBounds = true
setBackgroundColor(Color.WHITE)
setPadding(dp(8), dp(8), dp(8), dp(8))
}, LinearLayout.LayoutParams(-1, -2))
root.addView(space(12))
phoneShareStatusText = text(
note ?: "QFT 临时网络已就绪;另一台手机扫码后会自动连接并开始接收。",
14f,
if (note == null) SUCCESS else WARNING,
)
root.addView(phoneShareStatusText)
root.addView(text(
if (wifi != null) "临时网络:${wifi.ssid}\n发送服务端口:${server.port}"
else "连接方式:两台手机当前同一 Wi-Fi\n发送服务端口:${server.port}",
12f, MUTED,
), matchWrap(top = 8))
root.addView(space(16))
root.addView(button("停止发送并返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun startDownloadsFromPhone(pair: PairingPayload, baseUrl: String) {
val root = pageColumn()
root.addView(text("正在接收手机文件", 28f, Color.WHITE, true))
root.addView(text("${pair.pcName} → $receiverDeviceLabel", 16f, ACCENT))
root.addView(space(16))
val status = text("正在读取发送队列…", 14f, MUTED)
val bar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000 }
downloadStatusText = status
root.addView(status)
root.addView(bar, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
root.addView(space(18))
root.addView(button("取消并返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
downloadRunning = true
transferAbortReason = null
wifiConnector.acquireHighPerfLock()
transferExecutor.execute {
try {
val manifest = PhoneShareServer.fetchManifest(connectedNetwork, baseUrl, pair, receiverDeviceLabel)
val totalBytes = manifest.sumOf { it.size }
var completedBytes = 0L
val savedNames = mutableListOf<String>()
manifest.forEachIndexed { index, item ->
val filePair = pair.copy(
direction = TransferDirection.DOWNLOAD_TO_PHONE,
fileName = item.name,
fileSize = item.size,
sha256 = item.sha256,
downloadPath = item.path,
)
runOnUiThread { status.text = "正在接收 ${index + 1}/${manifest.size}:${item.name}" }
val before = completedBytes
val saved = DownloadClient.download(
context = this@MainActivity,
resolver = contentResolver,
networkProvider = { connectedNetwork },
baseUrl = baseUrl,
pairing = filePair,
deviceName = receiverDeviceLabel,
abortReason = { transferAbortReason },
onPhase = { phase -> runOnUiThread {
status.text = "${index + 1}/${manifest.size} ${item.name} · $phase"
} },
) { received, _ -> runOnUiThread {
val all = before + received
bar.progress = if (totalBytes <= 0) 0 else ((all * 1000L) / totalBytes).toInt().coerceIn(0, 1000)
status.text = "正在接收 ${index + 1}/${manifest.size}:${item.name}\n${humanBytes(all)} / ${humanBytes(totalBytes)}"
} }
completedBytes += item.size
savedNames += saved.name
}
runOnUiThread {
bar.progress = 1000
status.setTextColor(SUCCESS)
status.text = "手机互传完成:${savedNames.size} 个文件已保存到 Downloads/QFT"
}
} catch (e: Exception) {
runOnUiThread { showPairError(pair, "从手机接收失败:${e.message ?: e.javaClass.simpleName}") }
} finally {
downloadRunning = false
wifiConnector.releaseHighPerfLock()
}
}
}
private fun showSendReady(pair: PairingPayload, baseUrl: String) { private fun showSendReady(pair: PairingPayload, baseUrl: String) {
val root = pageColumn() val root = pageColumn()
root.addView(text("已连接电脑", 28f, Color.WHITE, true)) root.addView(text("已连接电脑", 28f, Color.WHITE, true))
@@ -1049,6 +1320,7 @@ class MainActivity : ComponentActivity() {
} }
private fun renderSelectedFiles() { private fun renderSelectedFiles() {
val phoneMode = phoneShareStatusText != null
val total = selectedFiles.sumOf { it.size } val total = selectedFiles.sumOf { it.size }
sendFilesText?.text = if (selectedFiles.isEmpty()) { sendFilesText?.text = if (selectedFiles.isEmpty()) {
"请先选择需要传输的文件" "请先选择需要传输的文件"
@@ -1097,9 +1369,10 @@ class MainActivity : ComponentActivity() {
sendButton?.text = when { sendButton?.text = when {
uploadRunning -> "传输中 · 队列已锁定" uploadRunning -> "传输中 · 队列已锁定"
selectedFiles.isEmpty() -> "请先添加文件" selectedFiles.isEmpty() -> "请先添加文件"
phoneMode -> "创建 ${selectedFiles.size} 个文件的发送二维码"
else -> "开始传输 ${selectedFiles.size} 个文件" else -> "开始传输 ${selectedFiles.size} 个文件"
} }
sendButton?.isEnabled = connectedBaseUrl != null && selectedFiles.isNotEmpty() && !uploadRunning sendButton?.isEnabled = (phoneMode || connectedBaseUrl != null) && selectedFiles.isNotEmpty() && !uploadRunning
} }
private fun installFileQueueDrag( private fun installFileQueueDrag(
@@ -1341,6 +1614,8 @@ class MainActivity : ComponentActivity() {
override fun onDestroy() { override fun onDestroy() {
assembler.reset() assembler.reset()
wifiConnector.release() wifiConnector.release()
phoneShareServer?.close()
phoneHotspot.close()
stopCamera() stopCamera()
cameraExecutor.shutdownNow() cameraExecutor.shutdownNow()
transferExecutor.shutdownNow() transferExecutor.shutdownNow()
@@ -21,23 +21,29 @@ data class PairingPayload(
val fileName: String? = null, val fileName: String? = null,
val fileSize: Long? = null, val fileSize: Long? = null,
val sha256: String? = null, val sha256: String? = null,
/** Internal per-file route used by Android → Android manifests. QR input
* never controls this value; parsed pairing codes always use the default. */
val downloadPath: String = "/qft/download",
) )
enum class TransferDirection { UPLOAD_TO_PC, DOWNLOAD_TO_PHONE } enum class TransferDirection { UPLOAD_TO_PC, DOWNLOAD_TO_PHONE, PHONE_TO_PHONE }
object PairingProtocol { object PairingProtocol {
const val PREFIX_V2 = "QFTPAIR2:" const val PREFIX_V2 = "QFTPAIR2:"
const val PREFIX_SEND_V2 = "QFTSEND2:" const val PREFIX_SEND_V2 = "QFTSEND2:"
const val PREFIX_PHONE_V2 = "QFTPHONE2:"
const val PREFIX_V1 = "QFTPAIR1:" const val PREFIX_V1 = "QFTPAIR1:"
fun isPairingText(text: String): Boolean = fun isPairingText(text: String): Boolean =
text.startsWith(PREFIX_V2) || text.startsWith(PREFIX_SEND_V2) || text.startsWith(PREFIX_V1) text.startsWith(PREFIX_V2) || text.startsWith(PREFIX_SEND_V2) ||
text.startsWith(PREFIX_PHONE_V2) || text.startsWith(PREFIX_V1)
fun parse(text: String): PairingPayload? { fun parse(text: String): PairingPayload? {
if (text.length > 4096) return null if (text.length > 4096) return null
return when { return when {
text.startsWith(PREFIX_V2) -> parseV2(text.substring(PREFIX_V2.length), TransferDirection.UPLOAD_TO_PC) text.startsWith(PREFIX_V2) -> parseV2(text.substring(PREFIX_V2.length), TransferDirection.UPLOAD_TO_PC)
text.startsWith(PREFIX_SEND_V2) -> parseV2(text.substring(PREFIX_SEND_V2.length), TransferDirection.DOWNLOAD_TO_PHONE) text.startsWith(PREFIX_SEND_V2) -> parseV2(text.substring(PREFIX_SEND_V2.length), TransferDirection.DOWNLOAD_TO_PHONE)
text.startsWith(PREFIX_PHONE_V2) -> parseV2(text.substring(PREFIX_PHONE_V2.length), TransferDirection.PHONE_TO_PHONE)
text.startsWith(PREFIX_V1) -> parseV1(text.substring(PREFIX_V1.length)) text.startsWith(PREFIX_V1) -> parseV1(text.substring(PREFIX_V1.length))
else -> null else -> null
} }
@@ -53,6 +59,7 @@ object PairingProtocol {
val direction = when (encodedDirection) { val direction = when (encodedDirection) {
"u" -> TransferDirection.UPLOAD_TO_PC "u" -> TransferDirection.UPLOAD_TO_PC
"d" -> TransferDirection.DOWNLOAD_TO_PHONE "d" -> TransferDirection.DOWNLOAD_TO_PHONE
"m" -> TransferDirection.PHONE_TO_PHONE
else -> return null else -> return null
} }
if (direction != expectedDirection) return null if (direction != expectedDirection) return null
@@ -67,7 +74,9 @@ object PairingProtocol {
val ssid = wifiArray.optString(0) val ssid = wifiArray.optString(0)
val passphrase = wifiArray.optString(1) val passphrase = wifiArray.optString(1)
if (!validWifi(ssid, passphrase)) return null if (!validWifi(ssid, passphrase)) return null
WifiCredentials(ssid, passphrase, "WPA2") val security = wifiArray.optString(2, "WPA2")
if (security !in setOf("WPA2", "WPA3")) return null
WifiCredentials(ssid, passphrase, security)
} else null } else null
val endpoints = mutableListOf<String>() val endpoints = mutableListOf<String>()
@@ -157,6 +166,34 @@ object PairingProtocol {
private fun decodeUrlBase64(encoded: String): ByteArray? = Base64Url.decode(encoded) private fun decodeUrlBase64(encoded: String): ByteArray? = Base64Url.decode(encoded)
/** Build a compact Android-sender QR. File names and hashes stay in the
* authenticated local manifest so a large queue does not make the QR dense. */
fun encodePhoneShare(
session: String,
senderName: String,
port: Int,
endpoints: List<String>,
wifi: WifiCredentials?,
): String {
require(validSession(session))
require(port in 1..65535)
val safeEndpoints = endpoints
.map { it.trim().removeSuffix("/") }
.filter { isAllowedLocalHttpEndpoint(it, port) }
.distinct()
require(wifi != null || safeEndpoints.isNotEmpty())
val obj = JSONObject().apply {
put("v", 2)
put("s", session)
put("n", senderName.take(80))
put("p", port)
put("d", "m")
if (safeEndpoints.isNotEmpty()) put("e", org.json.JSONArray(safeEndpoints))
wifi?.let { put("w", org.json.JSONArray(listOf(it.ssid, it.passphrase, it.security))) }
}
return PREFIX_PHONE_V2 + Base64Url.encode(obj.toString().toByteArray(Charsets.UTF_8))
}
private fun validSession(session: String): Boolean = session.matches(Regex("^[A-Za-z0-9_-]{20,64}$")) private fun validSession(session: String): Boolean = session.matches(Regex("^[A-Za-z0-9_-]{20,64}$"))
private fun validWifi(ssid: String, passphrase: String): Boolean { private fun validWifi(ssid: String, passphrase: String): Boolean {
@@ -0,0 +1,91 @@
package com.qft.optical
import android.content.Context
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.annotation.RequiresApi
/** Owns an Android LocalOnlyHotspot reservation for one phone-share session. */
class PhoneHotspotController(context: Context) {
private val wifiManager = context.applicationContext.getSystemService(WifiManager::class.java)
private var reservation: AutoCloseable? = null
private var generation = 0
fun start(
onStarted: (WifiCredentials) -> Unit,
onFailed: (String) -> Unit,
) {
close()
val run = ++generation
if (Build.VERSION.SDK_INT < 26) {
onFailed("Android 7 不支持应用内临时热点,将使用当前局域网")
return
}
startApi26(run, onStarted, onFailed)
}
@RequiresApi(26)
@Suppress("MissingPermission", "DEPRECATION")
private fun startApi26(
run: Int,
onStarted: (WifiCredentials) -> Unit,
onFailed: (String) -> Unit,
) {
try {
wifiManager.startLocalOnlyHotspot(
object : WifiManager.LocalOnlyHotspotCallback() {
override fun onStarted(value: WifiManager.LocalOnlyHotspotReservation) {
if (run != generation) {
value.close()
return
}
reservation = value
val identity = if (Build.VERSION.SDK_INT >= 30) {
val config = value.softApConfiguration
Triple(
config.ssid,
config.passphrase,
if (config.securityType == android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_SAE) "WPA3" else "WPA2",
)
} else {
val config = value.wifiConfiguration
Triple(config?.SSID?.trim('"'), config?.preSharedKey?.trim('"'), "WPA2")
}
val ssid = identity.first.orEmpty()
val passphrase = identity.second.orEmpty()
if (ssid.isBlank() || passphrase.length !in 8..63) {
close()
onFailed("系统临时热点没有返回有效的名称或密码")
return
}
onStarted(WifiCredentials(ssid, passphrase, identity.third))
}
override fun onStopped() {
if (run == generation) {
reservation = null
onFailed("系统已停止 QFT 临时热点")
}
}
override fun onFailed(reason: Int) {
if (run == generation) {
onFailed("系统无法创建临时热点(错误 $reason)")
}
}
},
Handler(Looper.getMainLooper()),
)
} catch (e: Exception) {
onFailed("启动临时热点失败:${e.message ?: e.javaClass.simpleName}")
}
}
fun close() {
generation++
try { reservation?.close() } catch (_: Exception) {}
reservation = null
}
}
@@ -0,0 +1,26 @@
package com.qft.optical
import android.graphics.Bitmap
import android.graphics.Color
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
object PhoneQr {
fun render(text: String, pixels: Int): Bitmap {
val hints = mapOf(
EncodeHintType.CHARACTER_SET to "UTF-8",
EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M,
EncodeHintType.MARGIN to 3,
)
val matrix = QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, pixels, pixels, hints)
val bitmap = Bitmap.createBitmap(matrix.width, matrix.height, Bitmap.Config.ARGB_8888)
val row = IntArray(matrix.width)
for (y in 0 until matrix.height) {
for (x in 0 until matrix.width) row[x] = if (matrix[x, y]) Color.BLACK else Color.WHITE
bitmap.setPixels(row, 0, matrix.width, 0, y, matrix.width, 1)
}
return bitmap
}
}
@@ -0,0 +1,309 @@
package com.qft.optical
import android.content.ContentResolver
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.FileInputStream
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketTimeoutException
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
data class PhoneShareItem(
val selected: SelectedFile,
val sha256: String,
)
data class PhoneShareManifestItem(
val name: String,
val size: Long,
val sha256: String,
val path: String,
)
internal fun phoneShareRange(value: String?, size: Long): Pair<Long, Long>? {
if (size == 0L) return if (value == null) 0L to 0L else null
if (value == null) return 0L to (size - 1L)
val body = value.removePrefix("bytes=")
if (body == value) return null
val split = body.split('-', limit = 2)
if (split.size != 2 || split[0].isBlank()) return null
val start = split[0].toLongOrNull() ?: return null
val end = if (split[1].isBlank()) size - 1L else split[1].toLongOrNull() ?: return null
return if (start in 0 until size && end in start until size) start to end else null
}
/** Minimal authenticated HTTP/Range sender used by Android → Android v2. */
class PhoneShareServer private constructor(
private val resolver: ContentResolver,
private val session: String,
private val deviceName: String,
private val items: List<PhoneShareItem>,
private val server: ServerSocket,
private val onPeer: (String) -> Unit,
) : AutoCloseable {
val port: Int get() = server.localPort
private val stopped = AtomicBoolean(false)
private val clients = Executors.newFixedThreadPool(10)
private val tcpThread: Thread
private val udpThread: Thread
init {
server.soTimeout = 250
tcpThread = Thread({ acceptLoop() }, "qft-phone-http").apply { start() }
udpThread = Thread({ discoveryLoop() }, "qft-phone-discovery").apply { start() }
}
fun pairingText(wifi: WifiCredentials?, endpoints: List<String>): String =
PairingProtocol.encodePhoneShare(session, deviceName, port, endpoints, wifi)
private fun acceptLoop() {
while (!stopped.get()) {
try {
val socket = server.accept()
clients.execute { socket.use { handle(it) } }
} catch (_: SocketTimeoutException) {
} catch (_: Exception) {
if (!stopped.get()) Thread.sleep(30)
}
}
}
private fun handle(socket: Socket) {
socket.tcpNoDelay = true
socket.soTimeout = 20_000
val input = BufferedInputStream(socket.getInputStream(), 32 * 1024)
val output = BufferedOutputStream(socket.getOutputStream(), 1024 * 1024)
val request = readLine(input) ?: return
val parts = request.split(' ')
if (parts.size < 2) return
val headers = linkedMapOf<String, String>()
while (true) {
val line = readLine(input) ?: return
if (line.isEmpty()) break
val split = line.indexOf(':')
if (split > 0) headers[line.substring(0, split).trim().lowercase()] = line.substring(split + 1).trim()
}
if (headers["x-qft-token"] != session) {
response(output, 403, "text/plain", "invalid session".toByteArray())
return
}
headers["x-qft-device"]?.let { encoded ->
Base64Url.decode(encoded)?.toString(Charsets.UTF_8)?.take(80)?.let(onPeer)
}
val method = parts[0]
val path = parts[1].substringBefore('?')
when {
method == "GET" && path == "/qft/ping" -> response(
output, 200, "application/json",
"{\"ok\":true,\"protocol\":2,\"direction\":\"phone-download\"}".toByteArray(),
)
method == "GET" && path == "/qft/phone/manifest" -> response(
output, 200, "application/json", manifestJson().toByteArray(Charsets.UTF_8),
)
method == "GET" && path.startsWith("/qft/phone/download/") -> {
val index = path.substringAfterLast('/').toIntOrNull()
if (index == null || index !in items.indices) {
response(output, 404, "text/plain", "not found".toByteArray())
} else {
serveFile(output, headers["range"], items[index])
}
}
else -> response(output, 404, "text/plain", "not found".toByteArray())
}
}
private fun manifestJson(): String = JSONObject().apply {
put("v", 2)
put("sender", deviceName)
put("files", JSONArray().apply {
items.forEachIndexed { index, item ->
put(JSONObject().apply {
put("name", item.selected.name)
put("size", item.selected.size)
put("sha256", item.sha256)
put("path", "/qft/phone/download/$index")
})
}
})
}.toString()
private fun serveFile(output: BufferedOutputStream, rangeText: String?, item: PhoneShareItem) {
val size = item.selected.size
val range = phoneShareRange(rangeText, size) ?: run {
response(output, 416, "text/plain", "invalid range".toByteArray())
return
}
val (start, end) = range
val length = if (size == 0L) 0L else end - start + 1L
val status = if (rangeText == null) "200 OK" else "206 Partial Content"
val header = buildString {
append("HTTP/1.1 $status\r\n")
append("Content-Type: application/octet-stream\r\n")
append("Content-Length: $length\r\n")
append("Accept-Ranges: bytes\r\n")
if (rangeText != null) append("Content-Range: bytes $start-$end/$size\r\n")
append("Connection: close\r\n\r\n")
}
output.write(header.toByteArray(StandardCharsets.US_ASCII))
if (length > 0L) {
resolver.openFileDescriptor(item.selected.uri, "r")?.use { descriptor ->
FileInputStream(descriptor.fileDescriptor).use { source ->
source.channel.position(start)
val buffer = ByteArray(1024 * 1024)
var remaining = length
while (remaining > 0 && !stopped.get()) {
val count = source.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
if (count < 0) error("source ended early")
output.write(buffer, 0, count)
remaining -= count
}
}
} ?: error("cannot open shared file")
}
output.flush()
}
private fun discoveryLoop() {
val socket = try {
DatagramSocket(39392).apply { soTimeout = 250; broadcast = true }
} catch (_: Exception) { return }
socket.use {
val buffer = ByteArray(512)
while (!stopped.get()) {
try {
val request = DatagramPacket(buffer, buffer.size)
socket.receive(request)
val text = String(request.data, 0, request.length, Charsets.US_ASCII)
if (!text.startsWith("QFTDISC2:$session:")) continue
val encodedName = text.substringAfter("QFTDISC2:$session:")
Base64Url.decode(encodedName)?.toString(Charsets.UTF_8)?.take(80)?.let(onPeer)
val reply = "QFTHERE2:$session:$port".toByteArray(Charsets.US_ASCII)
socket.send(DatagramPacket(reply, reply.size, request.address, request.port))
} catch (_: SocketTimeoutException) {
} catch (_: Exception) {
if (!stopped.get()) Thread.sleep(30)
}
}
}
}
override fun close() {
if (!stopped.compareAndSet(false, true)) return
try { server.close() } catch (_: Exception) {}
clients.shutdownNow()
tcpThread.interrupt()
udpThread.interrupt()
}
companion object {
fun create(
resolver: ContentResolver,
session: String,
deviceName: String,
selected: List<SelectedFile>,
onHashProgress: (Int, Int, String) -> Unit = { _, _, _ -> },
onPeer: (String) -> Unit = {},
): PhoneShareServer {
require(selected.isNotEmpty())
val items = selected.mapIndexed { index, file ->
onHashProgress(index, selected.size, file.name)
PhoneShareItem(file, sha256(resolver, file))
}
onHashProgress(selected.size, selected.size, "")
return PhoneShareServer(
resolver, session, deviceName, items,
ServerSocket(0, 32, InetAddress.getByName("0.0.0.0")), onPeer,
)
}
fun localEndpoints(port: Int): List<String> {
val result = mutableListOf<String>()
val interfaces = try { NetworkInterface.getNetworkInterfaces()?.toList().orEmpty() } catch (_: Exception) { emptyList() }
for (networkInterface in interfaces) {
if (!runCatching { networkInterface.isUp && !networkInterface.isLoopback }.getOrDefault(false)) continue
for (address in networkInterface.inetAddresses.toList()) {
val host = address.hostAddress?.substringBefore('%') ?: continue
val endpoint = "http://$host:$port"
if (PairingProtocol.isAllowedLocalHttpEndpoint(endpoint, port) && endpoint !in result) result += endpoint
}
}
return result
}
fun fetchManifest(
network: android.net.Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
): List<PhoneShareManifestItem> {
val url = java.net.URL("$baseUrl/qft/phone/manifest")
val connection = (network?.openConnection(url) ?: url.openConnection()) as java.net.HttpURLConnection
try {
connection.connectTimeout = 4_000
connection.readTimeout = 8_000
connection.setRequestProperty("X-QFT-Token", pairing.session)
connection.setRequestProperty("X-QFT-Device", Base64Url.encode(deviceName.toByteArray()))
if (connection.responseCode != 200) error("文件清单返回 HTTP ${connection.responseCode}")
val root = JSONObject(connection.inputStream.bufferedReader().use { it.readText() })
val files = root.getJSONArray("files")
require(files.length() in 1..10_000) { "文件清单数量无效" }
return (0 until files.length()).map { index ->
val item = files.getJSONObject(index)
val name = item.getString("name").takeIf { validName(it) } ?: error("文件名无效")
val size = item.getLong("size").takeIf { it >= 0L } ?: error("文件大小无效")
val sha = item.getString("sha256").lowercase()
.takeIf { it.matches(Regex("^[0-9a-f]{64}$")) } ?: error("文件校验值无效")
val expectedPath = "/qft/phone/download/$index"
require(item.getString("path") == expectedPath) { "文件路径无效" }
PhoneShareManifestItem(name, size, sha, expectedPath)
}
} finally {
connection.disconnect()
}
}
private fun validName(value: String): Boolean = value.isNotBlank() && value.length <= 180 &&
value.none { it.code <= 31 || it.code == 127 || it in "\\/:*?\"<>|" }
private fun sha256(resolver: ContentResolver, file: SelectedFile): String {
val digest = MessageDigest.getInstance("SHA-256")
resolver.openInputStream(file.uri)?.use { input ->
val buffer = ByteArray(1024 * 1024)
while (true) {
val count = input.read(buffer)
if (count < 0) break
if (count > 0) digest.update(buffer, 0, count)
}
} ?: error("无法读取 ${file.name}")
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xFF) }
}
private fun readLine(input: BufferedInputStream): String? {
val bytes = ArrayList<Byte>(128)
while (bytes.size <= 16 * 1024) {
val value = input.read()
if (value < 0) return if (bytes.isEmpty()) null else bytes.toByteArray().toString(Charsets.US_ASCII)
if (value == '\n'.code) break
if (value != '\r'.code) bytes += value.toByte()
}
return bytes.toByteArray().toString(Charsets.US_ASCII)
}
private fun response(output: BufferedOutputStream, code: Int, type: String, body: ByteArray) {
val reason = when (code) { 200 -> "OK"; 403 -> "Forbidden"; 404 -> "Not Found"; 416 -> "Range Not Satisfiable"; else -> "Error" }
output.write("HTTP/1.1 $code $reason\r\nContent-Type: $type\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray())
output.write(body)
output.flush()
}
}
}
@@ -125,11 +125,15 @@ class WifiConnector(context: Context) {
} }
notifyStatus("正在刷新 Wi-Fi 列表并连接 ${wifi.ssid}…") notifyStatus("正在刷新 Wi-Fi 列表并连接 ${wifi.ssid}…")
val specifier = try { val specifier = try {
WifiNetworkSpecifier.Builder() val builder = WifiNetworkSpecifier.Builder()
.setSsid(wifi.ssid) .setSsid(wifi.ssid)
.setWpa2Passphrase(wifi.passphrase)
.setIsHiddenSsid(false) .setIsHiddenSsid(false)
.build() if (wifi.security == "WPA3" && Build.VERSION.SDK_INT >= 29) {
builder.setWpa3Passphrase(wifi.passphrase)
} else {
builder.setWpa2Passphrase(wifi.passphrase)
}
builder.build()
} catch (e: Exception) { } catch (e: Exception) {
notifyUnavailable("配网参数无效:${e.message}") notifyUnavailable("配网参数无效:${e.message}")
return return
@@ -246,6 +250,10 @@ class WifiConnector(context: Context) {
@Suppress("DEPRECATION", "MissingPermission") @Suppress("DEPRECATION", "MissingPermission")
private fun connectLegacy(run: Int, wifi: WifiCredentials) { private fun connectLegacy(run: Int, wifi: WifiCredentials) {
if (wifi.security == "WPA3") {
notifyUnavailable("当前 Android 版本不支持自动加入 WPA3 临时热点;请让两台手机先连接同一个普通 Wi-Fi 后重试。")
return
}
notifyStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…") notifyStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
try { try {
if (!wifiManager.isWifiEnabled) { if (!wifiManager.isWifiEnabled) {
@@ -283,14 +291,14 @@ class WifiConnector(context: Context) {
if (matches) { if (matches) {
val network = bestWifiNetwork() val network = bestWifiNetwork()
if (network != null && hasIpv4(connectivity.getLinkProperties(network))) { if (network != null && hasIpv4(connectivity.getLinkProperties(network))) {
notifyStatus("QFT Wi-Fi 已连接,正在快速发现电脑…") notifyStatus("QFT Wi-Fi 已连接,正在快速发现发送设备…")
currentNetwork = network currentNetwork = network
notifyAvailable(network) notifyAvailable(network)
return return
} }
} }
if (SystemClock.elapsedRealtime() - started > 15_000) { if (SystemClock.elapsedRealtime() - started > 15_000) {
notifyUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。") notifyUnavailable("连接 QFT Wi-Fi 超时。请确认发送设备的临时网络仍在运行。")
} else { } else {
handler.postDelayed({ poll() }, 250) handler.postDelayed({ poll() }, 250)
} }
@@ -310,7 +318,7 @@ class WifiConnector(context: Context) {
return return
} }
if (SystemClock.elapsedRealtime() - started > 6_000) { if (SystemClock.elapsedRealtime() - started > 6_000) {
onStatus("网络已连接但路由仍未就绪,继续尝试电脑发现…") onStatus("网络已连接但路由仍未就绪,继续尝试发送设备发现…")
done() done()
} else { } else {
handler.postDelayed({ poll() }, 120) handler.postDelayed({ poll() }, 120)
@@ -158,6 +158,36 @@ class ProtocolTest {
assertTrue(payload.endpoints.isEmpty()) assertTrue(payload.endpoints.isEmpty())
} }
@Test
fun androidPhoneShareQrRoundTripsWithoutEmbeddingTheFileQueue() {
val text = PairingProtocol.encodePhoneShare(
session = "abcdefghijklmnopqrstuvwxyz012345",
senderName = "HUAWEI Mate",
port = 41888,
endpoints = emptyList(),
wifi = WifiCredentials("QFT-Android", "0123456789abcdef", "WPA3"),
)
val payload = PairingProtocol.parse(text)!!
assertTrue(text.startsWith(PairingProtocol.PREFIX_PHONE_V2))
assertEquals(TransferDirection.PHONE_TO_PHONE, payload.direction)
assertEquals("HUAWEI Mate", payload.pcName)
assertEquals("WPA3", payload.wifi?.security)
assertNull(payload.fileName)
assertEquals("/qft/download", payload.downloadPath)
}
@Test
fun androidPhoneShareAcceptsOnlyBoundedByteRanges() {
assertEquals(0L to 9L, phoneShareRange(null, 10))
assertEquals(2L to 9L, phoneShareRange("bytes=2-", 10))
assertEquals(2L to 6L, phoneShareRange("bytes=2-6", 10))
assertNull(phoneShareRange("bytes=-3", 10))
assertNull(phoneShareRange("bytes=8-3", 10))
assertNull(phoneShareRange("bytes=10-", 10))
assertNull(phoneShareRange("items=0-2", 10))
}
@Test @Test
fun base45KnownVectors() { fun base45KnownVectors() {
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8")) assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
+35
View File
@@ -0,0 +1,35 @@
# Android → Android 真机验收(v0.5.0-dev1)
## 构建约束
在 Windows 的 Android 开发环境构建。本仓库的 macOS 封版流程不会安装或调用 Android SDK。
```powershell
cd android
.\gradlew.bat :app:testDebugUnitTest :app:assembleDebug
```
## 首轮验收
1. 两台 Android 安装同一个 `v0.5.0-dev1` APK。
2. 发送手机进入“手机 → 手机”,选择至少两个文件并调整一次顺序。
3. 点击“创建发送二维码”,允许附近 Wi-Fi/位置权限。
4. 接收手机进入“扫码直传”,扫描发送手机二维码并确认系统连接提示。
5. 核对接收顺序与发送队列一致,文件位于 `Downloads/QFT`,大小与 SHA-256 一致。
建议首轮文件组合:空文件、100 KiB 文档、20 MiB 视频、100 MiB 压缩包。
## 必测网络组合
- Android 13+ → Android 13+:`NEARBY_WIFI_DEVICES` 权限与临时热点。
- Android 8–12 → Android 10+:位置权限与 WPA2 临时热点。
- Android 7 发送端:两机先连接同一 Wi-Fi,验证自动 LAN 回落。
- 手动停止发送端热点:接收端应报连接中断,而不是无限等待。
- 传输中返回发送端首页:服务和临时热点应立即关闭。
## 当前边界
- 仅文件,不包含文件夹。
- 发送与接收页面需保持前台;尚未引入前台服务。
- LocalOnlyHotspot 没有互联网是预期行为,文件只在本地链路传输。
- Android ↔ iOS 不在本开发版本范围内。
+24
View File
@@ -98,3 +98,27 @@ 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`. 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. 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.
## 6. Android → Android (`QFTPHONE2`, v0.5.0-dev1)
The sender starts an authenticated local HTTP service and encodes only session,
port, sender identity and optional LocalOnlyHotspot credentials in the QR. The
file queue is fetched after pairing so QR density is independent of queue size:
```text
GET /qft/ping
GET /qft/phone/manifest
GET /qft/phone/download/<queue-index>
Range: bytes=<start>-<end>
X-QFT-Token: <one-time session>
```
The manifest contains a bounded ordered list of `name`, `size`, `sha256` and a
server-generated fixed download path. The receiver does not accept arbitrary
paths from the QR or manifest: entry `N` must use `/qft/phone/download/N`.
Android 8+ prefers a system LocalOnlyHotspot. Android 7, or a hotspot failure,
falls back to literal private IPv4 endpoints on the current LAN. WPA2/WPA3
credentials are distinguished in `w[2]`. The receiver then reuses the existing
parallel Range ledger, retries and SHA-256-before-publish behavior for every
file, processing items in manifest order.
+7 -1
View File
@@ -7,6 +7,8 @@ wifi=(ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_te
download=(ROOT/'android/app/src/main/java/com/qft/optical/DownloadClient.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() 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()
queue=(ROOT/'android/app/src/main/java/com/qft/optical/TransferQueue.kt').read_text() queue=(ROOT/'android/app/src/main/java/com/qft/optical/TransferQueue.kt').read_text()
phone_server=(ROOT/'android/app/src/main/java/com/qft/optical/PhoneShareServer.kt').read_text()
phone_hotspot=(ROOT/'android/app/src/main/java/com/qft/optical/PhoneHotspotController.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() 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) assert re.search(r'minSdk\s*=\s*24',gradle)
assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest
@@ -19,6 +21,10 @@ assert 'requestNetwork(request, cb)' in wifi and 'delivered.set(false)' in wifi
assert 'wifiManager.startScan()' in wifi and '.setIsHiddenSsid(false)' in wifi assert 'wifiManager.startScan()' in wifi and '.setIsHiddenSsid(false)' in wifi
assert 'probeConnectedNetwork' in upload and 'workers = 48' in upload assert 'probeConnectedNetwork' in upload and 'workers = 48' in upload
assert 'awaitGatewayEndpoints' not in main assert 'awaitGatewayEndpoints' not in main
assert 'QFTPHONE2:' in (ROOT/'android/app/src/main/java/com/qft/optical/PairingProtocol.kt').read_text()
assert 'startLocalOnlyHotspot' in phone_hotspot and 'PhoneShareServer.create' in main
assert '/qft/phone/manifest' in phone_server and '/qft/phone/download/' in phone_server
assert 'startDownloadsFromPhone' in main and 'downloadPath = item.path' in main
assert 'if (mode == ScannerMode.PAIR) Size(960, 720) else Size(640, 480)' in main and 'Size(960, 540)' not in main assert 'if (mode == ScannerMode.PAIR) Size(960, 720) else 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 '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 assert '设备拒绝显式高帧率请求' in main and 'fallbackAnalysis' in main
@@ -34,4 +40,4 @@ assert 'row.translationY' in main and 'container.removeView(row)' not in main
assert 'BB8' in base45 or 'ALPHABET' in base45 assert 'BB8' in base45 or 'ALPHABET' in base45
all_kotlin='\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt')) all_kotlin='\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt'))
assert 'java.util.Base64' not in all_kotlin assert 'java.util.Base64' not in all_kotlin
print('PASS Android static guards: API24+, fast-pair/subnet discovery, crash-safe sortable upload queue, QFT2/Base45, dynamic lock/refocus, legacy/new Wi-Fi compatibility') print('PASS Android static guards: API24+, Android-to-Android hotspot/LAN queue transfer, fast-pair/subnet discovery, crash-safe sortable queue, QFT2/Base45, legacy/new Wi-Fi compatibility')
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Protocol/security guards for Android → Android v0.5 phone sharing."""
from pathlib import Path
import base64
import hashlib
import json
ROOT = Path(__file__).resolve().parents[1]
pairing = (ROOT / "android/app/src/main/java/com/qft/optical/PairingProtocol.kt").read_text()
server = (ROOT / "android/app/src/main/java/com/qft/optical/PhoneShareServer.kt").read_text()
download = (ROOT / "android/app/src/main/java/com/qft/optical/DownloadClient.kt").read_text()
session = base64.urlsafe_b64encode(bytes(range(24))).decode().rstrip("=")
payload = {
"v": 2,
"s": session,
"n": "Android Sender",
"p": 41888,
"d": "m",
"w": ["QFT-Android", "0123456789abcdef", "WPA2"],
}
qr = "QFTPHONE2:" + base64.urlsafe_b64encode(
json.dumps(payload, separators=(",", ":")).encode()
).decode().rstrip("=")
assert len(qr) < 300, len(qr)
blob = b"android-to-android-range-test" * 1000
sha = hashlib.sha256(blob).hexdigest()
manifest = {
"v": 2,
"files": [
{"name": "sample.bin", "size": len(blob), "sha256": sha, "path": "/qft/phone/download/0"}
],
}
assert manifest["files"][0]["path"] == "/qft/phone/download/0"
rebuilt = bytearray(len(blob))
ranges = [(len(blob) // 2, len(blob)), (0, len(blob) // 3), (len(blob) // 3, len(blob) // 2)]
for start, end in ranges:
rebuilt[start:end] = blob[start:end]
assert bytes(rebuilt) == blob
assert hashlib.sha256(rebuilt).hexdigest() == sha
assert 'const val PREFIX_PHONE_V2 = "QFTPHONE2:"' in pairing
assert '"m" -> TransferDirection.PHONE_TO_PHONE' in pairing
assert 'require(item.getString("path") == expectedPath)' in server
assert 'headers["x-qft-token"] != session' in server
assert 'Range: bytes=<start>-<end>' not in server # implementation, not documentation placeholder
assert 'baseUrl + pairing.downloadPath' in download
assert 'digest(downloadPath.toByteArray' in download
print(f"PASS Android phone share: compact QR={len(qr)} chars, authenticated fixed manifest paths, per-file partial isolation, SHA-256={sha[:12]}…")
+1
View File
@@ -8,6 +8,7 @@ scripts = [
'pairing_selftest.py', 'pairing_selftest.py',
'parallel_upload_selftest.py', 'parallel_upload_selftest.py',
'parallel_download_selftest.py', 'parallel_download_selftest.py',
'phone_share_selftest.py',
'udp_discovery_selftest.py', 'udp_discovery_selftest.py',
'local_transfer_integration_selftest.py', 'local_transfer_integration_selftest.py',
'memory_budget_selftest.py', 'memory_budget_selftest.py',