Compare commits
2 Commits
b444a39a63
...
34b8fdf050
| Author | SHA1 | Date | |
|---|---|---|---|
| 34b8fdf050 | |||
| e9e51a4941 |
@@ -12,8 +12,8 @@ android {
|
|||||||
applicationId = "com.qft.optical"
|
applicationId = "com.qft.optical"
|
||||||
minSdk = 24
|
minSdk = 24
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 16
|
versionCode = 17
|
||||||
versionName = "0.4.0-rc8"
|
versionName = "0.4.0-rc9"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
@@ -40,6 +40,7 @@ android {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("androidx.activity:activity-ktx:1.10.1")
|
implementation("androidx.activity:activity-ktx:1.10.1")
|
||||||
|
implementation("androidx.core:core-ktx:1.15.0")
|
||||||
implementation("androidx.camera:camera-core:1.4.2")
|
implementation("androidx.camera:camera-core:1.4.2")
|
||||||
implementation("androidx.camera:camera-camera2:1.4.2")
|
implementation("androidx.camera:camera-camera2:1.4.2")
|
||||||
implementation("androidx.camera:camera-lifecycle:1.4.2")
|
implementation("androidx.camera:camera-lifecycle:1.4.2")
|
||||||
|
|||||||
@@ -19,6 +19,15 @@
|
|||||||
android:label="QFT"
|
android:label="QFT"
|
||||||
android:supportsRtl="true"
|
android:supportsRtl="true"
|
||||||
android:theme="@style/QftTheme">
|
android:theme="@style/QftTheme">
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.files"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/qft_file_paths" />
|
||||||
|
</provider>
|
||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
|||||||
@@ -79,6 +79,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var connectedNetwork: Network? = null
|
private var connectedNetwork: Network? = null
|
||||||
private var connectedBaseUrl: String? = null
|
private var connectedBaseUrl: String? = null
|
||||||
private val selectedFiles = mutableListOf<SelectedFile>()
|
private val selectedFiles = mutableListOf<SelectedFile>()
|
||||||
|
private var managingFilesForPair: PairingPayload? = null
|
||||||
|
private var managingFilesForBaseUrl: String? = null
|
||||||
private var sendStatusText: TextView? = null
|
private var sendStatusText: TextView? = null
|
||||||
private var sendFilesText: TextView? = null
|
private var sendFilesText: TextView? = null
|
||||||
private var sendProgress: ProgressBar? = null
|
private var sendProgress: ProgressBar? = null
|
||||||
@@ -115,13 +117,18 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||||||
selectedFiles.clear()
|
|
||||||
var unknown = 0
|
var unknown = 0
|
||||||
for (uri in uris) {
|
for (uri in uris) {
|
||||||
val file = UploadClient.describeFile(contentResolver, uri)
|
val file = UploadClient.describeFile(contentResolver, uri)
|
||||||
if (file != null) selectedFiles += file else unknown++
|
if (file != null && selectedFiles.none { it.uri == file.uri }) selectedFiles += file else if (file == null) unknown++
|
||||||
}
|
}
|
||||||
renderSelectedFiles()
|
renderSelectedFiles()
|
||||||
|
val pair = managingFilesForPair
|
||||||
|
val baseUrl = managingFilesForBaseUrl
|
||||||
|
if (pair != null && baseUrl != null) {
|
||||||
|
showFileSelection(pair, baseUrl)
|
||||||
|
return@registerForActivityResult
|
||||||
|
}
|
||||||
if (unknown > 0) {
|
if (unknown > 0) {
|
||||||
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
|
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
|
||||||
} else if (selectedFiles.isNotEmpty()) {
|
} else if (selectedFiles.isNotEmpty()) {
|
||||||
@@ -150,6 +157,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
downloadRunning = false
|
downloadRunning = false
|
||||||
downloadStatusText = null
|
downloadStatusText = null
|
||||||
selectedFiles.clear()
|
selectedFiles.clear()
|
||||||
|
managingFilesForPair = null
|
||||||
|
managingFilesForBaseUrl = null
|
||||||
|
|
||||||
val root = pageColumn()
|
val root = pageColumn()
|
||||||
root.addView(text("QFT", 30f, Color.WHITE, true))
|
root.addView(text("QFT", 30f, Color.WHITE, true))
|
||||||
@@ -175,6 +184,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
|
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
|
||||||
buttonLabel = "扫描电脑二维码",
|
buttonLabel = "扫描电脑二维码",
|
||||||
) { requestScanner(ScannerMode.PAIR) })
|
) { requestScanner(ScannerMode.PAIR) })
|
||||||
|
root.addView(space(16))
|
||||||
|
root.addView(modeCard(
|
||||||
|
title = "接收文件柜",
|
||||||
|
badge = "Downloads/QFT · 图片/视频/PDF/Office/压缩包等",
|
||||||
|
body = "查看 QFT 已接收的文件;点击后将使用手机中可用的阅读器或播放器打开。",
|
||||||
|
buttonLabel = "打开文件柜",
|
||||||
|
) { showReceivedFiles() })
|
||||||
root.addView(space(22))
|
root.addView(space(22))
|
||||||
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
||||||
root.addView(text("QFT v0.4.0-rc2 · Android 7+ 到最新", 12f, MUTED))
|
root.addView(text("QFT v0.4.0-rc2 · Android 7+ 到最新", 12f, MUTED))
|
||||||
@@ -723,22 +739,25 @@ class MainActivity : ComponentActivity() {
|
|||||||
root.addView(space(14))
|
root.addView(space(14))
|
||||||
root.addView(card().apply {
|
root.addView(card().apply {
|
||||||
addView(text("选择文件", 17f, Color.WHITE, true))
|
addView(text("选择文件", 17f, Color.WHITE, true))
|
||||||
sendFilesText = text("尚未选择文件", 14f, MUTED)
|
sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
|
||||||
addView(sendFilesText, matchWrap(top = 8))
|
addView(sendFilesText, matchWrap(top = 8))
|
||||||
addView(button("选择文件(可多选)").apply {
|
addView(button("选择文件(可多选)").apply {
|
||||||
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
|
setOnClickListener { showFileSelection(pair, baseUrl) }
|
||||||
}, matchWrap(top = 12))
|
}, matchWrap(top = 12))
|
||||||
})
|
})
|
||||||
root.addView(space(14))
|
root.addView(space(14))
|
||||||
root.addView(card().apply {
|
root.addView(card().apply {
|
||||||
addView(text("传输进度", 17f, Color.WHITE, true))
|
addView(text("传输进度", 17f, Color.WHITE, true))
|
||||||
sendStatusText = text("选择文件后点击开始传输", 14f, MUTED)
|
sendStatusText = text("请先选择需要传输的文件,再点击“开始传输”", 14f, WARNING)
|
||||||
addView(sendStatusText, matchWrap(top = 8))
|
addView(sendStatusText, matchWrap(top = 8))
|
||||||
sendProgress = ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
|
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) })
|
addView(sendProgress, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
|
||||||
sendButton = button("开始传输").apply {
|
sendButton = button("选择传输文件").apply {
|
||||||
isEnabled = selectedFiles.isNotEmpty()
|
isEnabled = connectedBaseUrl != null
|
||||||
setOnClickListener { startUploads(pair, baseUrl) }
|
setOnClickListener {
|
||||||
|
if (selectedFiles.isEmpty()) showFileSelection(pair, baseUrl)
|
||||||
|
else startUploads(pair, baseUrl)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
addView(sendButton, matchWrap(top = 14))
|
addView(sendButton, matchWrap(top = 14))
|
||||||
})
|
})
|
||||||
@@ -819,10 +838,118 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun showReceivedFiles(message: String? = null) {
|
||||||
|
val root = pageColumn()
|
||||||
|
root.addView(text("接收文件柜", 28f, Color.WHITE, true))
|
||||||
|
root.addView(text("QFT 已保存到 Downloads/QFT 的文件", 14f, MUTED))
|
||||||
|
message?.let { root.addView(text(it, 13f, WARNING), matchWrap(top = 10)) }
|
||||||
|
root.addView(space(16))
|
||||||
|
|
||||||
|
val files = try {
|
||||||
|
ReceivedFileCabinet.list(this)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
if (files.isEmpty()) {
|
||||||
|
root.addView(card().apply {
|
||||||
|
addView(text("文件柜为空", 17f, Color.WHITE, true))
|
||||||
|
addView(text("完成电脑下发或光学接收后,文件会自动出现在这里。", 14f, MUTED), matchWrap(top = 8))
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
root.addView(text("共 ${files.size} 个文件", 13f, ACCENT, true))
|
||||||
|
files.forEach { file ->
|
||||||
|
val entry = card()
|
||||||
|
entry.addView(text(file.name, 16f, Color.WHITE, true))
|
||||||
|
entry.addView(
|
||||||
|
text("${humanBytes(file.size)} · ${file.mimeType.ifBlank { "未知格式" }}", 12f, MUTED),
|
||||||
|
matchWrap(top = 5),
|
||||||
|
)
|
||||||
|
entry.addView(button("打开文件").apply {
|
||||||
|
setOnClickListener {
|
||||||
|
try {
|
||||||
|
ReceivedFileCabinet.open(this@MainActivity, file)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
showReceivedFiles("无法打开 ${file.name}:请安装支持该格式的阅读器。")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, matchWrap(top = 10))
|
||||||
|
root.addView(entry, matchWrap(bottom = 10))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root.addView(space(12))
|
||||||
|
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
|
||||||
|
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showFileSelection(pair: PairingPayload, baseUrl: String) {
|
||||||
|
managingFilesForPair = pair
|
||||||
|
managingFilesForBaseUrl = baseUrl
|
||||||
|
val root = pageColumn()
|
||||||
|
root.addView(text("选择发送文件", 28f, Color.WHITE, true))
|
||||||
|
root.addView(text("可多次添加文件,并在列表中单独移除。", 14f, MUTED))
|
||||||
|
root.addView(space(14))
|
||||||
|
val total = selectedFiles.sumOf { it.size }
|
||||||
|
root.addView(card().apply {
|
||||||
|
addView(text("已选 ${selectedFiles.size} 个 · ${humanBytes(total)}", 16f, ACCENT, true))
|
||||||
|
if (selectedFiles.isEmpty()) {
|
||||||
|
addView(text("请先选择需要传输的文件", 14f, WARNING), matchWrap(top = 8))
|
||||||
|
} else {
|
||||||
|
selectedFiles.toList().forEach { file ->
|
||||||
|
val row = LinearLayout(this@MainActivity).apply {
|
||||||
|
orientation = LinearLayout.HORIZONTAL
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
}
|
||||||
|
row.addView(
|
||||||
|
text("${file.name}\n${humanBytes(file.size)}", 14f, Color.WHITE),
|
||||||
|
LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) },
|
||||||
|
)
|
||||||
|
row.addView(button("移除").apply {
|
||||||
|
setOnClickListener {
|
||||||
|
selectedFiles.removeAll { it.uri == file.uri }
|
||||||
|
showFileSelection(pair, baseUrl)
|
||||||
|
}
|
||||||
|
}, LinearLayout.LayoutParams(dp(82), dp(44)))
|
||||||
|
addView(row, matchWrap(top = 10))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
root.addView(space(14))
|
||||||
|
root.addView(button("添加文件(可多选)").apply {
|
||||||
|
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
|
||||||
|
})
|
||||||
|
if (selectedFiles.isNotEmpty()) {
|
||||||
|
root.addView(space(10))
|
||||||
|
root.addView(button("清空选择").apply {
|
||||||
|
setOnClickListener {
|
||||||
|
selectedFiles.clear()
|
||||||
|
showFileSelection(pair, baseUrl)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
root.addView(space(10))
|
||||||
|
root.addView(button("完成并返回传输").apply {
|
||||||
|
isEnabled = selectedFiles.isNotEmpty()
|
||||||
|
setOnClickListener {
|
||||||
|
managingFilesForPair = null
|
||||||
|
managingFilesForBaseUrl = null
|
||||||
|
showSendReady(pair, baseUrl)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
root.addView(space(10))
|
||||||
|
root.addView(button("取消并返回传输").apply {
|
||||||
|
setOnClickListener {
|
||||||
|
managingFilesForPair = null
|
||||||
|
managingFilesForBaseUrl = null
|
||||||
|
showSendReady(pair, baseUrl)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||||
|
}
|
||||||
|
|
||||||
private fun renderSelectedFiles() {
|
private fun renderSelectedFiles() {
|
||||||
val total = selectedFiles.sumOf { it.size }
|
val total = selectedFiles.sumOf { it.size }
|
||||||
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
||||||
"尚未选择文件"
|
"请先选择需要传输的文件"
|
||||||
} else {
|
} else {
|
||||||
buildString {
|
buildString {
|
||||||
selectedFiles.take(8).forEach { append("• ${it.name} ${humanBytes(it.size)}\n") }
|
selectedFiles.take(8).forEach { append("• ${it.name} ${humanBytes(it.size)}\n") }
|
||||||
@@ -830,11 +957,17 @@ class MainActivity : ComponentActivity() {
|
|||||||
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
|
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
|
||||||
}.trim()
|
}.trim()
|
||||||
}
|
}
|
||||||
sendButton?.isEnabled = selectedFiles.isNotEmpty() && connectedBaseUrl != null
|
sendButton?.text = if (selectedFiles.isEmpty()) "选择传输文件" else "开始传输"
|
||||||
|
sendButton?.isEnabled = connectedBaseUrl != null
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startUploads(pair: PairingPayload, baseUrl: String) {
|
private fun startUploads(pair: PairingPayload, baseUrl: String) {
|
||||||
if (selectedFiles.isEmpty()) return
|
if (selectedFiles.isEmpty()) {
|
||||||
|
sendStatusText?.setTextColor(WARNING)
|
||||||
|
sendStatusText?.text = "请先选择需要传输的文件"
|
||||||
|
showFileSelection(pair, baseUrl)
|
||||||
|
return
|
||||||
|
}
|
||||||
val files = selectedFiles.toList()
|
val files = selectedFiles.toList()
|
||||||
sendButton?.isEnabled = false
|
sendButton?.isEnabled = false
|
||||||
transferExecutor.execute {
|
transferExecutor.execute {
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package com.qft.optical
|
||||||
|
|
||||||
|
import android.content.ContentResolver
|
||||||
|
import android.content.ContentUris
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Environment
|
||||||
|
import android.provider.MediaStore
|
||||||
|
import android.webkit.MimeTypeMap
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
data class ReceivedFile(
|
||||||
|
val uri: Uri,
|
||||||
|
val name: String,
|
||||||
|
val size: Long,
|
||||||
|
val mimeType: String,
|
||||||
|
val modifiedAtSeconds: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Lists only the files QFT has finished writing to Downloads/QFT. */
|
||||||
|
object ReceivedFileCabinet {
|
||||||
|
private const val RELATIVE_QFT_PATH = "Download/QFT/"
|
||||||
|
|
||||||
|
fun list(context: Context): List<ReceivedFile> =
|
||||||
|
if (Build.VERSION.SDK_INT >= 29) listModern(context.contentResolver) else listLegacy(context)
|
||||||
|
|
||||||
|
fun open(context: Context, file: ReceivedFile) {
|
||||||
|
val resolvedMime = mimeFor(file.name, file.mimeType)
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW)
|
||||||
|
.setDataAndType(file.uri, resolvedMime)
|
||||||
|
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
context.startActivity(Intent.createChooser(intent, "打开 ${file.name}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun listModern(resolver: ContentResolver): List<ReceivedFile> {
|
||||||
|
val projection = arrayOf(
|
||||||
|
MediaStore.Downloads._ID,
|
||||||
|
MediaStore.Downloads.DISPLAY_NAME,
|
||||||
|
MediaStore.Downloads.SIZE,
|
||||||
|
MediaStore.Downloads.MIME_TYPE,
|
||||||
|
MediaStore.Downloads.DATE_MODIFIED,
|
||||||
|
)
|
||||||
|
val out = mutableListOf<ReceivedFile>()
|
||||||
|
resolver.query(
|
||||||
|
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
|
||||||
|
projection,
|
||||||
|
"${MediaStore.Downloads.RELATIVE_PATH}=? AND ${MediaStore.Downloads.IS_PENDING}=0",
|
||||||
|
arrayOf(RELATIVE_QFT_PATH),
|
||||||
|
"${MediaStore.Downloads.DATE_MODIFIED} DESC",
|
||||||
|
)?.use { cursor ->
|
||||||
|
val idIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID)
|
||||||
|
val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME)
|
||||||
|
val sizeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.SIZE)
|
||||||
|
val mimeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.MIME_TYPE)
|
||||||
|
val timeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DATE_MODIFIED)
|
||||||
|
while (cursor.moveToNext()) {
|
||||||
|
val id = cursor.getLong(idIndex)
|
||||||
|
val name = cursor.getString(nameIndex).orEmpty().ifBlank { "未命名文件" }
|
||||||
|
out += ReceivedFile(
|
||||||
|
uri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, id),
|
||||||
|
name = name,
|
||||||
|
size = cursor.getLong(sizeIndex).coerceAtLeast(0L),
|
||||||
|
mimeType = cursor.getString(mimeIndex).orEmpty(),
|
||||||
|
modifiedAtSeconds = cursor.getLong(timeIndex),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
private fun listLegacy(context: Context): List<ReceivedFile> {
|
||||||
|
val directory = File(
|
||||||
|
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
|
||||||
|
"QFT",
|
||||||
|
)
|
||||||
|
return directory.listFiles()
|
||||||
|
?.asSequence()
|
||||||
|
?.filter { it.isFile }
|
||||||
|
?.sortedByDescending { it.lastModified() }
|
||||||
|
?.map { file ->
|
||||||
|
ReceivedFile(
|
||||||
|
uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file),
|
||||||
|
name = file.name,
|
||||||
|
size = file.length().coerceAtLeast(0L),
|
||||||
|
mimeType = mimeFor(file.name, ""),
|
||||||
|
modifiedAtSeconds = file.lastModified() / 1000L,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
?.toList()
|
||||||
|
.orEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mimeFor(name: String, supplied: String): String {
|
||||||
|
if (supplied.isNotBlank() && supplied != "application/octet-stream") return supplied
|
||||||
|
val extension = name.substringAfterLast('.', "").lowercase()
|
||||||
|
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import android.database.Cursor
|
|||||||
import android.net.Network
|
import android.net.Network
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.provider.OpenableColumns
|
import android.provider.OpenableColumns
|
||||||
|
import android.util.Log
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.FileInputStream
|
import java.io.FileInputStream
|
||||||
import java.net.DatagramPacket
|
import java.net.DatagramPacket
|
||||||
@@ -28,12 +29,16 @@ data class SelectedFile(
|
|||||||
)
|
)
|
||||||
|
|
||||||
object UploadClient {
|
object UploadClient {
|
||||||
|
private const val TAG = "QftUpload"
|
||||||
private const val DISCOVERY_PORT = 39392
|
private const val DISCOVERY_PORT = 39392
|
||||||
private const val CHUNK_SMALL = 4L * 1024L * 1024L
|
private const val CHUNK_SMALL = 4L * 1024L * 1024L
|
||||||
private const val CHUNK_DEFAULT = 8L * 1024L * 1024L
|
private const val CHUNK_DEFAULT = 8L * 1024L * 1024L
|
||||||
private const val CHUNK_LARGE = 16L * 1024L * 1024L
|
private const val CHUNK_LARGE = 16L * 1024L * 1024L
|
||||||
private const val MAX_WORKERS = 8
|
private const val MAX_WORKERS = 8
|
||||||
private const val STREAM_BUFFER = 1024 * 1024
|
private const val STREAM_BUFFER = 1024 * 1024
|
||||||
|
// A single request is materially more reliable for small files on Wi-Fi
|
||||||
|
// Direct, and a 4 MiB parallel chunk gives no throughput benefit there.
|
||||||
|
private const val PARALLEL_MIN_FILE_SIZE = 32L * 1024L * 1024L
|
||||||
// QFT Direct can briefly reset a TCP flow while the Android network route
|
// QFT Direct can briefly reset a TCP flow while the Android network route
|
||||||
// settles. Chunk PUTs and the init/finish control calls are safe to retry;
|
// settles. Chunk PUTs and the init/finish control calls are safe to retry;
|
||||||
// the Windows receiver treats a repeated chunk as an idempotent success.
|
// the Windows receiver treats a repeated chunk as an idempotent success.
|
||||||
@@ -222,7 +227,7 @@ object UploadClient {
|
|||||||
file: SelectedFile,
|
file: SelectedFile,
|
||||||
onProgress: (sent: Long, total: Long) -> Unit,
|
onProgress: (sent: Long, total: Long) -> Unit,
|
||||||
) {
|
) {
|
||||||
if (pairing.version >= 2 && isSeekable(resolver, file)) {
|
if (pairing.version >= 2 && file.size >= PARALLEL_MIN_FILE_SIZE && isSeekable(resolver, file)) {
|
||||||
try {
|
try {
|
||||||
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
||||||
return
|
return
|
||||||
@@ -236,6 +241,7 @@ object UploadClient {
|
|||||||
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
|
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Log.i(TAG, "using single-stream upload: size=${file.size}, endpoint=$baseUrl")
|
||||||
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,6 +254,11 @@ object UploadClient {
|
|||||||
return block()
|
return block()
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
last = e
|
last = e
|
||||||
|
Log.w(
|
||||||
|
TAG,
|
||||||
|
"$label: attempt=${attempt + 1}/$LOCAL_REQUEST_ATTEMPTS, ${failureSummary(e)}",
|
||||||
|
e,
|
||||||
|
)
|
||||||
if (attempt + 1 < LOCAL_REQUEST_ATTEMPTS) {
|
if (attempt + 1 < LOCAL_REQUEST_ATTEMPTS) {
|
||||||
try { Thread.sleep(120L * (attempt + 1)) } catch (_: InterruptedException) {
|
try { Thread.sleep(120L * (attempt + 1)) } catch (_: InterruptedException) {
|
||||||
Thread.currentThread().interrupt()
|
Thread.currentThread().interrupt()
|
||||||
@@ -256,7 +267,23 @@ object UploadClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw IllegalStateException("$label after $LOCAL_REQUEST_ATTEMPTS attempts", last)
|
val failure = last ?: IllegalStateException("unknown local request failure")
|
||||||
|
throw IllegalStateException(
|
||||||
|
"$label,已重试 $LOCAL_REQUEST_ATTEMPTS 次:${failureSummary(failure)}",
|
||||||
|
failure,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun failureSummary(error: Throwable): String {
|
||||||
|
val chain = ArrayList<String>(3)
|
||||||
|
var current: Throwable? = error
|
||||||
|
while (current != null && chain.size < 3) {
|
||||||
|
val type = current.javaClass.simpleName.ifBlank { current.javaClass.name }
|
||||||
|
val detail = current.message?.replace(Regex("\\s+"), " ")?.take(240)
|
||||||
|
chain += if (detail.isNullOrBlank()) type else "$type: $detail"
|
||||||
|
current = current.cause
|
||||||
|
}
|
||||||
|
return chain.joinToString(" <- ")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun uploadParallel(
|
private fun uploadParallel(
|
||||||
@@ -268,7 +295,9 @@ object UploadClient {
|
|||||||
file: SelectedFile,
|
file: SelectedFile,
|
||||||
onProgress: (sent: Long, total: Long) -> Unit,
|
onProgress: (sent: Long, total: Long) -> Unit,
|
||||||
) {
|
) {
|
||||||
|
Log.i(TAG, "parallel init: size=${file.size}, endpoint=$baseUrl")
|
||||||
val init = initUpload(network, baseUrl, pairing, deviceName, file)
|
val init = initUpload(network, baseUrl, pairing, deviceName, file)
|
||||||
|
Log.i(TAG, "parallel init complete: chunks=${init.totalChunks}, chunkSize=${init.chunkSize}")
|
||||||
if (init.totalChunks == 0) {
|
if (init.totalChunks == 0) {
|
||||||
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
|
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
|
||||||
onProgress(0, 0)
|
onProgress(0, 0)
|
||||||
@@ -362,6 +391,7 @@ object UploadClient {
|
|||||||
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
|
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
|
||||||
buffer: ByteBuffer,
|
buffer: ByteBuffer,
|
||||||
) = retryLocalRequest("分块 $index 上传失败") {
|
) = retryLocalRequest("分块 $index 上传失败") {
|
||||||
|
Log.d(TAG, "chunk start: index=$index, bytes=$length, endpoint=$baseUrl")
|
||||||
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
|
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
|
||||||
try {
|
try {
|
||||||
conn.requestMethod = "POST"
|
conn.requestMethod = "POST"
|
||||||
@@ -391,6 +421,7 @@ object UploadClient {
|
|||||||
error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
|
error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
|
||||||
}
|
}
|
||||||
try { conn.inputStream.close() } catch (_: Exception) {}
|
try { conn.inputStream.close() } catch (_: Exception) {}
|
||||||
|
Log.d(TAG, "chunk complete: index=$index, bytes=$length")
|
||||||
} finally {
|
} finally {
|
||||||
conn.disconnect()
|
conn.disconnect()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<external-path name="qft_downloads" path="Download/QFT/" />
|
||||||
|
</paths>
|
||||||
@@ -169,6 +169,11 @@ fn handle_client(
|
|||||||
sessions: &SessionMap,
|
sessions: &SessionMap,
|
||||||
completed: &CompletedMap,
|
completed: &CompletedMap,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
// The listener is non-blocking so the UI can poll for shutdown. On
|
||||||
|
// Windows an accepted socket may retain that mode, which made a body read
|
||||||
|
// race the next Wi-Fi Direct packet and fail with WSAEWOULDBLOCK (10035).
|
||||||
|
// File requests must instead wait under the explicit socket timeouts.
|
||||||
|
stream.set_nonblocking(false)?;
|
||||||
stream.set_nodelay(true).ok();
|
stream.set_nodelay(true).ok();
|
||||||
stream.set_read_timeout(Some(Duration::from_secs(120)))?;
|
stream.set_read_timeout(Some(Duration::from_secs(120)))?;
|
||||||
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
|
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
|
||||||
@@ -572,3 +577,63 @@ fn hex(bytes: &[u8]) -> String {
|
|||||||
for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); }
|
for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); }
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::{
|
||||||
|
io::{Read, Write},
|
||||||
|
net::TcpListener,
|
||||||
|
sync::mpsc,
|
||||||
|
time::{SystemTime, UNIX_EPOCH},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_upload_waits_for_a_delayed_body_on_a_nonblocking_accepted_socket() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let dir = std::env::temp_dir().join(format!(
|
||||||
|
"qft-receiver-test-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(),
|
||||||
|
));
|
||||||
|
fs::create_dir_all(&dir).unwrap();
|
||||||
|
let dir_for_server = dir.clone();
|
||||||
|
let (events, _updates) = mpsc::channel();
|
||||||
|
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
let completed: CompletedMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
|
||||||
|
let server = thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
// This matches the Windows mode inheritance that previously made
|
||||||
|
// the body read return WSAEWOULDBLOCK between TCP packets.
|
||||||
|
stream.set_nonblocking(true).unwrap();
|
||||||
|
handle_client(
|
||||||
|
&mut stream,
|
||||||
|
&dir_for_server,
|
||||||
|
"session",
|
||||||
|
&events,
|
||||||
|
&sessions,
|
||||||
|
&completed,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut client = TcpStream::connect(address).unwrap();
|
||||||
|
client
|
||||||
|
.write_all(
|
||||||
|
b"POST /qft/upload HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\nContent-Length: 4\r\nX-QFT-Size: 4\r\n\r\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client.flush().unwrap();
|
||||||
|
thread::sleep(Duration::from_millis(50));
|
||||||
|
client.write_all(b"qft!").unwrap();
|
||||||
|
client.flush().unwrap();
|
||||||
|
|
||||||
|
let mut response = String::new();
|
||||||
|
client.read_to_string(&mut response).unwrap();
|
||||||
|
server.join().unwrap().unwrap();
|
||||||
|
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
|
||||||
|
assert_eq!(fs::read(dir.join("qft-upload.bin")).unwrap(), b"qft!");
|
||||||
|
let _ = fs::remove_dir_all(dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user