567 lines
24 KiB
Swift
567 lines
24 KiB
Swift
import Foundation
|
||
import Network
|
||
import CryptoKit
|
||
|
||
/// 点对点链路:Bonjour 发现 + TLS-PSK 加密 + 长度前缀分帧。
|
||
///
|
||
/// `includePeerToPeer = true` 让 Network.framework 在没有路由器时
|
||
/// 自动使用 BLE 发现 + AWDL 点对点 Wi-Fi,也就是隔空投送用的同一条链路。
|
||
/// 两台设备在同一个 Wi-Fi 下时它会优先走基础网络,速度同样很快。
|
||
///
|
||
/// AWDL 是苹果私有链路,Windows 无法参与——PC 方向仍走 HTTP
|
||
/// 局域网/专用网络路径。
|
||
enum PeerLink {
|
||
|
||
static let frameHeaderSize = 5 // 1 字节类型 + 4 字节 BE 长度
|
||
static let chunkSize = 256 * 1024
|
||
static let maxFrameSize = 4 * 1024 * 1024
|
||
|
||
enum FrameType: UInt8 {
|
||
/// 文件清单(JSON)。整个队列只发一次,摘要必须与二维码一致。
|
||
case queue = 1
|
||
case data = 2
|
||
case eof = 3
|
||
case result = 4
|
||
case fileBegin = 5
|
||
case fileEnd = 6
|
||
}
|
||
|
||
enum PeerError: LocalizedError {
|
||
case handshake(String)
|
||
case protocolViolation(String)
|
||
case rejected(String)
|
||
case timeout
|
||
|
||
var errorDescription: String? {
|
||
switch self {
|
||
case .handshake(let detail): return "建立加密连接失败:\(detail)"
|
||
case .protocolViolation(let detail): return "对方发来的数据不符合协议:\(detail)"
|
||
case .rejected(let detail): return "对方拒绝了传输:\(detail)"
|
||
case .timeout: return "等待对方超时"
|
||
}
|
||
}
|
||
}
|
||
|
||
/// TLS-PSK 参数。密钥来自二维码,因此不需要任何证书体系,
|
||
/// 且扫码这个动作本身就完成了双向认证——中间人拿不到密钥就握不了手。
|
||
static func parameters(key: Data, identity: String) -> NWParameters {
|
||
let tls = NWProtocolTLS.Options()
|
||
let keyData = key.withUnsafeBytes { DispatchData(bytes: $0) }
|
||
let identityData = Data(identity.utf8).withUnsafeBytes { DispatchData(bytes: $0) }
|
||
|
||
sec_protocol_options_add_pre_shared_key(
|
||
tls.securityProtocolOptions,
|
||
keyData as __DispatchData,
|
||
identityData as __DispatchData)
|
||
if let suite = tls_ciphersuite_t(rawValue: UInt16(TLS_PSK_WITH_AES_128_GCM_SHA256)) {
|
||
sec_protocol_options_append_tls_ciphersuite(tls.securityProtocolOptions, suite)
|
||
}
|
||
|
||
let tcp = NWProtocolTCP.Options()
|
||
tcp.noDelay = true
|
||
// 传输是一次性的,对端消失时不要长时间挂着
|
||
tcp.connectionTimeout = 10
|
||
tcp.enableKeepalive = true
|
||
tcp.keepaliveIdle = 5
|
||
|
||
let parameters = NWParameters(tls: tls, tcp: tcp)
|
||
parameters.includePeerToPeer = true
|
||
return parameters
|
||
}
|
||
|
||
// MARK: - 分帧收发
|
||
|
||
static func send(_ connection: NWConnection, type: FrameType, payload: Data) async throws {
|
||
var header = Data([type.rawValue])
|
||
var length = UInt32(payload.count).bigEndian
|
||
withUnsafeBytes(of: &length) { header.append(contentsOf: $0) }
|
||
|
||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
|
||
connection.send(content: header + payload,
|
||
completion: .contentProcessed { error in
|
||
if let error { continuation.resume(throwing: error) } else { continuation.resume() }
|
||
})
|
||
}
|
||
}
|
||
|
||
static func sendJSON(_ connection: NWConnection, type: FrameType,
|
||
object: [String: Any]) async throws {
|
||
let data = try JSONSerialization.data(withJSONObject: object)
|
||
try await send(connection, type: type, payload: data)
|
||
}
|
||
|
||
static func receiveFrame(_ connection: NWConnection) async throws -> (FrameType, Data) {
|
||
let header = try await receiveExactly(connection, count: frameHeaderSize)
|
||
guard let type = FrameType(rawValue: header[header.startIndex]) else {
|
||
throw PeerError.protocolViolation("未知帧类型 \(header[header.startIndex])")
|
||
}
|
||
// 手工拼大端,不用 loadUnaligned:那个 API 要 Swift 5.7 运行时(iOS 16),
|
||
// 而这个 App 要一直支持到 iOS 15
|
||
let bytes = [UInt8](header)
|
||
let length = (UInt32(bytes[1]) << 24) | (UInt32(bytes[2]) << 16)
|
||
| (UInt32(bytes[3]) << 8) | UInt32(bytes[4])
|
||
guard length <= UInt32(maxFrameSize) else {
|
||
throw PeerError.protocolViolation("帧长度 \(length) 超出上限")
|
||
}
|
||
if length == 0 { return (type, Data()) }
|
||
return (type, try await receiveExactly(connection, count: Int(length)))
|
||
}
|
||
|
||
static func receiveExactly(_ connection: NWConnection, count: Int) async throws -> Data {
|
||
var buffer = Data()
|
||
buffer.reserveCapacity(count)
|
||
while buffer.count < count {
|
||
let remaining = count - buffer.count
|
||
let block = try await withCheckedThrowingContinuation {
|
||
(continuation: CheckedContinuation<Data, Error>) in
|
||
connection.receive(minimumIncompleteLength: 1, maximumLength: remaining) {
|
||
content, _, isComplete, error in
|
||
if let error { continuation.resume(throwing: error); return }
|
||
if let content, !content.isEmpty { continuation.resume(returning: content); return }
|
||
if isComplete {
|
||
continuation.resume(throwing: PeerError.protocolViolation("连接提前关闭"))
|
||
} else {
|
||
continuation.resume(returning: Data())
|
||
}
|
||
}
|
||
}
|
||
buffer.append(block)
|
||
}
|
||
return buffer
|
||
}
|
||
|
||
static func waitReady(_ connection: NWConnection, queue: DispatchQueue,
|
||
timeout: TimeInterval = 15) async throws {
|
||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
|
||
let resumed = Locked(false)
|
||
@Sendable func finish(_ error: Error?) {
|
||
guard resumed.exchange(true) == false else { return }
|
||
if let error { continuation.resume(throwing: error) } else { continuation.resume() }
|
||
}
|
||
|
||
connection.stateUpdateHandler = { state in
|
||
switch state {
|
||
case .ready:
|
||
finish(nil)
|
||
case .failed(let error):
|
||
finish(error)
|
||
case .waiting(let error):
|
||
// NWConnection 默认会在 .waiting 里无限重试。对一次性传输来说:
|
||
// TLS 类错误(密钥不匹配、对端拒绝)不可能自愈,立刻失败;
|
||
// 而链路层的暂时不可达在 AWDL/Bonjour 起来之前是正常现象,继续等。
|
||
if case .tls = error {
|
||
finish(PeerError.handshake("预共享密钥不匹配,或对方已结束这次会话"))
|
||
}
|
||
case .cancelled:
|
||
finish(PeerError.handshake("连接被取消"))
|
||
default:
|
||
break
|
||
}
|
||
}
|
||
queue.asyncAfter(deadline: .now() + timeout) { finish(PeerError.timeout) }
|
||
connection.start(queue: queue)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 极简互斥包装。continuation 只能 resume 一次,而 stateUpdateHandler
|
||
/// 可能在多个状态里触发,需要一个原子的「是否已 resume」。
|
||
final class Locked<Value>: @unchecked Sendable {
|
||
private var value: Value
|
||
private let lock = NSLock()
|
||
|
||
init(_ value: Value) { self.value = value }
|
||
|
||
func exchange(_ newValue: Value) -> Value {
|
||
lock.lock(); defer { lock.unlock() }
|
||
let old = value
|
||
value = newValue
|
||
return old
|
||
}
|
||
|
||
var current: Value {
|
||
lock.lock(); defer { lock.unlock() }
|
||
return value
|
||
}
|
||
}
|
||
|
||
/// 队列传输的进度:既要有总进度,也要说明当前在传第几个文件。
|
||
struct PeerTransferUpdate {
|
||
let progress: TransferProgress
|
||
let fileIndex: Int
|
||
let fileCount: Int
|
||
let fileName: String
|
||
}
|
||
|
||
// MARK: - 发送端
|
||
|
||
/// 展示二维码的一方。持有一个文件队列,等待对方扫码后连入。
|
||
final class PeerSender {
|
||
|
||
/// 监听器的状态与排队中的连接。stateUpdateHandler / newConnectionHandler
|
||
/// 在任意线程触发,而等待方是 async,所以两边都要经过这把锁。
|
||
private final class Box: @unchecked Sendable {
|
||
let lock = NSLock()
|
||
var readyPort: UInt16?
|
||
var failure: Error?
|
||
var pending: [NWConnection] = []
|
||
var portWaiter: CheckedContinuation<UInt16, Error>?
|
||
var connectionWaiter: CheckedContinuation<NWConnection, Error>?
|
||
|
||
/// 同步方法:async 上下文里不允许直接调用 NSLock.lock()
|
||
func drainPending() -> [NWConnection] {
|
||
lock.lock(); defer { lock.unlock() }
|
||
let extras = pending
|
||
pending = []
|
||
return extras
|
||
}
|
||
}
|
||
|
||
private let fileURLs: [URL]
|
||
private let deviceName: String
|
||
private let queue = DispatchQueue(label: "qft.peer.sender")
|
||
private let box = Box()
|
||
private var listener: NWListener?
|
||
private var pairing: PeerPairing?
|
||
private var files: [PeerFileMeta] = []
|
||
private var queuePayload = Data()
|
||
|
||
init(fileURLs: [URL], deviceName: String) {
|
||
self.fileURLs = fileURLs
|
||
self.deviceName = deviceName
|
||
}
|
||
|
||
/// 等待监听就绪并返回实际端口。P2P 场景下对端靠 Bonjour 实例名找过来,
|
||
/// 端口只在测试直连时才需要。
|
||
func listeningPort() async throws -> UInt16 {
|
||
try await withCheckedThrowingContinuation { continuation in
|
||
box.lock.lock()
|
||
if let port = box.readyPort {
|
||
box.lock.unlock(); continuation.resume(returning: port)
|
||
} else if let failure = box.failure {
|
||
box.lock.unlock(); continuation.resume(throwing: failure)
|
||
} else {
|
||
box.portWaiter = continuation
|
||
box.lock.unlock()
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 逐个算摘要、启动监听并广播 Bonjour 服务,返回要显示成二维码的配对码。
|
||
/// 会完整读一遍每个文件,调用方应放到后台线程。
|
||
func start() throws -> PeerPairing {
|
||
guard !fileURLs.isEmpty else {
|
||
throw PeerLink.PeerError.protocolViolation("没有选择任何文件")
|
||
}
|
||
|
||
var metas: [PeerFileMeta] = []
|
||
var total: UInt64 = 0
|
||
for url in fileURLs {
|
||
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
|
||
let size = UInt64(truncating: (attributes[.size] as? NSNumber) ?? 0)
|
||
|
||
var hasher = SHA256()
|
||
let handle = try FileHandle(forReadingFrom: url)
|
||
var read: UInt64 = 0
|
||
while let block = try handle.read(upToCount: 4 * 1024 * 1024), !block.isEmpty {
|
||
hasher.update(data: block)
|
||
read &+= UInt64(block.count)
|
||
}
|
||
try handle.close()
|
||
// 文件选择器报告的大小偶尔会和实际内容对不上(iCloud 占位文件、
|
||
// 正在被其他 App 写入)。以实读为准,否则二维码里的总量是假的。
|
||
let digest = hasher.finalize().map { String(format: "%02x", $0) }.joined()
|
||
let name = OpticalProtocol.sanitizeFileName(url.lastPathComponent)
|
||
metas.append(PeerFileMeta(name: name, size: read, sha256: digest))
|
||
total &+= read
|
||
_ = size
|
||
}
|
||
|
||
let payload = try PeerQueue.encode(sender: deviceName, files: metas)
|
||
let pairing = PeerPairing(
|
||
version: 2,
|
||
key: PeerPairing.newKey(),
|
||
instance: PeerPairing.newInstance(),
|
||
senderName: deviceName,
|
||
fileCount: metas.count,
|
||
totalSize: total,
|
||
queueDigest: PeerQueue.digest(of: payload),
|
||
previewName: metas[0].name)
|
||
|
||
let parameters = PeerLink.parameters(key: pairing.key, identity: pairing.instance)
|
||
let listener = try NWListener(using: parameters)
|
||
listener.service = NWListener.Service(name: pairing.instance,
|
||
type: PeerPairing.serviceType)
|
||
|
||
listener.stateUpdateHandler = { [box] state in
|
||
switch state {
|
||
case .ready:
|
||
box.lock.lock()
|
||
box.readyPort = listener.port?.rawValue
|
||
let waiter = box.portWaiter
|
||
box.portWaiter = nil
|
||
box.lock.unlock()
|
||
if let port = listener.port?.rawValue { waiter?.resume(returning: port) }
|
||
case .failed(let error):
|
||
box.lock.lock()
|
||
box.failure = error
|
||
let portWaiter = box.portWaiter
|
||
let connectionWaiter = box.connectionWaiter
|
||
box.portWaiter = nil
|
||
box.connectionWaiter = nil
|
||
box.lock.unlock()
|
||
portWaiter?.resume(throwing: error)
|
||
connectionWaiter?.resume(throwing: error)
|
||
default:
|
||
break
|
||
}
|
||
}
|
||
listener.newConnectionHandler = { [box] connection in
|
||
box.lock.lock()
|
||
if let waiter = box.connectionWaiter {
|
||
box.connectionWaiter = nil
|
||
box.lock.unlock()
|
||
waiter.resume(returning: connection)
|
||
} else {
|
||
box.pending.append(connection)
|
||
box.lock.unlock()
|
||
}
|
||
}
|
||
listener.start(queue: queue)
|
||
|
||
self.listener = listener
|
||
self.pairing = pairing
|
||
self.files = metas
|
||
self.queuePayload = payload
|
||
return pairing
|
||
}
|
||
|
||
/// 等待一个连接并把整个队列推过去。
|
||
func waitAndSend(onProgress: @escaping (PeerTransferUpdate) -> Void) async throws {
|
||
guard let listener, let pairing else {
|
||
throw PeerLink.PeerError.handshake("尚未调用 start()")
|
||
}
|
||
|
||
let connection = try await withCheckedThrowingContinuation {
|
||
(continuation: CheckedContinuation<NWConnection, Error>) in
|
||
box.lock.lock()
|
||
if !box.pending.isEmpty {
|
||
let first = box.pending.removeFirst()
|
||
box.lock.unlock()
|
||
continuation.resume(returning: first)
|
||
} else if let failure = box.failure {
|
||
box.lock.unlock()
|
||
continuation.resume(throwing: failure)
|
||
} else {
|
||
box.connectionWaiter = continuation
|
||
box.lock.unlock()
|
||
}
|
||
}
|
||
// 一次会话只服务一个对端,其余排队的连接直接断开
|
||
box.drainPending().forEach { $0.cancel() }
|
||
|
||
defer { connection.cancel(); listener.cancel() }
|
||
|
||
try await PeerLink.waitReady(connection, queue: queue)
|
||
try await PeerLink.send(connection, type: .queue, payload: queuePayload)
|
||
|
||
var sent: UInt64 = 0
|
||
let startedAt = Date()
|
||
var lastReport = Date.distantPast
|
||
|
||
for (index, meta) in files.enumerated() {
|
||
try Task.checkCancellation()
|
||
try await PeerLink.sendJSON(connection, type: .fileBegin,
|
||
object: ["i": index, "name": meta.name])
|
||
|
||
let handle = try FileHandle(forReadingFrom: fileURLs[index])
|
||
defer { try? handle.close() }
|
||
var fileSent: UInt64 = 0
|
||
while let block = try handle.read(upToCount: PeerLink.chunkSize), !block.isEmpty {
|
||
try Task.checkCancellation()
|
||
guard fileSent &+ UInt64(block.count) <= meta.size else {
|
||
throw PeerLink.PeerError.protocolViolation("本地文件 \(meta.name) 在传输中变大了")
|
||
}
|
||
try await PeerLink.send(connection, type: .data, payload: block)
|
||
fileSent &+= UInt64(block.count)
|
||
sent &+= UInt64(block.count)
|
||
let now = Date()
|
||
if now.timeIntervalSince(lastReport) > 0.1 || sent >= pairing.totalSize {
|
||
lastReport = now
|
||
onProgress(PeerTransferUpdate(
|
||
progress: TransferProgress(
|
||
completed: sent, total: pairing.totalSize,
|
||
bytesPerSecond: Double(sent) / max(0.001, now.timeIntervalSince(startedAt))),
|
||
fileIndex: index, fileCount: files.count, fileName: meta.name))
|
||
}
|
||
}
|
||
guard fileSent == meta.size else {
|
||
throw PeerLink.PeerError.protocolViolation("本地文件 \(meta.name) 只读到 \(fileSent)/\(meta.size) 字节")
|
||
}
|
||
try await PeerLink.sendJSON(connection, type: .fileEnd, object: ["i": index])
|
||
}
|
||
|
||
try await PeerLink.send(connection, type: .eof, payload: Data())
|
||
|
||
let (type, payload) = try await PeerLink.receiveFrame(connection)
|
||
guard type == .result,
|
||
let object = try? JSONSerialization.jsonObject(with: payload) as? [String: Any] else {
|
||
throw PeerLink.PeerError.protocolViolation("收尾帧无效")
|
||
}
|
||
if (object["ok"] as? Bool) != true {
|
||
throw PeerLink.PeerError.rejected((object["error"] as? String) ?? "对方未说明原因")
|
||
}
|
||
}
|
||
|
||
func stop() {
|
||
listener?.cancel()
|
||
listener = nil
|
||
}
|
||
}
|
||
|
||
// MARK: - 接收端
|
||
|
||
/// 扫码的一方。按实例名找到对端并按顺序接收整个队列。
|
||
struct PeerReceiver {
|
||
|
||
let pairing: PeerPairing
|
||
let destinationDirectory: URL
|
||
/// 测试用:跳过 Bonjour,直接连指定端口。
|
||
var directPort: UInt16?
|
||
|
||
func run(onProgress: @escaping (PeerTransferUpdate) -> Void) async throws -> [URL] {
|
||
let queue = DispatchQueue(label: "qft.peer.receiver")
|
||
let parameters = PeerLink.parameters(key: pairing.key, identity: pairing.instance)
|
||
|
||
let endpoint: NWEndpoint
|
||
if let directPort {
|
||
endpoint = .hostPort(host: .ipv4(.loopback), port: .init(rawValue: directPort)!)
|
||
} else {
|
||
endpoint = .service(name: pairing.instance, type: PeerPairing.serviceType,
|
||
domain: "local", interface: nil)
|
||
}
|
||
|
||
let connection = NWConnection(to: endpoint, using: parameters)
|
||
defer { connection.cancel() }
|
||
try await PeerLink.waitReady(connection, queue: queue)
|
||
|
||
do {
|
||
let saved = try await receiveQueue(connection, onProgress: onProgress)
|
||
try await PeerLink.sendJSON(connection, type: .result,
|
||
object: ["ok": true, "saved": saved.map(\.lastPathComponent)])
|
||
return saved
|
||
} catch {
|
||
// 让发送端知道为什么停了,而不是收到一个无解释的断连
|
||
try? await PeerLink.sendJSON(connection, type: .result,
|
||
object: ["ok": false, "error": errorText(error)])
|
||
throw error
|
||
}
|
||
}
|
||
|
||
private func receiveQueue(_ connection: NWConnection,
|
||
onProgress: @escaping (PeerTransferUpdate) -> Void) async throws -> [URL] {
|
||
// --- 清单 ---
|
||
let (queueType, queuePayload) = try await PeerLink.receiveFrame(connection)
|
||
guard queueType == .queue else {
|
||
throw PeerLink.PeerError.protocolViolation("首帧不是文件清单")
|
||
}
|
||
// 摘要对着二维码算:扫码看到的是几个文件、多大,收到的就必须是那些
|
||
guard PeerQueue.digest(of: queuePayload) == pairing.queueDigest else {
|
||
throw PeerLink.PeerError.protocolViolation("文件清单与二维码不符")
|
||
}
|
||
guard let (_, files) = PeerQueue.decode(queuePayload) else {
|
||
throw PeerLink.PeerError.protocolViolation("文件清单无法解析")
|
||
}
|
||
guard files.count == pairing.fileCount,
|
||
files.reduce(UInt64(0), { $0 &+ $1.size }) == pairing.totalSize else {
|
||
throw PeerLink.PeerError.protocolViolation("文件清单的数量或总量与二维码不符")
|
||
}
|
||
|
||
try FileManager.default.createDirectory(at: destinationDirectory,
|
||
withIntermediateDirectories: true)
|
||
|
||
var saved: [URL] = []
|
||
var receivedTotal: UInt64 = 0
|
||
let startedAt = Date()
|
||
var lastReport = Date.distantPast
|
||
|
||
for (index, meta) in files.enumerated() {
|
||
try Task.checkCancellation()
|
||
let (beginType, beginPayload) = try await PeerLink.receiveFrame(connection)
|
||
guard beginType == .fileBegin,
|
||
let begin = try? JSONSerialization.jsonObject(with: beginPayload) as? [String: Any],
|
||
(begin["i"] as? Int) == index else {
|
||
throw PeerLink.PeerError.protocolViolation("第 \(index + 1) 个文件的起始帧无效")
|
||
}
|
||
|
||
let partURL = destinationDirectory.appendingPathComponent(meta.name + ".qftpart")
|
||
try? FileManager.default.removeItem(at: partURL)
|
||
guard FileManager.default.createFile(atPath: partURL.path, contents: nil) else {
|
||
throw QFTError.malformedResponse("无法创建临时文件")
|
||
}
|
||
let handle = try FileHandle(forWritingTo: partURL)
|
||
|
||
var hasher = SHA256()
|
||
var received: UInt64 = 0
|
||
do {
|
||
loop: while true {
|
||
try Task.checkCancellation()
|
||
let (type, payload) = try await PeerLink.receiveFrame(connection)
|
||
switch type {
|
||
case .data:
|
||
guard received &+ UInt64(payload.count) <= meta.size else {
|
||
throw PeerLink.PeerError.protocolViolation("\(meta.name) 的数据超出声明大小")
|
||
}
|
||
try handle.write(contentsOf: payload)
|
||
hasher.update(data: payload)
|
||
received &+= UInt64(payload.count)
|
||
receivedTotal &+= UInt64(payload.count)
|
||
let now = Date()
|
||
if now.timeIntervalSince(lastReport) > 0.1 || receivedTotal >= pairing.totalSize {
|
||
lastReport = now
|
||
onProgress(PeerTransferUpdate(
|
||
progress: TransferProgress(
|
||
completed: receivedTotal, total: pairing.totalSize,
|
||
bytesPerSecond: Double(receivedTotal)
|
||
/ max(0.001, now.timeIntervalSince(startedAt))),
|
||
fileIndex: index, fileCount: files.count, fileName: meta.name))
|
||
}
|
||
case .fileEnd:
|
||
break loop
|
||
default:
|
||
throw PeerLink.PeerError.protocolViolation("数据阶段收到 \(type)")
|
||
}
|
||
}
|
||
try handle.close()
|
||
} catch {
|
||
try? handle.close()
|
||
try? FileManager.default.removeItem(at: partURL)
|
||
saved.forEach { try? FileManager.default.removeItem(at: $0) }
|
||
throw error
|
||
}
|
||
|
||
let actual = hasher.finalize().map { String(format: "%02x", $0) }.joined()
|
||
guard received == meta.size, actual == meta.sha256 else {
|
||
try? FileManager.default.removeItem(at: partURL)
|
||
saved.forEach { try? FileManager.default.removeItem(at: $0) }
|
||
throw QFTError.integrity(
|
||
"\(meta.name):收到 \(received)/\(meta.size) 字节,SHA-256 \(actual == meta.sha256 ? "一致" : "不一致")")
|
||
}
|
||
|
||
let finalURL = DownloadClient.uniqueURL(in: destinationDirectory, name: meta.name)
|
||
try FileManager.default.moveItem(at: partURL, to: finalURL)
|
||
saved.append(finalURL)
|
||
}
|
||
|
||
let (eofType, _) = try await PeerLink.receiveFrame(connection)
|
||
guard eofType == .eof else {
|
||
throw PeerLink.PeerError.protocolViolation("队列结束帧无效")
|
||
}
|
||
return saved
|
||
}
|
||
|
||
private func errorText(_ error: Error) -> String {
|
||
String(((error as? LocalizedError)?.errorDescription ?? "\(error)").prefix(200))
|
||
}
|
||
}
|