193 lines
6.6 KiB
Kotlin
193 lines
6.6 KiB
Kotlin
package com.qft.optical
|
|
|
|
import android.content.ContentValues
|
|
import android.content.Context
|
|
import android.os.Build
|
|
import android.os.Environment
|
|
import android.provider.MediaStore
|
|
import java.io.File
|
|
import java.io.FileInputStream
|
|
import java.io.RandomAccessFile
|
|
import java.security.MessageDigest
|
|
|
|
sealed interface ReceiveEvent {
|
|
data class Started(val manifest: Manifest) : ReceiveEvent
|
|
data class Progress(val manifest: Manifest, val received: Int, val total: Int) : ReceiveEvent
|
|
data class Completed(val manifest: Manifest, val savedName: String) : ReceiveEvent
|
|
data class Error(val message: String) : ReceiveEvent
|
|
}
|
|
|
|
class SessionAssembler(
|
|
private val context: Context,
|
|
private val onEvent: (ReceiveEvent) -> Unit,
|
|
) {
|
|
private var manifest: Manifest? = null
|
|
private var received: BooleanArray? = null
|
|
private var receivedCount = 0
|
|
private var tempFile: File? = null
|
|
private var raf: RandomAccessFile? = null
|
|
private var completedSession: Long? = null
|
|
|
|
@Synchronized
|
|
fun acceptText(text: String) {
|
|
val frame = QftProtocol.parseText(text) ?: return
|
|
if (completedSession == frame.sessionId) return
|
|
|
|
when (frame.kind) {
|
|
FrameKind.MANIFEST -> acceptManifest(frame)
|
|
FrameKind.DATA -> acceptData(frame)
|
|
FrameKind.END -> Unit
|
|
}
|
|
}
|
|
|
|
private fun acceptManifest(frame: QftFrame) {
|
|
val incoming = QftProtocol.parseManifest(frame) ?: return
|
|
val current = manifest
|
|
if (current?.sessionId == incoming.sessionId) return
|
|
reset()
|
|
|
|
if (incoming.totalChunks > Int.MAX_VALUE) {
|
|
onEvent(ReceiveEvent.Error("文件分片数过大"))
|
|
return
|
|
}
|
|
manifest = incoming
|
|
received = BooleanArray(incoming.totalChunks.toInt())
|
|
tempFile = File(context.cacheDir, "qft-${incoming.sessionId}.part")
|
|
raf = RandomAccessFile(tempFile!!, "rw").apply { setLength(incoming.fileSize) }
|
|
onEvent(ReceiveEvent.Started(incoming))
|
|
if (incoming.totalChunks == 0L) finalizeIfComplete()
|
|
}
|
|
|
|
private fun acceptData(frame: QftFrame) {
|
|
val m = manifest ?: return
|
|
if (frame.sessionId != m.sessionId) return
|
|
if (frame.totalChunks != m.totalChunks) return
|
|
if (frame.seq >= m.totalChunks) return
|
|
if (frame.payload.size > m.chunkSize) return
|
|
|
|
val expectedOffset = frame.seq * m.chunkSize.toLong()
|
|
val remaining = m.fileSize - expectedOffset
|
|
if (remaining < 0) return
|
|
val expectedLen = minOf(m.chunkSize.toLong(), remaining).toInt()
|
|
if (frame.payload.size != expectedLen) return
|
|
|
|
val flags = received ?: return
|
|
val index = frame.seq.toInt()
|
|
if (flags[index]) return
|
|
|
|
raf?.seek(expectedOffset)
|
|
raf?.write(frame.payload)
|
|
flags[index] = true
|
|
receivedCount++
|
|
onEvent(ReceiveEvent.Progress(m, receivedCount, flags.size))
|
|
finalizeIfComplete()
|
|
}
|
|
|
|
private fun finalizeIfComplete() {
|
|
val m = manifest ?: return
|
|
val flags = received ?: return
|
|
if (receivedCount != flags.size) return
|
|
|
|
raf?.fd?.sync()
|
|
raf?.close()
|
|
raf = null
|
|
val file = tempFile ?: return
|
|
val actual = sha256(file)
|
|
if (!actual.contentEquals(m.sha256)) {
|
|
onEvent(ReceiveEvent.Error("SHA-256 校验失败,等待下一会话重新发送"))
|
|
reset()
|
|
return
|
|
}
|
|
|
|
try {
|
|
saveToDownloads(file, m.fileName)
|
|
completedSession = m.sessionId
|
|
onEvent(ReceiveEvent.Completed(m, m.fileName))
|
|
reset(keepCompleted = true)
|
|
} catch (e: Exception) {
|
|
onEvent(ReceiveEvent.Error("保存失败:${e.message}"))
|
|
}
|
|
}
|
|
|
|
private fun sha256(file: File): ByteArray {
|
|
val digest = MessageDigest.getInstance("SHA-256")
|
|
FileInputStream(file).use { input ->
|
|
val buf = ByteArray(1024 * 1024)
|
|
while (true) {
|
|
val n = input.read(buf)
|
|
if (n <= 0) break
|
|
digest.update(buf, 0, n)
|
|
}
|
|
}
|
|
return digest.digest()
|
|
}
|
|
|
|
private fun saveToDownloads(source: File, name: String) {
|
|
if (Build.VERSION.SDK_INT >= 29) {
|
|
saveModern(source, name)
|
|
} else {
|
|
saveLegacy(source, name)
|
|
}
|
|
}
|
|
|
|
@android.annotation.TargetApi(29)
|
|
private fun saveModern(source: File, name: String) {
|
|
val values = ContentValues().apply {
|
|
put(MediaStore.Downloads.DISPLAY_NAME, name)
|
|
put(MediaStore.Downloads.MIME_TYPE, "application/octet-stream")
|
|
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/QFT")
|
|
put(MediaStore.Downloads.IS_PENDING, 1)
|
|
}
|
|
val resolver = context.contentResolver
|
|
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
|
?: error("MediaStore insert failed")
|
|
try {
|
|
resolver.openOutputStream(uri, "w")!!.use { out ->
|
|
source.inputStream().use { input -> input.copyTo(out, 1024 * 1024) }
|
|
}
|
|
values.clear()
|
|
values.put(MediaStore.Downloads.IS_PENDING, 0)
|
|
resolver.update(uri, values, null, null)
|
|
} catch (e: Exception) {
|
|
resolver.delete(uri, null, null)
|
|
throw e
|
|
}
|
|
}
|
|
|
|
@Suppress("DEPRECATION")
|
|
private fun saveLegacy(source: File, name: String) {
|
|
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "QFT")
|
|
if (!dir.exists() && !dir.mkdirs()) error("无法创建 Downloads/QFT")
|
|
val target = uniqueLegacyFile(dir, name)
|
|
source.inputStream().use { input ->
|
|
target.outputStream().use { output -> input.copyTo(output, 1024 * 1024) }
|
|
}
|
|
}
|
|
|
|
private fun uniqueLegacyFile(dir: File, original: String): File {
|
|
var candidate = File(dir, original)
|
|
if (!candidate.exists()) return candidate
|
|
val dot = original.lastIndexOf('.')
|
|
val stem = if (dot > 0) original.substring(0, dot) else original
|
|
val ext = if (dot > 0) original.substring(dot) else ""
|
|
var n = 1
|
|
while (candidate.exists()) {
|
|
candidate = File(dir, "$stem ($n)$ext")
|
|
n++
|
|
}
|
|
return candidate
|
|
}
|
|
|
|
@Synchronized
|
|
fun reset(keepCompleted: Boolean = false) {
|
|
try { raf?.close() } catch (_: Exception) {}
|
|
raf = null
|
|
tempFile?.delete()
|
|
tempFile = null
|
|
manifest = null
|
|
received = null
|
|
receivedCount = 0
|
|
if (!keepCompleted) completedSession = null
|
|
}
|
|
}
|