feat: add Android to Android phone sharing
This commit is contained in:
@@ -12,8 +12,8 @@ android {
|
||||
applicationId = "com.qft.optical"
|
||||
minSdk = 24
|
||||
targetSdk = 35
|
||||
versionCode = 23
|
||||
versionName = "0.4.16"
|
||||
versionCode = 24
|
||||
versionName = "0.5.0-dev1"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ object DownloadClient {
|
||||
val expectedName = requireNotNull(pairing.fileName)
|
||||
val expectedSize = requireNotNull(pairing.fileSize)
|
||||
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("无法创建接收缓存目录") }
|
||||
if (partial.length() > expectedSize) discardTransferState(partial)
|
||||
|
||||
@@ -379,7 +379,7 @@ object DownloadClient {
|
||||
abortReason: () -> String?,
|
||||
) {
|
||||
val end = start + length - 1L
|
||||
val conn = open(network, URL("$baseUrl/qft/download"))
|
||||
val conn = open(network, URL(baseUrl + pairing.downloadPath))
|
||||
try {
|
||||
conn.requestMethod = "GET"
|
||||
conn.connectTimeout = 8_000
|
||||
@@ -466,7 +466,7 @@ object DownloadClient {
|
||||
onProgress: (received: Long, total: Long) -> Unit,
|
||||
) {
|
||||
val requestedOffset = partial.length().coerceIn(0L, expectedSize)
|
||||
val conn = open(network, URL("$baseUrl/qft/download"))
|
||||
val conn = open(network, URL(baseUrl + pairing.downloadPath))
|
||||
try {
|
||||
conn.requestMethod = "GET"
|
||||
conn.connectTimeout = 5_000
|
||||
@@ -482,7 +482,7 @@ object DownloadClient {
|
||||
val resumed = code == HttpURLConnection.HTTP_PARTIAL
|
||||
if (code != HttpURLConnection.HTTP_OK && !resumed) {
|
||||
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
|
||||
error("电脑下载服务返回 HTTP $code${message?.let { ": $it" } ?: ""}")
|
||||
error("发送端下载服务返回 HTTP $code${message?.let { ": $it" } ?: ""}")
|
||||
}
|
||||
|
||||
// Older desktop binaries return 200 even with Range. Restart only
|
||||
@@ -658,7 +658,7 @@ object DownloadClient {
|
||||
val offset = ledger.chunkOffset(index)
|
||||
val length = ledger.chunkLength(index)
|
||||
val end = offset + length - 1L
|
||||
val conn = open(network, URL("$baseUrl/qft/download"))
|
||||
val conn = open(network, URL(baseUrl + pairing.downloadPath))
|
||||
try {
|
||||
conn.requestMethod = "GET"
|
||||
conn.connectTimeout = 5_000
|
||||
@@ -672,7 +672,7 @@ object DownloadClient {
|
||||
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" } ?: ""}")
|
||||
error("发送端下载服务未返回并行 Range(HTTP $code)${message?.let { ": $it" } ?: ""}")
|
||||
}
|
||||
val expectedRange = "bytes $offset-$end/$expectedSize"
|
||||
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
|
||||
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 {
|
||||
|
||||
@@ -21,6 +21,7 @@ import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Button
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.ProgressBar
|
||||
import android.widget.ScrollView
|
||||
@@ -48,6 +49,7 @@ class MainActivity : ComponentActivity() {
|
||||
private val cameraExecutor = Executors.newSingleThreadExecutor()
|
||||
private val transferExecutor = Executors.newSingleThreadExecutor()
|
||||
private val wifiConnector by lazy { WifiConnector(this) }
|
||||
private val phoneHotspot by lazy { PhoneHotspotController(this) }
|
||||
private lateinit var assembler: SessionAssembler
|
||||
|
||||
private var cameraProvider: ProcessCameraProvider? = null
|
||||
@@ -91,6 +93,9 @@ class MainActivity : ComponentActivity() {
|
||||
private var downloadStatusText: TextView? = null
|
||||
@Volatile private var downloadRunning = false
|
||||
@Volatile private var uploadRunning = false
|
||||
@Volatile private var phoneShareRunning = false
|
||||
private var phoneShareServer: PhoneShareServer? = null
|
||||
private var phoneShareStatusText: TextView? = null
|
||||
/** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。
|
||||
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
|
||||
@Volatile private var transferAbortReason: String? = null
|
||||
@@ -102,8 +107,10 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
val pair = pendingPair
|
||||
if (granted && pair?.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||
connectPair(pair)
|
||||
val receivingFromNetwork = pair?.direction == TransferDirection.DOWNLOAD_TO_PHONE ||
|
||||
pair?.direction == TransferDirection.PHONE_TO_PHONE
|
||||
if (granted && receivingFromNetwork && pair != null) {
|
||||
ensureWifiPermissionThenConnect(pair)
|
||||
return@registerForActivityResult
|
||||
}
|
||||
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 ->
|
||||
if (uploadRunning) {
|
||||
sendStatusText?.text = "传输已经开始,当前队列已锁定"
|
||||
@@ -134,6 +147,7 @@ class MainActivity : ComponentActivity() {
|
||||
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
|
||||
} else if (selectedFiles.isNotEmpty()) {
|
||||
sendStatusText?.text = "已选择 ${selectedFiles.size} 个文件,点击“开始传输”"
|
||||
phoneShareStatusText?.text = "已选择 ${selectedFiles.size} 个文件,可以创建发送二维码"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +168,9 @@ class MainActivity : ComponentActivity() {
|
||||
pairConsumed.set(false)
|
||||
wifiConnector.releaseHighPerfLock()
|
||||
wifiConnector.release()
|
||||
phoneShareServer?.close()
|
||||
phoneShareServer = null
|
||||
phoneHotspot.close()
|
||||
pendingPair = null
|
||||
connectedNetwork = null
|
||||
connectedBaseUrl = null
|
||||
@@ -161,6 +178,8 @@ class MainActivity : ComponentActivity() {
|
||||
downloadStatusText = null
|
||||
selectedFiles.clear()
|
||||
uploadRunning = false
|
||||
phoneShareRunning = false
|
||||
phoneShareStatusText = null
|
||||
sendFilesContainer = null
|
||||
sendAddButton = null
|
||||
sendClearButton = null
|
||||
@@ -189,11 +208,18 @@ class MainActivity : ComponentActivity() {
|
||||
root.addView(space(16))
|
||||
root.addView(modeCard(
|
||||
title = "扫码直传",
|
||||
badge = "手机上传 / 电脑下发 · 自动配网 · 快速发现",
|
||||
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
|
||||
buttonLabel = "扫描电脑二维码",
|
||||
badge = "电脑互传 / 手机互传 · 自动配网 · 快速发现",
|
||||
body = "扫描电脑或另一台 Android 手机的二维码后自动连接 QFT 本地网络。电脑接收码会进入选文件上传;电脑/手机发送码会自动下载到 Downloads/QFT。",
|
||||
buttonLabel = "扫描接收二维码",
|
||||
) { requestScanner(ScannerMode.PAIR) })
|
||||
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(
|
||||
title = "接收文件柜",
|
||||
badge = "Downloads/QFT · 图片/视频/PDF/Office/压缩包等",
|
||||
@@ -202,7 +228,7 @@ class MainActivity : ComponentActivity() {
|
||||
) { showReceivedFiles() })
|
||||
root.addView(space(22))
|
||||
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) })
|
||||
}
|
||||
|
||||
@@ -529,7 +555,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
val back = button("‹ 返回").apply { setOnClickListener { showHome() } }
|
||||
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) })
|
||||
root.addView(top, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
|
||||
|
||||
@@ -540,12 +566,12 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
deviceText = text(
|
||||
if (mode == ScannerMode.OPTICAL) "接收设备:$receiverDeviceLabel\n发送设备:等待 QFT2 MANIFEST…"
|
||||
else "目标:等待 QFTPAIR2 配对二维码",
|
||||
else "目标:等待电脑或 Android 配对二维码",
|
||||
14f, Color.WHITE
|
||||
)
|
||||
statusText = text(
|
||||
if (mode == ScannerMode.OPTICAL) "让电脑的单个大二维码占取景框 50% 以上,识别后会自动锁定区域"
|
||||
else "扫描 Windows“手机传电脑”页面上的二维码",
|
||||
else "扫描电脑或另一台 Android 显示的 QFT 配对二维码",
|
||||
14f, MUTED
|
||||
)
|
||||
progress = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
|
||||
@@ -586,7 +612,7 @@ class MainActivity : ComponentActivity() {
|
||||
runOnUiThread {
|
||||
stopCamera()
|
||||
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
|
||||
) {
|
||||
requestLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||||
@@ -655,8 +681,8 @@ class MainActivity : ComponentActivity() {
|
||||
// 不使用二维码地址,也不猜测 192.168.137/49 网段。
|
||||
runOnUiThread {
|
||||
updateConnectingStatus(
|
||||
if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证网关和电脑…"
|
||||
else "网络已就绪 · 正在连接同网段电脑…"
|
||||
if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证发送设备…"
|
||||
else "网络已就绪 · 正在连接同网段发送设备…"
|
||||
)
|
||||
}
|
||||
val direct = if (dedicatedWifi) {
|
||||
@@ -683,7 +709,7 @@ class MainActivity : ComponentActivity() {
|
||||
runOnUiThread {
|
||||
updateConnectingStatus(
|
||||
if (dedicatedWifi) "专用网关正在初始化 · 仅在 QFT 子网内自动发现…"
|
||||
else "同网段地址未应答 · 正在 UDP 快速发现电脑…"
|
||||
else "同网段地址未应答 · 正在 UDP 快速发现发送设备…"
|
||||
)
|
||||
}
|
||||
discovered = UploadClient.discoverUdp(
|
||||
@@ -699,8 +725,8 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
runOnUiThread {
|
||||
updateConnectingStatus(
|
||||
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
|
||||
else "仅在当前连接的 QFT 子网内并行查找电脑…"
|
||||
if (discovered != null) "已通过 UDP 找到发送设备 · 正在验证服务…"
|
||||
else "仅在当前连接的 QFT 子网内并行查找发送设备…"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -724,26 +750,34 @@ class MainActivity : ComponentActivity() {
|
||||
val diagnosis = buildString {
|
||||
append(
|
||||
if (dedicatedWifi) {
|
||||
"QFT 专用 Wi-Fi 已连接,但在该专用网络的实际网关和子网内未找到服务。\n\n"
|
||||
"QFT 专用 Wi-Fi 已连接,但在该专用网络的实际网关和子网内未找到发送服务。\n\n"
|
||||
} else {
|
||||
"Wi-Fi 已连接,但在当前局域网内未找到 QFT 服务。\n\n"
|
||||
}
|
||||
)
|
||||
append("手机侧:").append(wifiConnector.describeNetwork(network)).append("\n")
|
||||
append("连接模式:")
|
||||
append(if (dedicatedWifi) "QFT 专用 Wi-Fi(不使用二维码/电脑本地网卡地址)" else "当前局域网备用模式")
|
||||
append(if (dedicatedWifi) "QFT 专用 Wi-Fi(不使用二维码内的旧网卡地址)" else "当前局域网备用模式")
|
||||
append("\n探测过的网关地址:")
|
||||
append(gateways.joinToString("、").ifEmpty { "(无)" })
|
||||
append("\n子网扫描范围:").append(subnet.size).append(" 个地址\n\n")
|
||||
append("请对照检查:① Windows 上 QFT Direct 是否仍显示已就绪;")
|
||||
append("② 防火墙是否放行 qft-desktop.exe 的当前专用网络类型;")
|
||||
append("③ 手机是否仍连接二维码内的 QFT 专用网络。")
|
||||
if (pair.direction == TransferDirection.PHONE_TO_PHONE) {
|
||||
append("请对照检查:① 发送手机是否仍停留在二维码页面;")
|
||||
append("② 两台手机是否仍连接二维码内的 QFT 临时网络;")
|
||||
append("③ 发送手机是否关闭了省电/热点。")
|
||||
} else {
|
||||
append("请对照检查:① Windows 上 QFT Direct 是否仍显示已就绪;")
|
||||
append("② 防火墙是否放行 qft-desktop.exe 的当前专用网络类型;")
|
||||
append("③ 手机是否仍连接二维码内的 QFT 专用网络。")
|
||||
}
|
||||
}
|
||||
showPairError(pair, diagnosis)
|
||||
} else {
|
||||
connectedBaseUrl = base
|
||||
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||
startDownloadFromPc(pair, base)
|
||||
} else if (pair.direction == TransferDirection.PHONE_TO_PHONE) {
|
||||
startDownloadsFromPhone(pair, base)
|
||||
} else {
|
||||
showSendReady(pair, base)
|
||||
}
|
||||
@@ -756,7 +790,7 @@ class MainActivity : ComponentActivity() {
|
||||
// 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) {
|
||||
if (pair.direction != TransferDirection.UPLOAD_TO_PC && downloadRunning) {
|
||||
transferAbortReason = message
|
||||
downloadStatusText?.apply {
|
||||
text = "QFT 本地网络已断开,正在结束当前下载请求…"
|
||||
@@ -771,12 +805,13 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
private fun showConnecting(pair: PairingPayload, message: String) {
|
||||
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(space(22))
|
||||
root.addView(card().apply {
|
||||
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.session.take(10)}…", 12f, MUTED), matchWrap(top = 5))
|
||||
})
|
||||
@@ -816,6 +851,242 @@ class MainActivity : ComponentActivity() {
|
||||
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) {
|
||||
val root = pageColumn()
|
||||
root.addView(text("已连接电脑", 28f, Color.WHITE, true))
|
||||
@@ -1049,6 +1320,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun renderSelectedFiles() {
|
||||
val phoneMode = phoneShareStatusText != null
|
||||
val total = selectedFiles.sumOf { it.size }
|
||||
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
||||
"请先选择需要传输的文件"
|
||||
@@ -1097,9 +1369,10 @@ class MainActivity : ComponentActivity() {
|
||||
sendButton?.text = when {
|
||||
uploadRunning -> "传输中 · 队列已锁定"
|
||||
selectedFiles.isEmpty() -> "请先添加文件"
|
||||
phoneMode -> "创建 ${selectedFiles.size} 个文件的发送二维码"
|
||||
else -> "开始传输 ${selectedFiles.size} 个文件"
|
||||
}
|
||||
sendButton?.isEnabled = connectedBaseUrl != null && selectedFiles.isNotEmpty() && !uploadRunning
|
||||
sendButton?.isEnabled = (phoneMode || connectedBaseUrl != null) && selectedFiles.isNotEmpty() && !uploadRunning
|
||||
}
|
||||
|
||||
private fun installFileQueueDrag(
|
||||
@@ -1341,6 +1614,8 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onDestroy() {
|
||||
assembler.reset()
|
||||
wifiConnector.release()
|
||||
phoneShareServer?.close()
|
||||
phoneHotspot.close()
|
||||
stopCamera()
|
||||
cameraExecutor.shutdownNow()
|
||||
transferExecutor.shutdownNow()
|
||||
|
||||
@@ -21,23 +21,29 @@ data class PairingPayload(
|
||||
val fileName: String? = null,
|
||||
val fileSize: Long? = 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 {
|
||||
const val PREFIX_V2 = "QFTPAIR2:"
|
||||
const val PREFIX_SEND_V2 = "QFTSEND2:"
|
||||
const val PREFIX_PHONE_V2 = "QFTPHONE2:"
|
||||
const val PREFIX_V1 = "QFTPAIR1:"
|
||||
|
||||
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? {
|
||||
if (text.length > 4096) return null
|
||||
return when {
|
||||
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_PHONE_V2) -> parseV2(text.substring(PREFIX_PHONE_V2.length), TransferDirection.PHONE_TO_PHONE)
|
||||
text.startsWith(PREFIX_V1) -> parseV1(text.substring(PREFIX_V1.length))
|
||||
else -> null
|
||||
}
|
||||
@@ -53,6 +59,7 @@ object PairingProtocol {
|
||||
val direction = when (encodedDirection) {
|
||||
"u" -> TransferDirection.UPLOAD_TO_PC
|
||||
"d" -> TransferDirection.DOWNLOAD_TO_PHONE
|
||||
"m" -> TransferDirection.PHONE_TO_PHONE
|
||||
else -> return null
|
||||
}
|
||||
if (direction != expectedDirection) return null
|
||||
@@ -67,7 +74,9 @@ object PairingProtocol {
|
||||
val ssid = wifiArray.optString(0)
|
||||
val passphrase = wifiArray.optString(1)
|
||||
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
|
||||
|
||||
val endpoints = mutableListOf<String>()
|
||||
@@ -157,6 +166,34 @@ object PairingProtocol {
|
||||
|
||||
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 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}…")
|
||||
val specifier = try {
|
||||
WifiNetworkSpecifier.Builder()
|
||||
val builder = WifiNetworkSpecifier.Builder()
|
||||
.setSsid(wifi.ssid)
|
||||
.setWpa2Passphrase(wifi.passphrase)
|
||||
.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) {
|
||||
notifyUnavailable("配网参数无效:${e.message}")
|
||||
return
|
||||
@@ -246,6 +250,10 @@ class WifiConnector(context: Context) {
|
||||
|
||||
@Suppress("DEPRECATION", "MissingPermission")
|
||||
private fun connectLegacy(run: Int, wifi: WifiCredentials) {
|
||||
if (wifi.security == "WPA3") {
|
||||
notifyUnavailable("当前 Android 版本不支持自动加入 WPA3 临时热点;请让两台手机先连接同一个普通 Wi-Fi 后重试。")
|
||||
return
|
||||
}
|
||||
notifyStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
|
||||
try {
|
||||
if (!wifiManager.isWifiEnabled) {
|
||||
@@ -283,14 +291,14 @@ class WifiConnector(context: Context) {
|
||||
if (matches) {
|
||||
val network = bestWifiNetwork()
|
||||
if (network != null && hasIpv4(connectivity.getLinkProperties(network))) {
|
||||
notifyStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
|
||||
notifyStatus("QFT Wi-Fi 已连接,正在快速发现发送设备…")
|
||||
currentNetwork = network
|
||||
notifyAvailable(network)
|
||||
return
|
||||
}
|
||||
}
|
||||
if (SystemClock.elapsedRealtime() - started > 15_000) {
|
||||
notifyUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
|
||||
notifyUnavailable("连接 QFT Wi-Fi 超时。请确认发送设备的临时网络仍在运行。")
|
||||
} else {
|
||||
handler.postDelayed({ poll() }, 250)
|
||||
}
|
||||
@@ -310,7 +318,7 @@ class WifiConnector(context: Context) {
|
||||
return
|
||||
}
|
||||
if (SystemClock.elapsedRealtime() - started > 6_000) {
|
||||
onStatus("网络已连接但路由仍未就绪,继续尝试电脑发现…")
|
||||
onStatus("网络已连接但路由仍未就绪,继续尝试发送设备发现…")
|
||||
done()
|
||||
} else {
|
||||
handler.postDelayed({ poll() }, 120)
|
||||
|
||||
@@ -158,6 +158,36 @@ class ProtocolTest {
|
||||
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
|
||||
fun base45KnownVectors() {
|
||||
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
|
||||
|
||||
Reference in New Issue
Block a user