fix: add legacy-compatible Android phone link
This commit is contained in:
@@ -12,8 +12,8 @@ android {
|
||||
applicationId = "com.qft.optical"
|
||||
minSdk = 24
|
||||
targetSdk = 35
|
||||
versionCode = 26
|
||||
versionName = "0.5.0-dev3"
|
||||
versionCode = 27
|
||||
versionName = "0.5.0-dev4"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
|
||||
<uses-feature android:name="android.hardware.camera.any" android:required="true" />
|
||||
<uses-feature android:name="android.hardware.wifi" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.wifi.direct" android:required="false" />
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
|
||||
@@ -181,7 +181,7 @@ object DownloadClient {
|
||||
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
|
||||
discardTransferState(partial)
|
||||
if (round + 1 >= VERIFY_ROUNDS) {
|
||||
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码")
|
||||
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让发送端重新创建传输")
|
||||
}
|
||||
onPhase("校验未通过,正在重新完整下载…")
|
||||
}
|
||||
@@ -550,7 +550,12 @@ object DownloadClient {
|
||||
onProgress(initial, expectedSize)
|
||||
if (ledger.allComplete()) return
|
||||
|
||||
val workers = ledger.totalChunks.coerceAtMost(RANGE_WORKERS).coerceAtLeast(1)
|
||||
// Some Android 7–9 DocumentsProvider implementations expose a stream
|
||||
// that is individually seekable but corrupts data when the same URI is
|
||||
// opened concurrently. Phone → phone therefore downloads its ranges in
|
||||
// deterministic order on one worker. PC senders keep the 8-way path.
|
||||
val workerLimit = if (pairing.downloadPath.startsWith("/qft/phone/download/")) 1 else RANGE_WORKERS
|
||||
val workers = ledger.totalChunks.coerceAtMost(workerLimit).coerceAtLeast(1)
|
||||
Log.i(TAG, "parallel start: chunks=${ledger.totalChunks}, workers=$workers, completed=$initial/$expectedSize")
|
||||
val pool = Executors.newFixedThreadPool(workers)
|
||||
val next = AtomicInteger(0)
|
||||
@@ -672,7 +677,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) {
|
||||
|
||||
@@ -228,7 +228,7 @@ class MainActivity : ComponentActivity() {
|
||||
) { showReceivedFiles() })
|
||||
root.addView(space(22))
|
||||
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
||||
root.addView(text("QFT v0.5.0-dev3 · Android 7+ 到最新", 12f, MUTED))
|
||||
root.addView(text("QFT v0.5.0-dev4 · Android 7+ 到最新", 12f, MUTED))
|
||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||
}
|
||||
|
||||
@@ -925,10 +925,6 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -1041,7 +1037,10 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
root.addView(phoneShareStatusText)
|
||||
root.addView(text(
|
||||
if (wifi != null) "临时网络:${wifi.ssid}\n发送服务端口:${server.port}"
|
||||
if (wifi != null) {
|
||||
val link = if (wifi.ssid.startsWith("DIRECT-")) "兼容专用网络(2.4GHz / WPA2)" else "备用临时网络"
|
||||
"$link:${wifi.ssid}\n发送服务端口:${server.port}"
|
||||
}
|
||||
else "连接方式:两台手机当前同一 Wi-Fi\n发送服务端口:${server.port}",
|
||||
12f, MUTED,
|
||||
), matchWrap(top = 8))
|
||||
|
||||
@@ -2,15 +2,32 @@ package com.qft.optical
|
||||
|
||||
import android.content.Context
|
||||
import android.net.wifi.WifiManager
|
||||
import android.net.wifi.p2p.WifiP2pConfig
|
||||
import android.net.wifi.p2p.WifiP2pManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import androidx.annotation.RequiresApi
|
||||
import java.security.SecureRandom
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/** Owns an Android LocalOnlyHotspot reservation for one phone-share session. */
|
||||
/**
|
||||
* Owns the phone-share access point.
|
||||
*
|
||||
* A second LocalOnlyHotspot request cannot create a second SSID: Android shares
|
||||
* one underlying hotspot. QFT therefore prefers a Wi-Fi Direct group-owner AP,
|
||||
* which is WPA2 and accepts legacy Wi-Fi stations. Android 10+ senders force it
|
||||
* onto 2.4 GHz so Android 7-era receivers can see the same single network.
|
||||
* LocalOnlyHotspot remains a fallback for OEMs that disable P2P group creation.
|
||||
*/
|
||||
class PhoneHotspotController(context: Context) {
|
||||
private val wifiManager = context.applicationContext.getSystemService(WifiManager::class.java)
|
||||
private val appContext = context.applicationContext
|
||||
private val wifiManager = appContext.getSystemService(WifiManager::class.java)
|
||||
private val p2pManager = appContext.getSystemService(Context.WIFI_P2P_SERVICE) as? WifiP2pManager
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var reservation: AutoCloseable? = null
|
||||
private var p2pChannel: WifiP2pManager.Channel? = null
|
||||
private var generation = 0
|
||||
|
||||
fun start(
|
||||
@@ -19,16 +36,136 @@ class PhoneHotspotController(context: Context) {
|
||||
) {
|
||||
close()
|
||||
val run = ++generation
|
||||
if (Build.VERSION.SDK_INT < 26) {
|
||||
onFailed("Android 7 不支持应用内临时热点,将使用当前局域网")
|
||||
startCompatibilityGroup(
|
||||
run = run,
|
||||
onStarted = onStarted,
|
||||
onFallback = { reason ->
|
||||
if (run != generation) return@startCompatibilityGroup
|
||||
if (Build.VERSION.SDK_INT >= 26) {
|
||||
startLocalOnlyHotspot(run, onStarted) { localReason ->
|
||||
onFailed("$reason;$localReason")
|
||||
}
|
||||
} else {
|
||||
onFailed("$reason;Android 7 无法创建备用临时热点,将使用当前局域网")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Suppress("MissingPermission")
|
||||
private fun startCompatibilityGroup(
|
||||
run: Int,
|
||||
onStarted: (WifiCredentials) -> Unit,
|
||||
onFallback: (String) -> Unit,
|
||||
) {
|
||||
val manager = p2pManager ?: run {
|
||||
onFallback("设备没有 Wi-Fi Direct 服务")
|
||||
return
|
||||
}
|
||||
startApi26(run, onStarted, onFailed)
|
||||
val terminal = AtomicBoolean(false)
|
||||
var localChannel: WifiP2pManager.Channel? = null
|
||||
|
||||
fun fallback(reason: String) {
|
||||
if (run != generation || !terminal.compareAndSet(false, true)) return
|
||||
val channel = localChannel
|
||||
if (p2pChannel === channel) p2pChannel = null
|
||||
if (channel != null) {
|
||||
try {
|
||||
manager.removeGroup(channel, object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() = onFallback(reason)
|
||||
override fun onFailure(removeReason: Int) = onFallback(reason)
|
||||
})
|
||||
} catch (_: Exception) {
|
||||
onFallback(reason)
|
||||
}
|
||||
} else {
|
||||
onFallback(reason)
|
||||
}
|
||||
}
|
||||
|
||||
val channel = try {
|
||||
manager.initialize(appContext, Looper.getMainLooper()) {
|
||||
fallback("Wi-Fi Direct 通道已断开")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
onFallback("初始化兼容专用网络失败:${e.message ?: e.javaClass.simpleName}")
|
||||
return
|
||||
}
|
||||
localChannel = channel
|
||||
p2pChannel = channel
|
||||
|
||||
val createListener = object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() {
|
||||
val deadline = SystemClock.elapsedRealtime() + 12_000L
|
||||
fun pollGroup() {
|
||||
if (run != generation || terminal.get()) return
|
||||
try {
|
||||
manager.requestGroupInfo(channel) { group ->
|
||||
if (run != generation || terminal.get()) return@requestGroupInfo
|
||||
val ssid = group?.networkName.orEmpty()
|
||||
val passphrase = group?.passphrase.orEmpty()
|
||||
if (group?.isGroupOwner == true && ssid.isNotBlank() && passphrase.length in 8..63) {
|
||||
if (!terminal.compareAndSet(false, true)) return@requestGroupInfo
|
||||
onStarted(WifiCredentials(ssid, passphrase, "WPA2"))
|
||||
} else if (SystemClock.elapsedRealtime() >= deadline) {
|
||||
fallback("创建 2.4GHz/WPA2 兼容专用网络超时")
|
||||
} else {
|
||||
handler.postDelayed({ pollGroup() }, 180L)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallback("读取兼容专用网络信息失败:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
pollGroup()
|
||||
}
|
||||
|
||||
override fun onFailure(reason: Int) {
|
||||
fallback("系统拒绝创建 2.4GHz/WPA2 兼容专用网络(错误 $reason)")
|
||||
}
|
||||
}
|
||||
|
||||
fun createGroup() {
|
||||
if (run != generation || terminal.get()) return
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
manager.createGroup(channel, compatibilityConfig(), createListener)
|
||||
} else {
|
||||
// API 24–28 creates the interoperable legacy-client group
|
||||
// with system-generated DIRECT-* credentials.
|
||||
manager.createGroup(channel, createListener)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallback("启动兼容专用网络失败:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
|
||||
// A stale persistent P2P group can keep old credentials or a 5 GHz
|
||||
// channel. Remove it before creating this session's 2.4 GHz group.
|
||||
try {
|
||||
manager.removeGroup(channel, object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() = createGroup()
|
||||
override fun onFailure(reason: Int) = createGroup()
|
||||
})
|
||||
} catch (_: Exception) {
|
||||
createGroup()
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(29)
|
||||
private fun compatibilityConfig(): WifiP2pConfig {
|
||||
val random = ByteArray(12).also { SecureRandom().nextBytes(it) }
|
||||
val token = random.joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
||||
return WifiP2pConfig.Builder()
|
||||
.setNetworkName("DIRECT-QF-QFT${token.take(6)}")
|
||||
.setPassphrase(token.take(16))
|
||||
.setGroupOperatingBand(WifiP2pConfig.GROUP_OWNER_BAND_2GHZ)
|
||||
.build()
|
||||
}
|
||||
|
||||
@RequiresApi(26)
|
||||
@Suppress("MissingPermission", "DEPRECATION")
|
||||
private fun startApi26(
|
||||
private fun startLocalOnlyHotspot(
|
||||
run: Int,
|
||||
onStarted: (WifiCredentials) -> Unit,
|
||||
onFailed: (String) -> Unit,
|
||||
@@ -57,7 +194,7 @@ class PhoneHotspotController(context: Context) {
|
||||
val passphrase = identity.second.orEmpty()
|
||||
if (ssid.isBlank() || passphrase.length !in 8..63) {
|
||||
close()
|
||||
onFailed("系统临时热点没有返回有效的名称或密码")
|
||||
onFailed("系统备用热点没有返回有效的名称或密码")
|
||||
return
|
||||
}
|
||||
onStarted(WifiCredentials(ssid, passphrase, identity.third))
|
||||
@@ -66,26 +203,31 @@ class PhoneHotspotController(context: Context) {
|
||||
override fun onStopped() {
|
||||
if (run == generation) {
|
||||
reservation = null
|
||||
onFailed("系统已停止 QFT 临时热点")
|
||||
onFailed("系统已停止 QFT 备用临时热点")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailed(reason: Int) {
|
||||
if (run == generation) {
|
||||
onFailed("系统无法创建临时热点(错误 $reason)")
|
||||
}
|
||||
if (run == generation) onFailed("系统无法创建备用临时热点(错误 $reason)")
|
||||
}
|
||||
},
|
||||
Handler(Looper.getMainLooper()),
|
||||
handler,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
onFailed("启动临时热点失败:${e.message ?: e.javaClass.simpleName}")
|
||||
onFailed("启动备用临时热点失败:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("MissingPermission")
|
||||
fun close() {
|
||||
generation++
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
try { reservation?.close() } catch (_: Exception) {}
|
||||
reservation = null
|
||||
val channel = p2pChannel
|
||||
p2pChannel = null
|
||||
if (channel != null) {
|
||||
try { p2pManager?.removeGroup(channel, null) } catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.BufferedOutputStream
|
||||
import java.io.FileInputStream
|
||||
import java.io.InputStream
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.InetAddress
|
||||
@@ -30,6 +31,24 @@ data class PhoneShareManifestItem(
|
||||
val path: String,
|
||||
)
|
||||
|
||||
/** Hash exactly the advertised number of bytes and reject stale provider size
|
||||
* metadata. The manifest and Range server must describe the identical snapshot. */
|
||||
internal fun phoneShareSha256Exact(input: InputStream, expectedSize: Long): String {
|
||||
require(expectedSize >= 0L)
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
val buffer = ByteArray(1024 * 1024)
|
||||
var remaining = expectedSize
|
||||
while (remaining > 0L) {
|
||||
val count = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
|
||||
require(count >= 0) { "实际内容小于文件选择器报告的大小" }
|
||||
if (count == 0) continue
|
||||
digest.update(buffer, 0, count)
|
||||
remaining -= count.toLong()
|
||||
}
|
||||
require(input.read() < 0) { "实际内容大于文件选择器报告的大小" }
|
||||
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xFF) }
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -276,16 +295,17 @@ class PhoneShareServer private constructor(
|
||||
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)
|
||||
val source = resolver.openInputStream(file.uri) ?: error("无法读取 ${file.name}")
|
||||
return source.use { input ->
|
||||
// Hash exactly the bytes that the Range server will expose.
|
||||
// Reject mutable/stale provider metadata instead of producing a
|
||||
// QR whose manifest hash can never match the advertised size.
|
||||
try {
|
||||
phoneShareSha256Exact(input, file.size)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
error("${file.name}:${e.message},请重新选择")
|
||||
}
|
||||
} ?: error("无法读取 ${file.name}")
|
||||
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xFF) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun readLine(input: BufferedInputStream): String? {
|
||||
|
||||
@@ -4,12 +4,28 @@ import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.util.concurrent.Callable
|
||||
import java.util.concurrent.ExecutorCompletionService
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.zip.CRC32
|
||||
|
||||
class ProtocolTest {
|
||||
@Test
|
||||
fun phoneShareHashRequiresTheAdvertisedExactSize() {
|
||||
val bytes = "phone-share-stable-snapshot".toByteArray()
|
||||
assertEquals(
|
||||
"83511688f11a9cb98da9339966f6a0b97e48913102aaad39ae395d2e88f3f65f",
|
||||
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong()),
|
||||
)
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong() + 1L)
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong() - 1L)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directDiscoveryCarriesTheAndroidDeviceName() {
|
||||
val request = directDiscoveryRequest(
|
||||
|
||||
Reference in New Issue
Block a user