feat(drone-dock): 实现局域网扫码直传交付
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import Foundation
|
||||
|
||||
/// 只在商家手机局域网内提供所选文件的临时会话,不包含订单或登录凭证。
|
||||
struct DroneDockNearbyTransferSession: Equatable, Sendable {
|
||||
/// 每次重新生成二维码使用独立身份。
|
||||
let id: UUID
|
||||
/// 游客浏览器访问的局域网接收页地址。
|
||||
let url: URL
|
||||
/// 到期后停止监听并关闭已有连接。
|
||||
let expiresAt: Date
|
||||
}
|
||||
|
||||
/// 本机文件服务的状态;发送完字节不等于游客已经保存至相册。
|
||||
enum DroneDockNearbyTransferEvent: Equatable, Sendable {
|
||||
case visitorConnected
|
||||
/// 本次下载响应的已发送字节数;分段请求只统计该段,不推断游客已有文件。
|
||||
case sending(bytesSent: Int64, totalBytes: Int64)
|
||||
case sent
|
||||
/// 浏览器只请求了部分文件;等待其后续请求,不记为整段视频发送成功。
|
||||
case partialSent
|
||||
case interrupted
|
||||
case stopped
|
||||
case failed(String)
|
||||
}
|
||||
|
||||
/// 闪传页面依赖的本地传输边界,不提供任何云端回退或上传功能。
|
||||
protocol DroneDockNearbyTransferServing: AnyObject {
|
||||
/// 建立临时接收页;回调来自服务串行队列,调用方自行切换 UI 执行上下文。
|
||||
func start(video: DroneDockDeliveryVideo,
|
||||
onEvent: @escaping @Sendable (DroneDockNearbyTransferEvent) -> Void) async throws -> DroneDockNearbyTransferSession
|
||||
/// 同步撤销会话、关闭监听与正在发送的文件,迟到回调不能恢复旧会话。
|
||||
func stop()
|
||||
}
|
||||
|
||||
/// 可向用户显示的局域网服务启动失败原因。
|
||||
enum DroneDockNearbyTransferError: LocalizedError, Equatable {
|
||||
case noLocalNetwork, invalidAddress, randomGenerationFailed, startTimedOut, listenerFailed
|
||||
|
||||
/// 提示用户连接可互通的 Wi-Fi,并允许重新生成二维码。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .noLocalNetwork: "未找到可用的局域网地址,请先连接 Wi-Fi 后重试"
|
||||
case .invalidAddress: "无法使用当前网络地址,请切换 Wi-Fi 后重试"
|
||||
case .randomGenerationFailed: "无法生成本次接收凭证,请重试"
|
||||
case .startTimedOut: "本地传输服务启动超时,请检查网络后重试"
|
||||
case .listenerFailed: "无法启动本地传输服务,请检查局域网权限和网络后重试"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
|
||||
/// 可绑定的 IPv4 局域网接口;正式发现不使用蜂窝、VPN 或公网地址。
|
||||
struct DroneDockNearbyTransferEndpoint: Equatable, Sendable {
|
||||
let address: String
|
||||
let interfaceName: String
|
||||
|
||||
/// 读取已启用的 Wi-Fi / 本地网桥地址,不进行网络探测或广播。
|
||||
static func current() throws -> DroneDockNearbyTransferEndpoint {
|
||||
var list: UnsafeMutablePointer<ifaddrs>?
|
||||
guard getifaddrs(&list) == 0, let first = list else { throw DroneDockNearbyTransferError.noLocalNetwork }
|
||||
defer { freeifaddrs(list) }
|
||||
var candidates: [DroneDockNearbyTransferEndpoint] = []
|
||||
var item: UnsafeMutablePointer<ifaddrs>? = first
|
||||
while let current = item {
|
||||
defer { item = current.pointee.ifa_next }
|
||||
guard let address = current.pointee.ifa_addr, address.pointee.sa_family == UInt8(AF_INET),
|
||||
current.pointee.ifa_flags & UInt32(IFF_UP) != 0,
|
||||
current.pointee.ifa_flags & UInt32(IFF_RUNNING) != 0,
|
||||
current.pointee.ifa_flags & UInt32(IFF_LOOPBACK) == 0 else { continue }
|
||||
let name = String(cString: current.pointee.ifa_name)
|
||||
guard name.hasPrefix("en") || name.hasPrefix("bridge") else { continue }
|
||||
var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
guard getnameinfo(address, socklen_t(address.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 else { continue }
|
||||
let value = String(cString: host)
|
||||
guard isPrivateIPv4(value) else { continue }
|
||||
candidates.append(.init(address: value, interfaceName: name))
|
||||
}
|
||||
guard let selected = candidates.sorted(by: { lhs, rhs in
|
||||
let left = lhs.interfaceName == "en0" ? "0" : lhs.interfaceName
|
||||
let right = rhs.interfaceName == "en0" ? "0" : rhs.interfaceName
|
||||
return left < right
|
||||
}).first else { throw DroneDockNearbyTransferError.noLocalNetwork }
|
||||
return selected
|
||||
}
|
||||
|
||||
/// 接收页面只公布 RFC 1918 地址,避免意外选择公网或蜂窝接口。
|
||||
static func isPrivateIPv4(_ address: String) -> Bool {
|
||||
let parts = address.split(separator: ".", omittingEmptySubsequences: false)
|
||||
guard parts.count == 4 else { return false }
|
||||
let numbers = parts.compactMap { part -> Int? in
|
||||
guard !part.isEmpty, part.allSatisfy({ $0 >= "0" && $0 <= "9" }), let value = Int(part), value <= 255 else { return nil }
|
||||
return value
|
||||
}
|
||||
guard numbers.count == 4 else { return false }
|
||||
return numbers[0] == 10 || (numbers[0] == 172 && (16...31).contains(numbers[1])) || (numbers[0] == 192 && numbers[1] == 168)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import Foundation
|
||||
|
||||
/// 局域网文件服务的小型 HTTP 解析器,只支持单个无请求体的 GET / HEAD 请求。
|
||||
enum DroneDockNearbyTransferHTTP {
|
||||
/// 限制每个连接的头部缓存,避免将任意大小请求读入内存。
|
||||
static let maximumHeaderBytes = 16 * 1_024
|
||||
/// 文件流每次最多读取 64 KiB;不随视频大小增长。
|
||||
static let fileChunkBytes = 64 * 1_024
|
||||
|
||||
/// 已校验的请求,路径保持原始形式,拒绝通过编码或查询参数绕过会话路径。
|
||||
struct Request: Equatable {
|
||||
let method: String
|
||||
let target: String
|
||||
let headers: [String: String]
|
||||
var isHead: Bool { method == "HEAD" }
|
||||
}
|
||||
|
||||
/// 一个闭区间文件片段,用于 Content-Range 和磁盘 seek。
|
||||
struct ByteRange: Equatable {
|
||||
let lower: Int64
|
||||
let upper: Int64
|
||||
var count: Int64 { upper - lower + 1 }
|
||||
}
|
||||
|
||||
/// 拒绝格式异常、重复头、过长头部及带请求体的请求。
|
||||
static func parse(_ data: Data) -> Request? {
|
||||
guard data.count <= maximumHeaderBytes, data.suffix(4) == Data([13, 10, 13, 10]),
|
||||
let text = String(data: data.dropLast(4), encoding: .utf8) else { return nil }
|
||||
// CRLF 在 Swift String 中是一个 Character;协议分隔符必须按四个字节移除。
|
||||
let lines = text.components(separatedBy: "\r\n")
|
||||
guard let first = lines.first, first.utf8.count <= 2_048 else { return nil }
|
||||
let parts = first.split(separator: " ", omittingEmptySubsequences: false)
|
||||
guard parts.count == 3, ["HTTP/1.0", "HTTP/1.1"].contains(String(parts[2])),
|
||||
!parts[0].isEmpty, parts[1].hasPrefix("/"),
|
||||
parts[1].allSatisfy({ $0.isASCII && !$0.isWhitespace && !$0.isNewline }) else { return nil }
|
||||
var headers: [String: String] = [:]
|
||||
let allowedName = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-!")
|
||||
for line in lines.dropFirst() {
|
||||
guard let colon = line.firstIndex(of: ":"), colon != line.startIndex else { return nil }
|
||||
let name = String(line[..<colon])
|
||||
let value = String(line[line.index(after: colon)...]).trimmingCharacters(in: .whitespaces)
|
||||
guard name.unicodeScalars.allSatisfy(allowedName.contains),
|
||||
value.unicodeScalars.allSatisfy({ $0.value >= 32 && $0.value != 127 }),
|
||||
headers[name.lowercased()] == nil else { return nil }
|
||||
headers[name.lowercased()] = value
|
||||
}
|
||||
guard headers["transfer-encoding"] == nil,
|
||||
headers["content-length"] == nil || headers["content-length"] == "0",
|
||||
String(parts[2]) != "HTTP/1.1" || headers["host"] != nil else { return nil }
|
||||
return Request(method: String(parts[0]), target: String(parts[1]), headers: headers)
|
||||
}
|
||||
|
||||
/// 解析单段 Range,包括从某字节到末尾及后缀片段;多段或越界请求返回 nil。
|
||||
static func range(_ value: String, size: Int64) -> ByteRange? {
|
||||
guard size > 0, value.hasPrefix("bytes=") else { return nil }
|
||||
let parts = value.dropFirst(6).split(separator: "-", omittingEmptySubsequences: false)
|
||||
guard parts.count == 2 else { return nil }
|
||||
func number(_ text: Substring) -> Int64? {
|
||||
guard !text.isEmpty, text.allSatisfy({ $0 >= "0" && $0 <= "9" }) else { return nil }
|
||||
return Int64(text)
|
||||
}
|
||||
if parts[0].isEmpty {
|
||||
guard let suffix = number(parts[1]), suffix > 0 else { return nil }
|
||||
return ByteRange(lower: max(0, size - suffix), upper: size - 1)
|
||||
}
|
||||
guard let lower = number(parts[0]), lower < size else { return nil }
|
||||
if parts[1].isEmpty { return ByteRange(lower: lower, upper: size - 1) }
|
||||
guard let upper = number(parts[1]), upper >= lower else { return nil }
|
||||
return ByteRange(lower: lower, upper: min(upper, size - 1))
|
||||
}
|
||||
|
||||
/// 保留中文文件名的 RFC 5987 下载头;ASCII 回退名不含用户输入。
|
||||
static func disposition(fileName: String) -> String {
|
||||
let allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$&+-.^_`|~")
|
||||
let escaped = fileName.addingPercentEncoding(withAllowedCharacters: allowed) ?? "video.mp4"
|
||||
let ext = URL(fileURLWithPath: fileName).pathExtension.lowercased()
|
||||
let safeExtension = ext.allSatisfy({ $0.isASCII && $0.isLetter }) && !ext.isEmpty ? ext : "mp4"
|
||||
return "attachment; filename=\"video.\(safeExtension)\"; filename*=UTF-8''\(escaped)"
|
||||
}
|
||||
|
||||
/// 所有响应禁止缓存和站外引用,不提供跨域访问能力。
|
||||
static func header(status: Int, length: Int64, contentType: String, extra: [String: String] = [:]) -> Data {
|
||||
let reasons = [200: "OK", 206: "Partial Content", 400: "Bad Request", 403: "Forbidden", 404: "Not Found",
|
||||
405: "Method Not Allowed", 409: "Conflict", 416: "Range Not Satisfiable", 431: "Request Header Fields Too Large", 500: "Internal Server Error", 503: "Service Unavailable"]
|
||||
var headers = ["Content-Length": String(length), "Content-Type": contentType,
|
||||
"Connection": "close", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "no-referrer", "X-Frame-Options": "DENY"]
|
||||
headers.merge(extra) { _, new in new }
|
||||
let lines = headers.keys.sorted().map { "\($0): \(headers[$0]!)" }.joined(separator: "\r\n")
|
||||
return Data("HTTP/1.1 \(status) \(reasons[status] ?? "Error")\r\n\(lines)\r\n\r\n".utf8)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import Foundation
|
||||
|
||||
/// 随 App 分发的局域网接收页;纯 HTML/CSS,不请求远程资源,也不在浏览器内缓存整段视频。
|
||||
enum DroneDockNearbyTransferPage {
|
||||
/// 生成单个视频的下载页,仅接受当前局域网会话格式的相对下载路径。
|
||||
static func html(video: DroneDockDeliveryVideo, downloadPath: String) -> String {
|
||||
let fileName = escape(video.fileName)
|
||||
let size = escape(ByteCountFormatter.string(fromByteCount: Int64(max(0, video.fileSize)), countStyle: .file))
|
||||
let isValidPath = downloadPath.range(of: #"\A/s/[0-9a-f]{64}/video\z"#, options: .regularExpression) != nil
|
||||
let download: String
|
||||
if isValidPath {
|
||||
download = """
|
||||
<a class="download" href="\(escape(downloadPath))" download aria-label="下载视频">下载视频 <span aria-hidden="true">↓</span></a>
|
||||
<p class="download-note">点击后,请在浏览器下载列表查看进度。</p>
|
||||
"""
|
||||
} else {
|
||||
download = """
|
||||
<p class="unavailable" role="status">下载链接不可用,请让商家重新生成二维码。</p>
|
||||
"""
|
||||
}
|
||||
return """
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>面对面闪传 · 随心瞰</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; color: #162b24; background: #f4f7f5; font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
|
||||
main { width: 100%; max-width: 500px; margin: 0 auto; padding: 30px 20px calc(28px + env(safe-area-inset-bottom)); }
|
||||
.brand { display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 650; color: #53675d; }
|
||||
.brand-mark { display: inline-grid; place-items: center; width: 26px; height: 26px; background: #16845c; color: white; border-radius: 8px; font-size: 15px; }
|
||||
.intro { margin: 32px 0 24px; }
|
||||
.badge { display: inline-flex; align-items: center; gap: 6px; color: #167b55; background: #e5f3eb; border-radius: 20px; padding: 4px 10px; font-size: 12px; font-weight: 600; }
|
||||
.badge::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: #16845c; }
|
||||
h1 { font-size: 28px; line-height: 1.3; letter-spacing: -.6px; margin: 15px 0 9px; }
|
||||
.subtitle { margin: 0; color: #68796f; font-size: 14px; }
|
||||
.file-card { background: #fff; border: 1px solid #e3ebe6; border-radius: 22px; padding: 24px 20px 20px; box-shadow: 0 8px 28px #16382906; }
|
||||
.file-row { display: flex; align-items: center; gap: 13px; margin-bottom: 24px; }
|
||||
.file-icon { display: grid; place-items: center; flex: 0 0 50px; height: 58px; border-radius: 13px; background: #edf6f0; color: #16845c; font-size: 22px; }
|
||||
.file-info { min-width: 0; }
|
||||
.file-name { margin: 0; font-size: 16px; font-weight: 650; line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.file-size { margin: 5px 0 0; color: #7b8981; font-size: 13px; }
|
||||
.download { display: flex; min-height: 52px; align-items: center; justify-content: center; gap: 12px; border-radius: 14px; background: #16845c; color: #fff; text-decoration: none; font-weight: 650; -webkit-tap-highlight-color: transparent; }
|
||||
.download:active { background: #106846; }
|
||||
.download:focus-visible, summary:focus-visible { outline: 3px solid #78bda0; outline-offset: 4px; }
|
||||
.download span { font-size: 22px; line-height: 1; }
|
||||
.download-note { margin: 12px 0 0; text-align: center; font-size: 12px; color: #7b8981; }
|
||||
.unavailable { background: #fff4e6; color: #8b591a; padding: 14px; border-radius: 12px; font-size: 14px; }
|
||||
.connection { display: flex; align-items: flex-start; gap: 10px; margin: 18px 2px 25px; color: #64766b; font-size: 13px; }
|
||||
.connection-mark { color: #16845c; font-size: 16px; line-height: 1.5; }
|
||||
.connection p { margin: 0; }
|
||||
.help { border-top: 1px solid #dfe8e2; }
|
||||
details { border-bottom: 1px solid #dfe8e2; padding: 15px 0; }
|
||||
summary { cursor: pointer; font-size: 14px; font-weight: 600; }
|
||||
details p { margin: 10px 0 0; padding-left: 15px; color: #68796f; font-size: 13px; }
|
||||
.footer { margin-top: 26px; color: #91a096; text-align: center; font-size: 12px; }
|
||||
@media (min-width: 600px) { main { padding-top: 48px; } }
|
||||
@media (prefers-reduced-motion: no-preference) { .download { transition: background .15s; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="brand"><span class="brand-mark" aria-hidden="true">瞰</span>随心瞰 · 面对面闪传</div>
|
||||
<header class="intro">
|
||||
<span class="badge">本地直传</span>
|
||||
<h1>你的航拍作品<br>就在这里</h1>
|
||||
<p class="subtitle">视频由附近的商家手机直接提供。</p>
|
||||
</header>
|
||||
<section class="file-card" aria-label="待接收视频">
|
||||
<div class="file-row">
|
||||
<div class="file-icon" aria-hidden="true">▶</div>
|
||||
<div class="file-info">
|
||||
<p class="file-name">\(fileName)</p>
|
||||
<p class="file-size">视频文件 · \(size)</p>
|
||||
</div>
|
||||
</div>
|
||||
\(download)
|
||||
</section>
|
||||
<div class="connection">
|
||||
<span class="connection-mark" aria-hidden="true">◎</span>
|
||||
<p>双方请保持连接同一个 Wi-Fi。<br>传输期间,请让商家保持闪传页面亮屏。</p>
|
||||
</div>
|
||||
<section class="help" aria-label="接收帮助">
|
||||
<details>
|
||||
<summary>iPhone 下载后在哪里查看?</summary>
|
||||
<p>建议使用 Safari 打开。下载前,可在系统设置中的 Safari 下载设置里选择“我的 iPhone”,避免保存到 iCloud Drive。</p>
|
||||
<p>下载完成后,在“文件”App 的“下载”文件夹打开视频。格式受支持时,可通过分享菜单选择“存储视频”保存到相册。</p>
|
||||
</details>
|
||||
<details>
|
||||
<summary>安卓下载后在哪里查看?</summary>
|
||||
<p>请在浏览器的“下载内容”或手机文件管理的“下载”文件夹中查看。是否显示在相册中取决于手机和视频格式。</p>
|
||||
</details>
|
||||
<details>
|
||||
<summary>无法下载或传输中断怎么办?</summary>
|
||||
<p>请先确认双方仍连接同一个 Wi-Fi,商家没有关闭闪传页面,再点击下载重试。部分公共 Wi-Fi 会限制手机之间连接,可以更换网络后重新扫码。</p>
|
||||
<p>本次链接短时有效。商家结束闪传后链接会失效,需要重新生成二维码。</p>
|
||||
</details>
|
||||
</section>
|
||||
<p class="footer">无需安装 App · 接收后请核对视频是否完整</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
}
|
||||
|
||||
private static func escape(_ value: String) -> String {
|
||||
value.replacingOccurrences(of: "&", with: "&")
|
||||
.replacingOccurrences(of: "<", with: "<")
|
||||
.replacingOccurrences(of: ">", with: ">")
|
||||
.replacingOccurrences(of: "\"", with: """)
|
||||
.replacingOccurrences(of: "'", with: "'")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
import Foundation
|
||||
import Network
|
||||
import Security
|
||||
|
||||
/// 仅绑定本地接口的临时 HTTP 服务;视频按 64 KiB 分块读取,不访问任何云端接口。
|
||||
final class DroneDockNearbyTransferServer: DroneDockNearbyTransferServing, @unchecked Sendable {
|
||||
private let queue = DispatchQueue(label: "cn.suixinkan.nearby-transfer")
|
||||
private let queueKey = DispatchSpecificKey<Bool>()
|
||||
private let endpointProvider: @Sendable () throws -> DroneDockNearbyTransferEndpoint
|
||||
private let lifetime: TimeInterval
|
||||
private let headerTimeout: TimeInterval
|
||||
private let startTimeout: TimeInterval
|
||||
private var generation: UInt64 = 0
|
||||
private var context: SessionContext?
|
||||
|
||||
/// 正式使用自动发现的局域网地址;测试可注入回环端点与短超时,无需访问外网。
|
||||
init(endpointProvider: @escaping @Sendable () throws -> DroneDockNearbyTransferEndpoint = DroneDockNearbyTransferEndpoint.current,
|
||||
lifetime: TimeInterval = 600, headerTimeout: TimeInterval = 10, startTimeout: TimeInterval = 10) {
|
||||
self.endpointProvider = endpointProvider
|
||||
self.lifetime = max(0.05, lifetime)
|
||||
self.headerTimeout = max(0.05, headerTimeout)
|
||||
self.startTimeout = max(0.05, startTimeout)
|
||||
queue.setSpecific(key: queueKey, value: true)
|
||||
}
|
||||
|
||||
deinit { stop() }
|
||||
|
||||
/// 建立新会话前撤销旧会话;取消启动会关闭监听且恰好恢复一次 continuation。
|
||||
func start(video: DroneDockDeliveryVideo,
|
||||
onEvent: @escaping @Sendable (DroneDockNearbyTransferEvent) -> Void) async throws -> DroneDockNearbyTransferSession {
|
||||
let id = UUID()
|
||||
let cancellation = StartCancellation()
|
||||
let expectedGeneration = onQueue { generation }
|
||||
return try await withTaskCancellationHandler {
|
||||
try Task.checkCancellation()
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
queue.async { [self] in
|
||||
guard expectedGeneration == generation, !cancellation.isCancelled else {
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
begin(id: id, video: video, cancellation: cancellation, onEvent: onEvent, continuation: continuation)
|
||||
}
|
||||
}
|
||||
} onCancel: { [self] in
|
||||
cancellation.cancel()
|
||||
onQueue {
|
||||
if context?.id == id { close(error: CancellationError(), event: nil) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 返回前会话已撤销;排队中的启动与发送回调不能复活旧二维码。
|
||||
func stop() {
|
||||
onQueue {
|
||||
generation &+= 1
|
||||
close(error: CancellationError(), event: nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func onQueue<T>(_ action: () throws -> T) rethrows -> T {
|
||||
if DispatchQueue.getSpecific(key: queueKey) == true { return try action() }
|
||||
return try queue.sync(execute: action)
|
||||
}
|
||||
|
||||
private func begin(id: UUID, video: DroneDockDeliveryVideo, cancellation: StartCancellation,
|
||||
onEvent: @escaping @Sendable (DroneDockNearbyTransferEvent) -> Void,
|
||||
continuation: CheckedContinuation<DroneDockNearbyTransferSession, Error>) {
|
||||
close(error: CancellationError(), event: .stopped)
|
||||
do {
|
||||
let contentType = try DroneDockFilmPolicy.validate(video: video)
|
||||
let endpoint = try endpointProvider()
|
||||
guard IPv4Address(endpoint.address) != nil,
|
||||
DroneDockNearbyTransferEndpoint.isPrivateIPv4(endpoint.address) || endpoint.address == "127.0.0.1" else {
|
||||
throw DroneDockNearbyTransferError.invalidAddress
|
||||
}
|
||||
let token = try makeToken()
|
||||
let parameters = NWParameters.tcp
|
||||
parameters.requiredLocalEndpoint = .hostPort(host: .init(endpoint.address), port: .any)
|
||||
parameters.includePeerToPeer = false
|
||||
// 手机热点可能被标记为 expensive;本地绑定已限制接口,不按资费标签误拦局域网。
|
||||
let listener = try NWListener(using: parameters)
|
||||
let current = SessionContext(id: id, video: video, contentType: contentType, token: token,
|
||||
endpoint: endpoint, listener: listener, expiresAt: Date().addingTimeInterval(lifetime),
|
||||
cancellation: cancellation, onEvent: onEvent, continuation: continuation)
|
||||
context = current
|
||||
listener.stateUpdateHandler = { [weak self] state in self?.listenerChanged(state, id: id) }
|
||||
listener.newConnectionHandler = { [weak self] connection in
|
||||
guard let self else { connection.cancel(); return }
|
||||
accept(connection, sessionID: id)
|
||||
}
|
||||
let timeout = DispatchWorkItem { [weak self] in
|
||||
guard let self, context?.id == id, context?.continuation != nil else { return }
|
||||
close(error: DroneDockNearbyTransferError.startTimedOut, event: .failed(DroneDockNearbyTransferError.startTimedOut.localizedDescription))
|
||||
}
|
||||
current.startTimer = timeout
|
||||
queue.asyncAfter(deadline: .now() + startTimeout, execute: timeout)
|
||||
listener.start(queue: queue)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
|
||||
private func listenerChanged(_ state: NWListener.State, id: UUID) {
|
||||
guard let current = context, current.id == id else { return }
|
||||
switch state {
|
||||
case .ready:
|
||||
guard !current.cancellation.isCancelled else { close(error: CancellationError(), event: nil); return }
|
||||
guard current.continuation != nil, let port = current.listener.port else { return }
|
||||
current.startTimer?.cancel()
|
||||
current.startTimer = nil
|
||||
var components = URLComponents()
|
||||
components.scheme = "http"
|
||||
components.host = current.endpoint.address
|
||||
components.port = Int(port.rawValue)
|
||||
components.path = current.pagePath
|
||||
guard let url = components.url else { close(error: DroneDockNearbyTransferError.invalidAddress, event: nil); return }
|
||||
current.host = "\(current.endpoint.address):\(port.rawValue)"
|
||||
let session = DroneDockNearbyTransferSession(id: id, url: url, expiresAt: current.expiresAt)
|
||||
let pending = current.continuation
|
||||
current.continuation = nil
|
||||
installSessionTimers(id: id)
|
||||
pending?.resume(returning: session)
|
||||
case .failed:
|
||||
close(error: DroneDockNearbyTransferError.listenerFailed,
|
||||
event: .failed(DroneDockNearbyTransferError.listenerFailed.localizedDescription))
|
||||
case .cancelled:
|
||||
close(error: CancellationError(), event: .stopped)
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
private func installSessionTimers(id: UUID) {
|
||||
guard let current = context, current.id == id else { return }
|
||||
let expiry = DispatchWorkItem { [weak self] in
|
||||
guard let self, context?.id == id else { return }
|
||||
close(error: CancellationError(), event: .failed("本次闪传已到期,请重新生成二维码"))
|
||||
}
|
||||
current.expiryTimer = expiry
|
||||
queue.asyncAfter(deadline: .now() + max(0, current.expiresAt.timeIntervalSinceNow), execute: expiry)
|
||||
let monitor = DispatchSource.makeTimerSource(queue: queue)
|
||||
monitor.schedule(deadline: .now() + 2, repeating: 2)
|
||||
monitor.setEventHandler { [weak self] in
|
||||
guard let self, let active = context, active.id == id else { return }
|
||||
guard let latest = try? endpointProvider(), latest == active.endpoint else {
|
||||
close(error: CancellationError(), event: .failed("网络已变化,请连接同一 Wi-Fi 后重新生成二维码"))
|
||||
return
|
||||
}
|
||||
}
|
||||
current.networkTimer = monitor
|
||||
monitor.resume()
|
||||
}
|
||||
|
||||
private func accept(_ connection: NWConnection, sessionID: UUID) {
|
||||
guard let current = context, current.id == sessionID, current.continuation == nil,
|
||||
current.expiresAt > Date(), current.connections.count < 8 else { connection.cancel(); return }
|
||||
if case .hostPort(let host, _) = connection.endpoint {
|
||||
let address = String(describing: host)
|
||||
guard DroneDockNearbyTransferEndpoint.isPrivateIPv4(address)
|
||||
|| (current.endpoint.address == "127.0.0.1" && address == "127.0.0.1") else { connection.cancel(); return }
|
||||
} else { connection.cancel(); return }
|
||||
let state = ConnectionContext(connection: connection)
|
||||
current.connections[state.id] = state
|
||||
connection.stateUpdateHandler = { [weak self] status in
|
||||
guard let self else { return }
|
||||
switch status {
|
||||
case .ready: receiveHeader(id: state.id, sessionID: sessionID)
|
||||
case .failed, .cancelled: finish(id: state.id, sessionID: sessionID, successful: false)
|
||||
default: break
|
||||
}
|
||||
}
|
||||
setTimeout(id: state.id, sessionID: sessionID, seconds: headerTimeout)
|
||||
connection.start(queue: queue)
|
||||
}
|
||||
|
||||
private func receiveHeader(id: UUID, sessionID: UUID) {
|
||||
guard let state = connection(id: id, sessionID: sessionID) else { return }
|
||||
let remaining = DroneDockNearbyTransferHTTP.maximumHeaderBytes - state.requestBytes.count
|
||||
guard remaining > 0 else { sendError(431, id: id, sessionID: sessionID); return }
|
||||
state.connection.receive(minimumIncompleteLength: 1, maximumLength: min(4_096, remaining)) { [weak self] data, _, complete, error in
|
||||
guard let self, let state = connection(id: id, sessionID: sessionID) else { return }
|
||||
if let data { state.requestBytes.append(data) }
|
||||
if let ending = state.requestBytes.range(of: Data("\r\n\r\n".utf8)) {
|
||||
guard ending.upperBound == state.requestBytes.endIndex,
|
||||
let request = DroneDockNearbyTransferHTTP.parse(state.requestBytes) else {
|
||||
sendError(400, id: id, sessionID: sessionID); return
|
||||
}
|
||||
state.requestBytes.removeAll(keepingCapacity: false)
|
||||
respond(to: request, id: id, sessionID: sessionID)
|
||||
} else if error != nil || complete {
|
||||
finish(id: id, sessionID: sessionID, successful: false)
|
||||
} else { receiveHeader(id: id, sessionID: sessionID) }
|
||||
}
|
||||
}
|
||||
|
||||
private func respond(to request: DroneDockNearbyTransferHTTP.Request, id: UUID, sessionID: UUID) {
|
||||
guard let current = context, current.id == sessionID, let state = current.connections[id] else { return }
|
||||
if let host = request.headers["host"], host != current.host { sendError(403, id: id, sessionID: sessionID, head: request.isHead); return }
|
||||
guard ["GET", "HEAD"].contains(request.method) else {
|
||||
sendError(405, id: id, sessionID: sessionID, extra: ["Allow": "GET, HEAD"]); return
|
||||
}
|
||||
guard current.expiresAt > Date() else { close(error: CancellationError(), event: .failed("本次闪传已到期,请重新生成二维码")); return }
|
||||
if request.target == current.pagePath {
|
||||
let body = Data(DroneDockNearbyTransferPage.html(video: current.video, downloadPath: current.videoPath).utf8)
|
||||
let csp = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
|
||||
let header = DroneDockNearbyTransferHTTP.header(status: 200, length: Int64(body.count), contentType: "text/html; charset=utf-8",
|
||||
extra: ["Content-Security-Policy": csp])
|
||||
if !request.isHead { current.onEvent(.visitorConnected) }
|
||||
sendSmall(header + (request.isHead ? Data() : body), id: id, sessionID: sessionID)
|
||||
return
|
||||
}
|
||||
guard request.target == current.videoPath else { sendError(404, id: id, sessionID: sessionID, head: request.isHead); return }
|
||||
do { _ = try DroneDockFilmPolicy.validate(video: current.video) }
|
||||
catch { sendError(409, id: id, sessionID: sessionID, head: request.isHead); return }
|
||||
let size = Int64(current.video.fileSize)
|
||||
let etag = "\"\(current.video.id.uuidString.lowercased())-\(size)\""
|
||||
let requestedRange = request.headers["if-range"] == nil || request.headers["if-range"] == etag ? request.headers["range"] : nil
|
||||
let range: DroneDockNearbyTransferHTTP.ByteRange
|
||||
if let requestedRange {
|
||||
guard let value = DroneDockNearbyTransferHTTP.range(requestedRange, size: size) else {
|
||||
sendError(416, id: id, sessionID: sessionID, head: request.isHead, extra: ["Content-Range": "bytes */\(size)"]); return
|
||||
}
|
||||
range = value
|
||||
} else { range = .init(lower: 0, upper: size - 1) }
|
||||
var extra = ["Accept-Ranges": "bytes", "ETag": etag,
|
||||
"Content-Disposition": DroneDockNearbyTransferHTTP.disposition(fileName: current.video.fileName)]
|
||||
if requestedRange != nil { extra["Content-Range"] = "bytes \(range.lower)-\(range.upper)/\(size)" }
|
||||
let header = DroneDockNearbyTransferHTTP.header(status: requestedRange == nil ? 200 : 206,
|
||||
length: range.count, contentType: current.contentType, extra: extra)
|
||||
if request.isHead { sendSmall(header, id: id, sessionID: sessionID); return }
|
||||
guard current.downloadID == nil else { sendError(409, id: id, sessionID: sessionID); return }
|
||||
do {
|
||||
let file = try FileHandle(forReadingFrom: current.video.url)
|
||||
try file.seek(toOffset: UInt64(range.lower))
|
||||
state.file = file
|
||||
} catch { sendError(500, id: id, sessionID: sessionID); return }
|
||||
current.downloadID = id
|
||||
state.isDownload = true
|
||||
state.responseBytes = range.count
|
||||
state.isWholeFile = range.lower == 0 && range.upper == size - 1
|
||||
state.lastProgressTime = DispatchTime.now().uptimeNanoseconds
|
||||
current.onEvent(.sending(bytesSent: 0, totalBytes: range.count))
|
||||
setTimeout(id: id, sessionID: sessionID, seconds: 30)
|
||||
state.connection.send(content: header, completion: .contentProcessed { [weak self] error in
|
||||
guard let self else { return }
|
||||
if error != nil { finish(id: id, sessionID: sessionID, successful: false) }
|
||||
else { sendChunk(id: id, sessionID: sessionID) }
|
||||
})
|
||||
}
|
||||
|
||||
private func sendChunk(id: UUID, sessionID: UUID) {
|
||||
guard let state = connection(id: id, sessionID: sessionID), let file = state.file else { return }
|
||||
let remaining = state.responseBytes - state.sentBytes
|
||||
guard remaining > 0 else { finish(id: id, sessionID: sessionID, successful: true); return }
|
||||
do {
|
||||
guard let data = try file.read(upToCount: Int(min(Int64(DroneDockNearbyTransferHTTP.fileChunkBytes), remaining))),
|
||||
!data.isEmpty else { finish(id: id, sessionID: sessionID, successful: false); return }
|
||||
let count = Int64(data.count)
|
||||
let last = count == remaining
|
||||
setTimeout(id: id, sessionID: sessionID, seconds: 30)
|
||||
state.connection.send(content: data, contentContext: last ? .finalMessage : .defaultMessage,
|
||||
isComplete: true, completion: .contentProcessed { [weak self] error in
|
||||
guard let self, let state = connection(id: id, sessionID: sessionID) else { return }
|
||||
if error != nil { finish(id: id, sessionID: sessionID, successful: false); return }
|
||||
state.sentBytes += count
|
||||
let now = DispatchTime.now().uptimeNanoseconds
|
||||
if last || now - state.lastProgressTime >= 100_000_000 {
|
||||
state.lastProgressTime = now
|
||||
context?.onEvent(.sending(bytesSent: state.sentBytes, totalBytes: state.responseBytes))
|
||||
}
|
||||
if last { finish(id: id, sessionID: sessionID, successful: true) }
|
||||
else { sendChunk(id: id, sessionID: sessionID) }
|
||||
})
|
||||
} catch { finish(id: id, sessionID: sessionID, successful: false) }
|
||||
}
|
||||
|
||||
private func sendError(_ status: Int, id: UUID, sessionID: UUID, head: Bool = false, extra: [String: String] = [:]) {
|
||||
let body = Data("本次请求无法处理,请返回商家页面重新扫码。".utf8)
|
||||
let header = DroneDockNearbyTransferHTTP.header(status: status, length: Int64(body.count), contentType: "text/plain; charset=utf-8", extra: extra)
|
||||
sendSmall(header + (head ? Data() : body), id: id, sessionID: sessionID)
|
||||
}
|
||||
|
||||
private func sendSmall(_ data: Data, id: UUID, sessionID: UUID) {
|
||||
guard let state = connection(id: id, sessionID: sessionID) else { return }
|
||||
setTimeout(id: id, sessionID: sessionID, seconds: 30)
|
||||
state.connection.send(content: data, contentContext: .finalMessage, isComplete: true,
|
||||
completion: .contentProcessed { [weak self] error in self?.finish(id: id, sessionID: sessionID, successful: error == nil) })
|
||||
}
|
||||
|
||||
private func connection(id: UUID, sessionID: UUID) -> ConnectionContext? {
|
||||
guard context?.id == sessionID else { return nil }
|
||||
return context?.connections[id]
|
||||
}
|
||||
|
||||
private func setTimeout(id: UUID, sessionID: UUID, seconds: TimeInterval) {
|
||||
guard let state = connection(id: id, sessionID: sessionID) else { return }
|
||||
state.timeout?.cancel()
|
||||
let timeout = DispatchWorkItem { [weak self] in self?.finish(id: id, sessionID: sessionID, successful: false) }
|
||||
state.timeout = timeout
|
||||
queue.asyncAfter(deadline: .now() + seconds, execute: timeout)
|
||||
}
|
||||
|
||||
private func finish(id: UUID, sessionID: UUID, successful: Bool) {
|
||||
guard let current = context, current.id == sessionID, let state = current.connections.removeValue(forKey: id) else { return }
|
||||
state.timeout?.cancel()
|
||||
try? state.file?.close()
|
||||
state.file = nil
|
||||
state.connection.stateUpdateHandler = nil
|
||||
state.connection.cancel()
|
||||
if current.downloadID == id { current.downloadID = nil }
|
||||
if state.isDownload {
|
||||
if successful && state.isWholeFile && state.sentBytes == state.responseBytes { current.onEvent(.sent) }
|
||||
else if successful { current.onEvent(.partialSent) }
|
||||
else if !successful { current.onEvent(.interrupted) }
|
||||
}
|
||||
}
|
||||
|
||||
private func close(error: Error, event: DroneDockNearbyTransferEvent?) {
|
||||
guard let old = context else { return }
|
||||
context = nil
|
||||
old.startTimer?.cancel()
|
||||
old.expiryTimer?.cancel()
|
||||
old.networkTimer?.cancel()
|
||||
old.listener.stateUpdateHandler = nil
|
||||
old.listener.newConnectionHandler = nil
|
||||
old.listener.cancel()
|
||||
for connection in old.connections.values {
|
||||
connection.timeout?.cancel()
|
||||
try? connection.file?.close()
|
||||
connection.file = nil
|
||||
connection.connection.stateUpdateHandler = nil
|
||||
connection.connection.cancel()
|
||||
}
|
||||
old.connections.removeAll()
|
||||
old.continuation?.resume(throwing: error)
|
||||
old.continuation = nil
|
||||
if let event { old.onEvent(event) }
|
||||
}
|
||||
|
||||
private func makeToken() throws -> String {
|
||||
var bytes = [UInt8](repeating: 0, count: 32)
|
||||
guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else {
|
||||
throw DroneDockNearbyTransferError.randomGenerationFailed
|
||||
}
|
||||
return bytes.map { String(format: "%02x", $0) }.joined()
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动取消标记在任务执行器与服务队列间同步,取消先到时也不会遗留监听。
|
||||
private final class StartCancellation: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var cancelled = false
|
||||
var isCancelled: Bool { lock.lock(); defer { lock.unlock() }; return cancelled }
|
||||
func cancel() { lock.lock(); cancelled = true; lock.unlock() }
|
||||
}
|
||||
|
||||
/// 一个 listener 与其授权文件的生命周期,所有成员只在服务串行队列访问。
|
||||
private final class SessionContext {
|
||||
let id: UUID
|
||||
let video: DroneDockDeliveryVideo
|
||||
let contentType: String
|
||||
let token: String
|
||||
let endpoint: DroneDockNearbyTransferEndpoint
|
||||
let listener: NWListener
|
||||
let expiresAt: Date
|
||||
let cancellation: StartCancellation
|
||||
let onEvent: @Sendable (DroneDockNearbyTransferEvent) -> Void
|
||||
var continuation: CheckedContinuation<DroneDockNearbyTransferSession, Error>?
|
||||
var connections: [UUID: ConnectionContext] = [:]
|
||||
var downloadID: UUID?
|
||||
var host = ""
|
||||
var startTimer: DispatchWorkItem?
|
||||
var expiryTimer: DispatchWorkItem?
|
||||
var networkTimer: DispatchSourceTimer?
|
||||
var pagePath: String { "/s/\(token)" }
|
||||
var videoPath: String { pagePath + "/video" }
|
||||
|
||||
init(id: UUID, video: DroneDockDeliveryVideo, contentType: String, token: String,
|
||||
endpoint: DroneDockNearbyTransferEndpoint, listener: NWListener, expiresAt: Date,
|
||||
cancellation: StartCancellation, onEvent: @escaping @Sendable (DroneDockNearbyTransferEvent) -> Void,
|
||||
continuation: CheckedContinuation<DroneDockNearbyTransferSession, Error>) {
|
||||
self.id = id; self.video = video; self.contentType = contentType; self.token = token
|
||||
self.endpoint = endpoint; self.listener = listener; self.expiresAt = expiresAt
|
||||
self.cancellation = cancellation; self.onEvent = onEvent; self.continuation = continuation
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个有界 HTTP 请求及文件游标,关闭连接时同步释放文件句柄。
|
||||
private final class ConnectionContext {
|
||||
let id = UUID()
|
||||
let connection: NWConnection
|
||||
var requestBytes = Data()
|
||||
var file: FileHandle?
|
||||
var timeout: DispatchWorkItem?
|
||||
var isDownload = false
|
||||
var isWholeFile = false
|
||||
var responseBytes: Int64 = 0
|
||||
var sentBytes: Int64 = 0
|
||||
var lastProgressTime: UInt64 = 0
|
||||
init(connection: NWConnection) { self.connection = connection }
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import Foundation
|
||||
import Photos
|
||||
|
||||
/// 本地 Photos 分块读取边界;实现必须允许回调同步发生,并支持跨线程取消。
|
||||
protocol DroneDockNearbyVideoResourceRequesting: AnyObject, Sendable {
|
||||
/// 开始读取,数据和完成回调可以在任意线程或方法返回前到达。
|
||||
func requestData(onData: @escaping @Sendable (Data) -> Void,
|
||||
onComplete: @escaping @Sendable (Error?) -> Void) -> PHAssetResourceDataRequestID
|
||||
/// 停止已分配身份的读取请求。
|
||||
func cancelDataRequest(_ id: PHAssetResourceDataRequestID)
|
||||
}
|
||||
|
||||
/// 将 Photos 数据流写入独占文件;取消或超限立即关闭并删除未完成文件。
|
||||
enum DroneDockNearbyVideoResourceWriter {
|
||||
/// 创建禁止 iCloud 下载的参数;没有网络回退路径。
|
||||
static func localResourceOptions() -> PHAssetResourceRequestOptions {
|
||||
let options = PHAssetResourceRequestOptions()
|
||||
options.isNetworkAccessAllowed = false
|
||||
return options
|
||||
}
|
||||
|
||||
/// 从 Photos 导出本地资源,执行与成片选择一致的单文件大小上限。
|
||||
static func write(resource: PHAssetResource, to url: URL) async throws {
|
||||
try await write(requester: PhotosNearbyVideoRequester(resource: resource), to: url,
|
||||
maximumByteCount: Int64(DroneDockFilmPolicy.maximumFileSize))
|
||||
}
|
||||
|
||||
/// 注入数据流以验证取消竞争、超限和失败清理;只保留完整成功的文件。
|
||||
static func write(requester: any DroneDockNearbyVideoResourceRequesting, to url: URL,
|
||||
maximumByteCount: Int64) async throws {
|
||||
let operation = try NearbyVideoWriteOperation(requester: requester, url: url, maximumByteCount: maximumByteCount)
|
||||
try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { continuation in operation.start(continuation) }
|
||||
} onCancel: {
|
||||
operation.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Photos 的线程安全系统入口适配;资源和管理器在建立后不再变化。
|
||||
private final class PhotosNearbyVideoRequester: DroneDockNearbyVideoResourceRequesting, @unchecked Sendable {
|
||||
private let resource: PHAssetResource
|
||||
private let manager: PHAssetResourceManager
|
||||
|
||||
init(resource: PHAssetResource, manager: PHAssetResourceManager = .default()) {
|
||||
self.resource = resource
|
||||
self.manager = manager
|
||||
}
|
||||
|
||||
func requestData(onData: @escaping @Sendable (Data) -> Void,
|
||||
onComplete: @escaping @Sendable (Error?) -> Void) -> PHAssetResourceDataRequestID {
|
||||
manager.requestData(for: resource, options: DroneDockNearbyVideoResourceWriter.localResourceOptions(),
|
||||
dataReceivedHandler: onData, completionHandler: onComplete)
|
||||
}
|
||||
|
||||
func cancelDataRequest(_ id: PHAssetResourceDataRequestID) { manager.cancelDataRequest(id) }
|
||||
}
|
||||
|
||||
/// 同一锁串行保护句柄、完成结果和请求身份,系统回调永远只恢复 continuation 一次。
|
||||
private final class NearbyVideoWriteOperation: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private let requester: any DroneDockNearbyVideoResourceRequesting
|
||||
private let url: URL
|
||||
private let maximumByteCount: Int64
|
||||
private var handle: FileHandle?
|
||||
private var byteCount: Int64 = 0
|
||||
private var requestID: PHAssetResourceDataRequestID?
|
||||
private var continuation: CheckedContinuation<Void, Error>?
|
||||
private var result: Result<Void, Error>?
|
||||
private var needsRequestCancellation = false
|
||||
|
||||
init(requester: any DroneDockNearbyVideoResourceRequesting, url: URL, maximumByteCount: Int64) throws {
|
||||
guard url.isFileURL, maximumByteCount > 0 else { throw DroneDockFilmError.invalidLocalFile }
|
||||
guard !FileManager.default.fileExists(atPath: url.path) else { throw CocoaError(.fileWriteFileExists) }
|
||||
guard FileManager.default.createFile(atPath: url.path, contents: nil) else { throw CocoaError(.fileWriteUnknown) }
|
||||
do { handle = try FileHandle(forWritingTo: url) }
|
||||
catch { try? FileManager.default.removeItem(at: url); throw error }
|
||||
self.requester = requester
|
||||
self.url = url
|
||||
self.maximumByteCount = maximumByteCount
|
||||
}
|
||||
|
||||
func start(_ continuation: CheckedContinuation<Void, Error>) {
|
||||
lock.lock()
|
||||
if let result {
|
||||
lock.unlock()
|
||||
continuation.resume(with: result)
|
||||
return
|
||||
}
|
||||
self.continuation = continuation
|
||||
lock.unlock()
|
||||
|
||||
let id = requester.requestData(onData: { [weak self] data in self?.receive(data) }, onComplete: { [weak self] error in
|
||||
if let error { self?.finish(.failure(error), cancelRequest: false) }
|
||||
else { self?.finish(.success(()), cancelRequest: false) }
|
||||
})
|
||||
lock.lock()
|
||||
requestID = id
|
||||
let shouldCancel = needsRequestCancellation
|
||||
lock.unlock()
|
||||
// 取消和同步错误回调可能先于 requestData 返回,等拿到身份后补发取消。
|
||||
if shouldCancel { requester.cancelDataRequest(id) }
|
||||
}
|
||||
|
||||
func cancel() { finish(.failure(CancellationError()), cancelRequest: true) }
|
||||
|
||||
private func receive(_ data: Data) {
|
||||
lock.lock()
|
||||
guard result == nil else { lock.unlock(); return }
|
||||
guard Int64(data.count) <= maximumByteCount - byteCount else {
|
||||
let completion = finishLocked(.failure(DroneDockFilmError.fileTooLarge), cancelRequest: true)
|
||||
lock.unlock()
|
||||
completion?()
|
||||
return
|
||||
}
|
||||
do {
|
||||
try handle?.write(contentsOf: data)
|
||||
byteCount += Int64(data.count)
|
||||
lock.unlock()
|
||||
} catch {
|
||||
let completion = finishLocked(.failure(error), cancelRequest: true)
|
||||
lock.unlock()
|
||||
completion?()
|
||||
}
|
||||
}
|
||||
|
||||
private func finish(_ proposedResult: Result<Void, Error>, cancelRequest: Bool) {
|
||||
lock.lock()
|
||||
let completion = finishLocked(proposedResult, cancelRequest: cancelRequest)
|
||||
lock.unlock()
|
||||
completion?()
|
||||
}
|
||||
|
||||
private func finishLocked(_ proposedResult: Result<Void, Error>, cancelRequest: Bool) -> (() -> Void)? {
|
||||
guard result == nil else { return nil }
|
||||
var resolved = proposedResult
|
||||
if case .success = resolved, byteCount == 0 { resolved = .failure(DroneDockFilmError.emptyFile) }
|
||||
do { try handle?.close() }
|
||||
catch { if case .success = resolved { resolved = .failure(error) } }
|
||||
handle = nil
|
||||
if case .failure = resolved { try? FileManager.default.removeItem(at: url) }
|
||||
result = resolved
|
||||
needsRequestCancellation = cancelRequest
|
||||
let continuation = self.continuation
|
||||
self.continuation = nil
|
||||
let id = cancelRequest ? requestID : nil
|
||||
// Photos 取消可能同步触发完成回调,不能在锁内调用。
|
||||
return { [requester] in
|
||||
if let id { requester.cancelDataRequest(id) }
|
||||
continuation?.resume(with: resolved)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import Foundation
|
||||
|
||||
/// 局域网闪传的生命周期;发送结束只表示本机完成发送,不代表游客保存到相册。
|
||||
enum DroneDockNearbyTransferPhase: Equatable, Sendable {
|
||||
case idle, starting, waiting, connected, sending, sent, interrupted, ended, failed
|
||||
}
|
||||
|
||||
/// 给页面的不可变状态快照,网络回调可以在任意线程产生。
|
||||
struct DroneDockNearbyTransferSnapshot: Equatable, Sendable {
|
||||
var video: DroneDockDeliveryVideo?
|
||||
var session: DroneDockNearbyTransferSession?
|
||||
var phase: DroneDockNearbyTransferPhase = .idle
|
||||
var bytesSent: Int64 = 0
|
||||
var totalBytes: Int64 = 0
|
||||
var message: String?
|
||||
|
||||
/// 会话存续期间禁止换片,避免游客拿到其他订单的视频。
|
||||
var isActive: Bool { phase == .starting || session != nil }
|
||||
/// 生成二维码必须由用户主动操作,结束后可以重新生成。
|
||||
var canStart: Bool { video != nil && !isActive }
|
||||
/// 在传输中不暴露换片操作。
|
||||
var canChooseVideo: Bool { !isActive }
|
||||
/// 网络发送进度,不作为接收方落盘或相册保存的凭证。
|
||||
var progress: Float {
|
||||
guard totalBytes > 0 else { return 0 }
|
||||
return min(1, max(0, Float(bytesSent) / Float(totalBytes)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理单视频的本地传输会话;锁保护快照与代次,不依赖 UIKit 或隐式主线程。
|
||||
final class DroneDockNearbyTransferViewModel: @unchecked Sendable {
|
||||
private let service: any DroneDockNearbyTransferServing
|
||||
private let lock = NSLock()
|
||||
private let lifecycleLock = NSLock()
|
||||
private var state = DroneDockNearbyTransferSnapshot()
|
||||
private var generation = UUID()
|
||||
private var updateHandler: (@Sendable (DroneDockNearbyTransferSnapshot) -> Void)?
|
||||
private var startTask: Task<DroneDockNearbyTransferSession, Error>?
|
||||
|
||||
/// 注入只在本地监听的服务,测试可以替换为不联网的实现。
|
||||
init(service: any DroneDockNearbyTransferServing = DroneDockNearbyTransferServer()) {
|
||||
self.service = service
|
||||
}
|
||||
|
||||
deinit { startTask?.cancel(); service.stop() }
|
||||
|
||||
/// 页面只读取副本,避免和网络线程共享可变属性。
|
||||
var snapshot: DroneDockNearbyTransferSnapshot { locked { state } }
|
||||
|
||||
/// 更新通知可能来自后台线程;View 必须主动切回主线程再渲染。
|
||||
func setUpdateHandler(_ handler: (@Sendable (DroneDockNearbyTransferSnapshot) -> Void)?) {
|
||||
locked { updateHandler = handler }
|
||||
}
|
||||
|
||||
/// 仅接收已准备好的本地视频;无效文件不覆盖原选择。
|
||||
@discardableResult
|
||||
func selectVideo(_ video: DroneDockDeliveryVideo) throws -> Bool {
|
||||
_ = try DroneDockFilmPolicy.validate(video: video)
|
||||
let changed = locked {
|
||||
guard state.canChooseVideo else { return false }
|
||||
state = DroneDockNearbyTransferSnapshot(video: video)
|
||||
return true
|
||||
}
|
||||
if changed { notify() }
|
||||
return changed
|
||||
}
|
||||
|
||||
/// 用户明确生成二维码后才开始监听,不读取订单或调用云端接口。
|
||||
func start() async {
|
||||
let request: (UUID, Task<DroneDockNearbyTransferSession, Error>)? = lifecycle {
|
||||
locked {
|
||||
guard state.canStart, let video = state.video else { return nil }
|
||||
generation = UUID()
|
||||
let requestID = generation
|
||||
state.phase = .starting
|
||||
state.message = nil
|
||||
state.bytesSent = 0
|
||||
state.totalBytes = Int64(video.fileSize)
|
||||
let task = Task<DroneDockNearbyTransferSession, Error> { [weak self] in
|
||||
guard let self else { throw CancellationError() }
|
||||
try Task.checkCancellation()
|
||||
return try await self.service.start(video: video) { [weak self] event in
|
||||
self?.receive(event, requestID: requestID)
|
||||
}
|
||||
}
|
||||
startTask = task
|
||||
return (requestID, task)
|
||||
}
|
||||
}
|
||||
guard let (requestID, task) = request else { return }
|
||||
notify()
|
||||
do {
|
||||
let session = try await withTaskCancellationHandler {
|
||||
try await task.value
|
||||
} onCancel: { [weak self] in
|
||||
self?.cancel(requestID: requestID)
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
let accepted = locked {
|
||||
guard generation == requestID, state.phase != .ended, state.phase != .failed else { return false }
|
||||
startTask = nil
|
||||
state.session = session
|
||||
if state.phase == .starting { state.phase = .waiting }
|
||||
return true
|
||||
}
|
||||
if accepted { notify() }
|
||||
} catch {
|
||||
let accepted = locked {
|
||||
guard generation == requestID else { return false }
|
||||
startTask = nil
|
||||
state.session = nil
|
||||
state.phase = error is CancellationError ? .ended : .failed
|
||||
state.message = error is CancellationError ? "本次闪传已结束" : error.localizedDescription
|
||||
return true
|
||||
}
|
||||
if accepted { notify() }
|
||||
}
|
||||
}
|
||||
|
||||
/// 结束时立即使旧事件失效;后台或离开页面均使用同一清理路径。
|
||||
func stop(message: String = "本次闪传已结束,原二维码已失效") {
|
||||
lifecycle {
|
||||
let task = locked {
|
||||
generation = UUID()
|
||||
state.session = nil
|
||||
state.phase = .ended
|
||||
state.message = message
|
||||
let task = startTask
|
||||
startTask = nil
|
||||
return task
|
||||
}
|
||||
task?.cancel()
|
||||
service.stop()
|
||||
}
|
||||
notify()
|
||||
}
|
||||
|
||||
private func cancel(requestID: UUID) {
|
||||
let cancelled = lifecycle {
|
||||
let result: (Bool, Task<DroneDockNearbyTransferSession, Error>?) = locked {
|
||||
guard generation == requestID else { return (false, nil) }
|
||||
generation = UUID()
|
||||
state.session = nil
|
||||
state.phase = .ended
|
||||
state.message = "本次闪传已结束"
|
||||
let task = startTask
|
||||
startTask = nil
|
||||
return (true, task)
|
||||
}
|
||||
guard result.0 else { return false }
|
||||
result.1?.cancel()
|
||||
service.stop()
|
||||
return true
|
||||
}
|
||||
if cancelled { notify() }
|
||||
}
|
||||
|
||||
private func receive(_ event: DroneDockNearbyTransferEvent, requestID: UUID) {
|
||||
let accepted = locked {
|
||||
guard generation == requestID, state.phase != .ended, state.phase != .failed else { return false }
|
||||
switch event {
|
||||
case .visitorConnected:
|
||||
if state.phase == .starting || state.phase == .waiting { state.phase = .connected }
|
||||
case let .sending(bytesSent, totalBytes):
|
||||
state.phase = .sending
|
||||
state.bytesSent = max(0, min(bytesSent, totalBytes))
|
||||
state.totalBytes = max(0, totalBytes)
|
||||
state.message = nil
|
||||
case .sent:
|
||||
state.phase = .sent
|
||||
state.bytesSent = state.totalBytes
|
||||
state.message = "文件已发送,请游客在浏览器中核对下载结果"
|
||||
case .partialSent:
|
||||
state.phase = .connected
|
||||
state.bytesSent = 0
|
||||
state.message = "已发送部分内容,游客可继续下载"
|
||||
case .interrupted:
|
||||
state.phase = .interrupted
|
||||
state.message = "连接中断,请游客保持连接同一 Wi-Fi,并在接收页重试下载"
|
||||
case .stopped:
|
||||
state.phase = .ended
|
||||
state.session = nil
|
||||
state.message = "本次闪传已结束,请重新生成二维码"
|
||||
case let .failed(message):
|
||||
state.phase = .failed
|
||||
state.session = nil
|
||||
state.message = message
|
||||
}
|
||||
return true
|
||||
}
|
||||
if accepted { notify() }
|
||||
}
|
||||
|
||||
private func notify() {
|
||||
let delivery = locked { (updateHandler, state) }
|
||||
delivery.0?(delivery.1)
|
||||
}
|
||||
|
||||
private func locked<T>(_ work: () -> T) -> T {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return work()
|
||||
}
|
||||
|
||||
private func lifecycle<T>(_ work: () -> T) -> T {
|
||||
lifecycleLock.lock()
|
||||
defer { lifecycleLock.unlock() }
|
||||
return work()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user