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()
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,8 @@
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>用于面对面闪传,让同一 Wi-Fi 下的游客扫码接收本机视频</string>
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
|
||||
@@ -21,12 +21,12 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
weak var delegate: DroneDeliveryUploadViewControllerDelegate?
|
||||
|
||||
/// 页面阶段只管理展示导航,不参与上传成功或拍摄次数计算。
|
||||
private enum Phase: Equatable { case method, nearby, point, picker, queue }
|
||||
private enum Phase: Equatable { case method, point, picker, queue }
|
||||
/// 队列摘要与主体使用独立分区。
|
||||
private enum Section: Hashable { case summary, content }
|
||||
/// 每一项依靠稳定业务身份更新,选择与进度不改变 Diffable 标识。
|
||||
private enum Item: Hashable {
|
||||
case nearbyMethod, cloudMethod, nearbyMessage, point(String), video(String), upload(String), summary, empty
|
||||
case nearbyMethod, cloudMethod, point(String), video(String), upload(String), summary, empty
|
||||
}
|
||||
|
||||
private var phase: Phase
|
||||
@@ -53,6 +53,7 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
/// 返回前台或结束预览后只刷新本地状态,不自动启动暂停队列。
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.setNavigationBarHidden(true, animated: false)
|
||||
viewModel.refresh()
|
||||
if dataSource != nil { applySnapshot(animated: false) }
|
||||
}
|
||||
@@ -145,7 +146,6 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
let height: CGFloat
|
||||
switch self.phase {
|
||||
case .method: height = 88
|
||||
case .nearby: height = 170
|
||||
case .point: height = self.viewModel.points.isEmpty ? 180 : 52
|
||||
case .picker: height = 180
|
||||
case .queue: height = self.viewModel.batch?.items.isEmpty == false ? 82 : 180
|
||||
@@ -174,7 +174,7 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
case .nearbyMethod, .cloudMethod:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "method", for: indexPath) as! DroneDeliveryUploadMethodCell
|
||||
if item == .nearbyMethod {
|
||||
cell.apply(title: "面对面闪传", detail: "近距离传给游客 · 流程待确认", symbol: "wifi",
|
||||
cell.apply(title: "面对面闪传", detail: "同一 Wi-Fi 扫码接收 · 无需上传", symbol: "wifi",
|
||||
identifier: "drone.delivery.upload.method.nearby")
|
||||
} else {
|
||||
cell.apply(title: "云端上传", detail: "选择打卡点,演示上传成片", symbol: "icloud.and.arrow.up",
|
||||
@@ -215,11 +215,9 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
self.delegate?.deliveryUploadViewControllerDidRequestReview(self)
|
||||
}
|
||||
return cell
|
||||
case .nearbyMessage, .empty:
|
||||
case .empty:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: indexPath) as! DroneDeliveryUploadMessageCell
|
||||
if item == .nearbyMessage {
|
||||
cell.apply(title: "闪传流程待确认", detail: "热点连接与游客接收流程暂未接入。\n现在可以先体验云端演示上传。", symbol: "wifi")
|
||||
} else if self.phase == .point {
|
||||
if self.phase == .point {
|
||||
cell.apply(title: "暂无可交付点位", detail: "当前订单没有可用点位,请稍后重试。", symbol: "mappin.slash.circle")
|
||||
} else if self.phase == .picker {
|
||||
cell.apply(title: "暂无可选演示视频", detail: "本点位的示例视频已交付,可返回选择其他点位。", symbol: "video.slash")
|
||||
@@ -256,7 +254,6 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
let items: [Item]
|
||||
switch phase {
|
||||
case .method: items = [.nearbyMethod, .cloudMethod]
|
||||
case .nearby: items = [.nearbyMessage]
|
||||
case .point: items = viewModel.points.isEmpty ? [.empty] : viewModel.points.map { .point($0.id) }
|
||||
case .picker: items = viewModel.availableVideos.isEmpty ? [.empty] : viewModel.availableVideos.map { .video($0.id) }
|
||||
case .queue: items = uploadItems.isEmpty ? [.empty] : uploadItems.map { .upload($0.id) }
|
||||
@@ -276,9 +273,6 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
case .method:
|
||||
headerView.apply(title: "交付成片", customer: customer, detail: "请选择本次交付方式")
|
||||
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批演示交付多个作品,不影响拍摄次数", secondaryTitle: nil)
|
||||
case .nearby:
|
||||
headerView.apply(title: "面对面闪传", customer: customer, detail: "本次仅展示交付入口")
|
||||
footerView.apply(primaryTitle: "改用云端上传", enabled: true, identifier: "drone.delivery.upload.useCloud", detail: "", secondaryTitle: "返回交付方式")
|
||||
case .point:
|
||||
headerView.apply(title: "选择打卡点", customer: customer, detail: "云端上传 · 请选择本批成片对应的打卡点")
|
||||
footerView.apply(primaryTitle: "去演示相册选视频", enabled: viewModel.selectedPoint != nil && !viewModel.isUploadLocked,
|
||||
@@ -320,7 +314,6 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
private func primaryTapped() {
|
||||
switch phase {
|
||||
case .method: break
|
||||
case .nearby: openCloudFlow()
|
||||
case .point: if viewModel.selectedPoint != nil { showPhase(.picker) }
|
||||
case .picker:
|
||||
if viewModel.startUpload() { showPhase(.queue); startDemoUpload() }
|
||||
@@ -338,6 +331,25 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 演示入口也使用同一局域网页面,但必须显式选择本机视频才会开放传输。
|
||||
private func openNearbyFlow() {
|
||||
let nearby = DroneDockNearbyTransferViewController(customerTitle: "面对面交付")
|
||||
if let navigation = navigationController {
|
||||
nearby.onClose = { [weak navigation] in navigation?.popViewController(animated: true) }
|
||||
navigation.sheetPresentationController?.animateChanges {
|
||||
navigation.sheetPresentationController?.selectedDetentIdentifier = .large
|
||||
}
|
||||
navigation.setNavigationBarHidden(false, animated: true)
|
||||
navigation.pushViewController(nearby, animated: true)
|
||||
} else {
|
||||
let navigation = UINavigationController(rootViewController: nearby)
|
||||
navigation.modalPresentationStyle = .pageSheet
|
||||
navigation.sheetPresentationController?.detents = [.large()]
|
||||
nearby.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
present(navigation, animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 选择云端仅恢复原队列或进入选点,不清除批次,也不自动继续上传。
|
||||
private func openCloudFlow() {
|
||||
showPhase(viewModel.batch == nil ? .point : .queue)
|
||||
@@ -346,7 +358,7 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
private func secondaryTapped() {
|
||||
switch phase {
|
||||
case .method: break
|
||||
case .nearby, .point: showPhase(.method)
|
||||
case .point: showPhase(.method)
|
||||
case .picker: showPhase(.point)
|
||||
case .queue: finish()
|
||||
}
|
||||
@@ -402,7 +414,7 @@ extension DroneDeliveryUploadViewController: UICollectionViewDelegate {
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||
switch item {
|
||||
case .nearbyMethod: showPhase(.nearby)
|
||||
case .nearbyMethod: openNearbyFlow()
|
||||
case .cloudMethod: openCloudFlow()
|
||||
case .point(let id): viewModel.selectPoint(id: id); applySnapshot(animated: true)
|
||||
case .upload(let id):
|
||||
|
||||
@@ -13,6 +13,18 @@ enum DroneDockDeliveryEntry {
|
||||
navigation.modalPresentationStyle = .pageSheet
|
||||
navigation.onDidCloseCloud = onDidCloseCloud
|
||||
methods.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
methods.onNearbyTransfer = { [weak navigation, weak methods] in
|
||||
guard let navigation, let methods, navigation.topViewController === methods else { return }
|
||||
let nearby = DroneDockNearbyTransferViewController(customerTitle: order.touristTitle)
|
||||
nearby.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
navigation.isModalInPresentation = true
|
||||
navigation.sheetPresentationController?.animateChanges {
|
||||
navigation.sheetPresentationController?.detents = [.large()]
|
||||
navigation.sheetPresentationController?.selectedDetentIdentifier = .large
|
||||
}
|
||||
navigation.setNavigationBarHidden(false, animated: true)
|
||||
navigation.pushViewController(nearby, animated: true)
|
||||
}
|
||||
methods.onCloudUpload = { [weak navigation, weak methods] in
|
||||
guard let navigation, let methods, navigation.topViewController === methods else { return }
|
||||
let cloud = controllerFactory(order, context, taskID)
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 真实订单的交付方式弹窗,只展示方式选择并将云端交付导航交回入口。
|
||||
/// 订单的交付方式弹窗,将云端交付和局域网闪传导航交回统一入口。
|
||||
@MainActor
|
||||
final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
/// 用户选择云端上传后,由入口打开现有真实交付页。
|
||||
var onCloudUpload: (() -> Void)?
|
||||
/// 用户选择面对面闪传后,由入口打开独立本地传输页。
|
||||
var onNearbyTransfer: (() -> Void)?
|
||||
/// 用户关闭弹窗后,由入口统一结束当前模态流程。
|
||||
var onClose: (() -> Void)?
|
||||
|
||||
/// 闪传只显示未接入说明,不创建传输任务或连接设备。
|
||||
private enum Phase: Equatable { case methods, nearby }
|
||||
/// 两种交付方式与闪传说明使用独立、稳定的列表身份。
|
||||
private enum Item: Hashable { case nearby, cloud, nearbyMessage }
|
||||
/// 两种交付方式使用独立、稳定的列表身份。
|
||||
private enum Item: Hashable { case nearby, cloud }
|
||||
|
||||
private let customerTitle: String
|
||||
private let headerView = DroneDeliveryUploadHeaderView()
|
||||
private let footerView = DroneDeliveryUploadFooterView()
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Int, Item>!
|
||||
private var phase = Phase.methods
|
||||
private var hasRequestedCloud = false
|
||||
private var hasRequestedNavigation = false
|
||||
|
||||
/// 游客标题由选中的订单传入,本弹窗不读取网络或改变订单状态。
|
||||
init(customerTitle: String) {
|
||||
@@ -34,7 +33,7 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
hasRequestedCloud = false
|
||||
hasRequestedNavigation = false
|
||||
navigationController?.isModalInPresentation = false
|
||||
isModalInPresentation = false
|
||||
navigationController?.setNavigationBarHidden(true, animated: false)
|
||||
@@ -54,7 +53,6 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
collectionView.accessibilityIdentifier = "drone.delivery.method.list"
|
||||
collectionView.delegate = self
|
||||
collectionView.register(DroneDeliveryUploadMethodCell.self, forCellWithReuseIdentifier: "method")
|
||||
collectionView.register(DroneDeliveryUploadMessageCell.self, forCellWithReuseIdentifier: "message")
|
||||
[headerView, collectionView, footerView].forEach(view.addSubview)
|
||||
configureDataSource()
|
||||
applySnapshot(animated: false)
|
||||
@@ -76,7 +74,6 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
override func bindActions() {
|
||||
headerView.onCloseTap = { [weak self] in self?.onClose?() }
|
||||
footerView.onPrimaryTap = { [weak self] in self?.requestCloudUpload() }
|
||||
footerView.onSecondaryTap = { [weak self] in self?.showPhase(.methods) }
|
||||
}
|
||||
|
||||
private func configureSheet() {
|
||||
@@ -93,14 +90,13 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] _, _ in
|
||||
guard let self else { return nil }
|
||||
let height: CGFloat = self.phase == .methods ? 88 : 132
|
||||
UICollectionViewCompositionalLayout { _, _ in
|
||||
let height: CGFloat = 88
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
|
||||
let group = NSCollectionLayoutGroup.vertical(
|
||||
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: [item])
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.interGroupSpacing = self.phase == .methods ? 12 : 0
|
||||
section.interGroupSpacing = 12
|
||||
section.contentInsets = .init(top: 4, leading: 20, bottom: 4, trailing: 20)
|
||||
return section
|
||||
}
|
||||
@@ -112,16 +108,11 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
case .nearby, .cloud:
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "method", for: path) as! DroneDeliveryUploadMethodCell
|
||||
if item == .nearby {
|
||||
cell.apply(title: "面对面闪传", detail: "近距离传给游客 · 流程待确认", symbol: "wifi", identifier: "drone.delivery.method.nearby")
|
||||
cell.apply(title: "面对面闪传", detail: "同一 Wi-Fi 扫码接收 · 无需上传", symbol: "wifi", identifier: "drone.delivery.method.nearby")
|
||||
} else {
|
||||
cell.apply(title: "云端上传", detail: "选择打卡点,上传后游客可查看", symbol: "icloud.and.arrow.up", identifier: "drone.delivery.method.cloud")
|
||||
}
|
||||
return cell
|
||||
case .nearbyMessage:
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDeliveryUploadMessageCell
|
||||
cell.apply(title: "闪传流程待确认", detail: "热点连接与游客接收流程暂未接入。\n请使用云端上传交付成片。", symbol: "wifi")
|
||||
cell.accessibilityIdentifier = "drone.delivery.method.nearbyMessage"
|
||||
return cell
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,41 +121,30 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
guard dataSource != nil else { return }
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
|
||||
snapshot.appendSections([0])
|
||||
switch phase {
|
||||
case .methods:
|
||||
headerView.apply(title: "交付成片", customer: customerTitle, detail: "请选择本次交付方式")
|
||||
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批交付多个作品,不影响拍摄次数", secondaryTitle: nil)
|
||||
snapshot.appendItems([.nearby, .cloud])
|
||||
case .nearby:
|
||||
headerView.apply(title: "面对面闪传", customer: customerTitle, detail: "本次仅展示交付入口")
|
||||
footerView.apply(primaryTitle: "改用云端上传", enabled: true, identifier: "drone.delivery.method.useCloud", detail: "", secondaryTitle: "返回交付方式")
|
||||
snapshot.appendItems([.nearbyMessage])
|
||||
}
|
||||
headerView.apply(title: "交付成片", customer: customerTitle, detail: "请选择本次交付方式")
|
||||
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批交付多个作品,不影响拍摄次数", secondaryTitle: nil)
|
||||
snapshot.appendItems([.nearby, .cloud])
|
||||
dataSource.apply(snapshot, animatingDifferences: animated)
|
||||
collectionView.collectionViewLayout.invalidateLayout()
|
||||
}
|
||||
|
||||
private func showPhase(_ phase: Phase) {
|
||||
self.phase = phase
|
||||
applySnapshot(animated: true)
|
||||
collectionView.setContentOffset(.zero, animated: false)
|
||||
}
|
||||
|
||||
private func requestCloudUpload() {
|
||||
guard !hasRequestedCloud, let onCloudUpload else { return }
|
||||
hasRequestedCloud = true
|
||||
guard !hasRequestedNavigation, let onCloudUpload else { return }
|
||||
hasRequestedNavigation = true
|
||||
onCloudUpload()
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockDeliveryMethodViewController: UICollectionViewDelegate {
|
||||
/// 云端方式交回调用方,闪传方式只在当前弹窗展示待接入说明。
|
||||
/// 只在用户选择后进入对应流程,方式弹窗本身不读取网络。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath), !hasRequestedCloud else { return }
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath), !hasRequestedNavigation else { return }
|
||||
switch item {
|
||||
case .nearby: showPhase(.nearby)
|
||||
case .nearby:
|
||||
guard let onNearbyTransfer else { return }
|
||||
hasRequestedNavigation = true
|
||||
onNearbyTransfer()
|
||||
case .cloud: requestCloudUpload()
|
||||
case .nearbyMessage: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import AVKit
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 单个本地视频的局域网扫码交付页,游客无需安装 App。
|
||||
@MainActor
|
||||
final class DroneDockNearbyTransferViewController: BaseViewController {
|
||||
/// 同一页面供订单和素材库入口复用,不依赖云端交付状态。
|
||||
let viewModel: DroneDockNearbyTransferViewModel
|
||||
/// 在交付弹窗中关闭整个流程,由调用方决定如何退出。
|
||||
var onClose: (() -> Void)?
|
||||
|
||||
private let customerTitle: String
|
||||
private let videoPicker: (@MainActor () async throws -> DroneDockDeliveryVideo?)?
|
||||
private var operationTask: Task<Void, Never>?
|
||||
private var metadataTask: Task<Void, Never>?
|
||||
private var isPicking = false
|
||||
private var pickerError: String?
|
||||
private var ownedVideoURLs: Set<URL> = []
|
||||
private var displayedVideoID: UUID?
|
||||
private var durationText: String?
|
||||
private var pendingRevealSessionID: UUID?
|
||||
private var revealedSessionID: UUID?
|
||||
private var isRevealScheduled = false
|
||||
private var previousIdleTimerDisabled: Bool?
|
||||
private var previousGestureEnabled: Bool?
|
||||
private let scrollView = UIScrollView()
|
||||
private let content = UIStackView()
|
||||
private let customerLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
|
||||
private let fileLabel = DroneDockStyle.label("尚未选择视频", size: 16, weight: .semibold)
|
||||
private let fileDetailLabel = DroneDockStyle.label("选择一段已在本机的视频", size: 12, color: DroneDockStyle.secondary)
|
||||
private let chooseButton = UIButton(type: .system)
|
||||
private let previewButton = UIButton(type: .system)
|
||||
private let statusLabel = DroneDockStyle.label("准备闪传", size: 18, weight: .semibold)
|
||||
private let statusDetailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
|
||||
private let qrContainer = UIView()
|
||||
private let qrView = UIImageView()
|
||||
private let addressButton = UIButton(type: .system)
|
||||
private let expiryLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let progressView = UIProgressView(progressViewStyle: .default)
|
||||
private let progressLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let footer = UIView()
|
||||
private let primaryButton = UIButton(type: .system)
|
||||
private let footerLabel = DroneDockStyle.label("无需互联网 · 请双方保持连接同一 Wi-Fi", size: 11, color: DroneDockStyle.secondary)
|
||||
|
||||
/// 注入本地服务和测试视频选择器;默认使用禁止云端取片的本地相册选择器。
|
||||
init(customerTitle: String, viewModel: DroneDockNearbyTransferViewModel = DroneDockNearbyTransferViewModel(),
|
||||
videoPicker: (@MainActor () async throws -> DroneDockDeliveryVideo?)? = nil) {
|
||||
self.customerTitle = customerTitle
|
||||
self.viewModel = viewModel
|
||||
self.videoPicker = videoPicker
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit {
|
||||
operationTask?.cancel()
|
||||
metadataTask?.cancel()
|
||||
viewModel.setUpdateHandler(nil)
|
||||
viewModel.stop()
|
||||
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "面对面闪传"
|
||||
let back = UIBarButtonItem(title: "交付方式", style: .plain, target: self, action: #selector(backTapped))
|
||||
back.accessibilityIdentifier = "drone.nearby.back"
|
||||
navigationItem.leftBarButtonItem = back
|
||||
let close = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(closeTapped))
|
||||
close.accessibilityLabel = "关闭面对面闪传"
|
||||
close.accessibilityIdentifier = "drone.nearby.close"
|
||||
navigationItem.rightBarButtonItem = close
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = DroneDockStyle.background
|
||||
scrollView.alwaysBounceVertical = true
|
||||
scrollView.accessibilityIdentifier = "drone.nearby.content"
|
||||
content.axis = .vertical
|
||||
content.spacing = 14
|
||||
customerLabel.text = customerTitle
|
||||
customerLabel.numberOfLines = 0
|
||||
content.addArrangedSubview(customerLabel)
|
||||
let networkTitle = DroneDockStyle.label("1 连接同一 Wi-Fi", size: 15, weight: .semibold)
|
||||
let networkDetail = DroneDockStyle.label("请商家和游客连接同一 Wi-Fi。没有现场 Wi-Fi 时,可手动连接同一手机热点。", size: 13, color: DroneDockStyle.secondary)
|
||||
networkDetail.numberOfLines = 0
|
||||
content.addArrangedSubview(card([networkTitle, networkDetail]))
|
||||
let videoTitle = DroneDockStyle.label("2 选择本地视频", size: 15, weight: .semibold)
|
||||
fileLabel.numberOfLines = 2
|
||||
fileLabel.accessibilityIdentifier = "drone.nearby.fileName"
|
||||
fileDetailLabel.numberOfLines = 0
|
||||
fileDetailLabel.accessibilityIdentifier = "drone.nearby.fileDetail"
|
||||
chooseButton.setTitle("选择视频", for: .normal)
|
||||
chooseButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .semibold)
|
||||
chooseButton.accessibilityIdentifier = "drone.nearby.chooseVideo"
|
||||
previewButton.setTitle("预览", for: .normal)
|
||||
previewButton.setImage(UIImage(systemName: "play.circle"), for: .normal)
|
||||
previewButton.accessibilityIdentifier = "drone.nearby.preview"
|
||||
let videoActions = UIStackView(arrangedSubviews: [chooseButton, previewButton])
|
||||
videoActions.spacing = 18
|
||||
videoActions.distribution = .fillEqually
|
||||
videoActions.snp.makeConstraints { $0.height.equalTo(44) }
|
||||
content.addArrangedSubview(card([videoTitle, fileLabel, fileDetailLabel, videoActions]))
|
||||
let sessionTitle = DroneDockStyle.label("3 游客扫码接收", size: 15, weight: .semibold)
|
||||
statusLabel.textColor = DroneDockStyle.primary
|
||||
statusLabel.accessibilityIdentifier = "drone.nearby.status"
|
||||
statusDetailLabel.numberOfLines = 0
|
||||
statusDetailLabel.accessibilityIdentifier = "drone.nearby.statusDetail"
|
||||
qrView.contentMode = .scaleAspectFit
|
||||
qrView.accessibilityIdentifier = "drone.nearby.qr"
|
||||
qrView.isAccessibilityElement = true
|
||||
qrView.accessibilityLabel = "请游客用系统相机扫描此二维码"
|
||||
qrContainer.addSubview(qrView)
|
||||
qrContainer.snp.makeConstraints { $0.height.equalTo(212) }
|
||||
qrView.snp.makeConstraints { make in make.center.equalToSuperview(); make.size.equalTo(204) }
|
||||
addressButton.titleLabel?.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
|
||||
addressButton.titleLabel?.numberOfLines = 2
|
||||
addressButton.accessibilityIdentifier = "drone.nearby.copyAddress"
|
||||
addressButton.setTitle("复制接收地址", for: .normal)
|
||||
addressButton.snp.makeConstraints { $0.height.greaterThanOrEqualTo(44) }
|
||||
expiryLabel.textAlignment = .center
|
||||
expiryLabel.numberOfLines = 0
|
||||
expiryLabel.accessibilityIdentifier = "drone.nearby.expiry"
|
||||
progressView.progressTintColor = DroneDockStyle.primary
|
||||
progressView.accessibilityIdentifier = "drone.nearby.progress"
|
||||
progressLabel.textAlignment = .center
|
||||
progressLabel.accessibilityIdentifier = "drone.nearby.progressText"
|
||||
content.addArrangedSubview(card([sessionTitle, statusLabel, statusDetailLabel, qrContainer, addressButton, expiryLabel, progressView, progressLabel]))
|
||||
footer.backgroundColor = .white
|
||||
primaryButton.layer.cornerRadius = 12
|
||||
primaryButton.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
primaryButton.setTitleColor(DroneDockStyle.secondary, for: .disabled)
|
||||
primaryButton.accessibilityIdentifier = "drone.nearby.primary"
|
||||
footerLabel.textAlignment = .center
|
||||
footerLabel.numberOfLines = 0
|
||||
view.addSubview(scrollView)
|
||||
scrollView.addSubview(content)
|
||||
view.addSubview(footer)
|
||||
[primaryButton, footerLabel].forEach(footer.addSubview)
|
||||
render()
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
scrollView.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalTo(footer.snp.top)
|
||||
}
|
||||
content.snp.makeConstraints { make in
|
||||
make.edges.equalTo(scrollView.contentLayoutGuide).inset(16)
|
||||
make.width.equalTo(scrollView.frameLayoutGuide).offset(-32)
|
||||
}
|
||||
footer.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
|
||||
primaryButton.snp.makeConstraints { make in
|
||||
make.top.equalToSuperview().offset(12)
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
make.height.equalTo(48)
|
||||
}
|
||||
footerLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(primaryButton.snp.bottom).offset(9)
|
||||
make.leading.trailing.equalTo(primaryButton)
|
||||
make.bottom.equalTo(footer.safeAreaLayoutGuide).offset(-10)
|
||||
}
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
chooseButton.addTarget(self, action: #selector(chooseVideoTapped), for: .touchUpInside)
|
||||
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
|
||||
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||
addressButton.addTarget(self, action: #selector(copyAddressTapped), for: .touchUpInside)
|
||||
viewModel.setUpdateHandler { [weak self] _ in
|
||||
Task { @MainActor [weak self] in self?.render() }
|
||||
}
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(enteredBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.setNavigationBarHidden(false, animated: false)
|
||||
navigationController?.sheetPresentationController?.detents = [.large()]
|
||||
navigationController?.sheetPresentationController?.selectedDetentIdentifier = .large
|
||||
render()
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
if isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||||
finishForLeaving()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
scheduleReceiveCodeReveal()
|
||||
}
|
||||
|
||||
private func scheduleReceiveCodeReveal() {
|
||||
guard pendingRevealSessionID != nil, !isRevealScheduled else { return }
|
||||
isRevealScheduled = true
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self else { return }
|
||||
defer { self.isRevealScheduled = false }
|
||||
self.view.layoutIfNeeded()
|
||||
self.scrollView.layoutIfNeeded()
|
||||
self.content.layoutIfNeeded()
|
||||
self.revealReceiveCodeIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
private func revealReceiveCodeIfNeeded() {
|
||||
guard let sessionID = pendingRevealSessionID,
|
||||
viewModel.snapshot.session?.id == sessionID,
|
||||
view.window != nil, scrollView.bounds.height > 0,
|
||||
qrContainer.bounds.height > 0, expiryLabel.bounds.height > 0 else { return }
|
||||
pendingRevealSessionID = nil
|
||||
revealedSessionID = sessionID
|
||||
// 只在新接收码生成后定位一次;下载进度和游客连接事件不抢走用户的滚动位置。
|
||||
let target = qrContainer.convert(qrContainer.bounds, to: scrollView)
|
||||
.union(addressButton.convert(addressButton.bounds, to: scrollView))
|
||||
.union(expiryLabel.convert(expiryLabel.bounds, to: scrollView))
|
||||
.insetBy(dx: 0, dy: -8)
|
||||
scrollView.scrollRectToVisible(target, animated: !UIAccessibility.isReduceMotionEnabled)
|
||||
}
|
||||
|
||||
private func card(_ views: [UIView]) -> UIView {
|
||||
let container = UIView()
|
||||
DroneDockStyle.applyCard(to: container)
|
||||
let stack = UIStackView(arrangedSubviews: views)
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 10
|
||||
container.addSubview(stack)
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(16) }
|
||||
return container
|
||||
}
|
||||
|
||||
private func render() {
|
||||
guard isViewLoaded else { return }
|
||||
let state = viewModel.snapshot
|
||||
updateScreenAwake(active: state.isActive)
|
||||
navigationController?.isModalInPresentation = state.isActive || isPicking
|
||||
if state.isActive {
|
||||
if previousGestureEnabled == nil { previousGestureEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled }
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
|
||||
} else if let enabled = previousGestureEnabled {
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = enabled
|
||||
previousGestureEnabled = nil
|
||||
}
|
||||
chooseButton.isEnabled = state.canChooseVideo && !isPicking
|
||||
chooseButton.setTitle(isPicking ? "正在准备视频…" : state.video == nil ? "选择视频" : "重新选择", for: .normal)
|
||||
previewButton.isHidden = state.video == nil
|
||||
previewButton.isEnabled = !isPicking && !state.isActive
|
||||
fileLabel.text = state.video?.fileName ?? "尚未选择视频"
|
||||
if let video = state.video {
|
||||
let size = ByteCountFormatter.string(fromByteCount: Int64(video.fileSize), countStyle: .file)
|
||||
fileDetailLabel.text = [size, durationText].compactMap { $0 }.joined(separator: " · ")
|
||||
} else { fileDetailLabel.text = "选择一段已在本机的视频,仅本次闪传可访问" }
|
||||
if let pickerError { statusLabel.text = "视频准备失败"; statusDetailLabel.text = pickerError }
|
||||
else {
|
||||
switch state.phase {
|
||||
case .idle:
|
||||
statusLabel.text = "准备闪传"
|
||||
statusDetailLabel.text = "选择视频后生成二维码,游客使用系统相机扫码,在浏览器中接收。"
|
||||
case .starting:
|
||||
statusLabel.text = "正在准备接收码…"
|
||||
statusDetailLabel.text = "请保持本页打开,正在检查本地连接。"
|
||||
case .waiting:
|
||||
statusLabel.text = "等待游客扫码"
|
||||
statusDetailLabel.text = "请游客先连接同一 Wi-Fi,再用系统相机扫码。传输期间请保持本页亮屏。"
|
||||
case .connected:
|
||||
statusLabel.text = "游客已打开接收页"
|
||||
statusDetailLabel.text = state.message ?? "请游客点击“下载视频”开始接收。"
|
||||
case .sending:
|
||||
statusLabel.text = "正在发送视频"
|
||||
statusDetailLabel.text = "请保持本页亮屏,并让游客保持连接同一 Wi-Fi。"
|
||||
case .sent:
|
||||
statusLabel.text = "文件已发送"
|
||||
statusDetailLabel.text = state.message
|
||||
case .interrupted:
|
||||
statusLabel.text = "传输已中断"
|
||||
statusDetailLabel.text = state.message
|
||||
case .ended:
|
||||
statusLabel.text = "闪传已结束"
|
||||
statusDetailLabel.text = state.message
|
||||
case .failed:
|
||||
statusLabel.text = "暂时无法闪传"
|
||||
statusDetailLabel.text = state.message
|
||||
}
|
||||
}
|
||||
statusLabel.textColor = state.phase == .sent ? DroneDockStyle.success : state.phase == .failed || state.phase == .interrupted || pickerError != nil ? DroneDockStyle.warning : DroneDockStyle.primary
|
||||
let receiveURL = state.session?.url
|
||||
qrContainer.isHidden = receiveURL == nil
|
||||
addressButton.isHidden = receiveURL == nil
|
||||
expiryLabel.isHidden = receiveURL == nil
|
||||
if let receiveURL {
|
||||
if qrView.accessibilityValue != receiveURL.absoluteString {
|
||||
qrView.image = QRCodeGenerator.generateStyledQRCode(content: receiveURL.absoluteString, backgroundColor: .white, cornerRadius: 0)
|
||||
qrView.accessibilityValue = receiveURL.absoluteString
|
||||
}
|
||||
addressButton.accessibilityValue = receiveURL.absoluteString
|
||||
if let expiry = state.session?.expiresAt {
|
||||
expiryLabel.text = "接收码有效至 \(expiry.formatted(date: .omitted, time: .shortened))\n结束闪传或离开本页后失效"
|
||||
}
|
||||
} else {
|
||||
qrView.image = nil
|
||||
qrView.accessibilityValue = nil
|
||||
addressButton.accessibilityValue = nil
|
||||
}
|
||||
let hasProgress = [.sending, .sent, .interrupted].contains(state.phase)
|
||||
progressView.isHidden = !hasProgress
|
||||
progressLabel.isHidden = !hasProgress
|
||||
progressView.setProgress(state.progress, animated: state.phase == .sending)
|
||||
progressLabel.text = "已发送 \(ByteCountFormatter.string(fromByteCount: state.bytesSent, countStyle: .file)) / \(ByteCountFormatter.string(fromByteCount: state.totalBytes, countStyle: .file))"
|
||||
primaryButton.setTitle(state.isActive ? "结束闪传" : state.phase == .ended || state.phase == .failed ? "重新生成接收码" : "生成接收二维码", for: .normal)
|
||||
primaryButton.isEnabled = !isPicking && (state.isActive || state.canStart)
|
||||
primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : DroneDockStyle.border
|
||||
if let sessionID = state.session?.id, sessionID != revealedSessionID {
|
||||
pendingRevealSessionID = sessionID
|
||||
} else if state.session == nil { pendingRevealSessionID = nil }
|
||||
view.setNeedsLayout()
|
||||
scheduleReceiveCodeReveal()
|
||||
}
|
||||
|
||||
@objc private func chooseVideoTapped() {
|
||||
guard viewModel.snapshot.canChooseVideo, !isPicking else { return }
|
||||
pickerError = nil
|
||||
if let videoPicker {
|
||||
isPicking = true
|
||||
render()
|
||||
operationTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
defer { self.isPicking = false; self.render() }
|
||||
do {
|
||||
if let video = try await videoPicker() {
|
||||
guard !Task.isCancelled else { DroneDockDeliveryVideoLoader.discard(video.url); return }
|
||||
self.useVideo(video)
|
||||
}
|
||||
} catch { if !Task.isCancelled { self.pickerError = error.localizedDescription } }
|
||||
}
|
||||
} else {
|
||||
let picker = DroneDockNearbyVideoPickerViewController(onSelect: { [weak self] video in
|
||||
guard let self else { DroneDockDeliveryVideoLoader.discard(video.url); return }
|
||||
self.dismiss(animated: true)
|
||||
self.useVideo(video)
|
||||
}, onCancel: { [weak self] in self?.dismiss(animated: true) })
|
||||
present(UINavigationController(rootViewController: picker), animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func useVideo(_ video: DroneDockDeliveryVideo) {
|
||||
do {
|
||||
guard try viewModel.selectVideo(video) else { DroneDockDeliveryVideoLoader.discard(video.url); return }
|
||||
ownedVideoURLs.insert(video.url)
|
||||
let obsolete = ownedVideoURLs.filter { $0 != video.url }
|
||||
obsolete.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
ownedVideoURLs.subtract(obsolete)
|
||||
pickerError = nil
|
||||
durationText = nil
|
||||
displayedVideoID = video.id
|
||||
metadataTask?.cancel()
|
||||
metadataTask = Task { @MainActor [weak self] in
|
||||
let duration = try? await AVURLAsset(url: video.url).load(.duration)
|
||||
guard !Task.isCancelled, let self, self.displayedVideoID == video.id else { return }
|
||||
if let seconds = duration?.seconds, seconds.isFinite, seconds > 0 {
|
||||
let whole = Int(seconds.rounded())
|
||||
self.durationText = String(format: "%d:%02d", whole / 60, whole % 60)
|
||||
}
|
||||
self.render()
|
||||
}
|
||||
} catch { DroneDockDeliveryVideoLoader.discard(video.url); pickerError = error.localizedDescription }
|
||||
render()
|
||||
}
|
||||
|
||||
@objc private func primaryTapped() {
|
||||
guard !isPicking else { return }
|
||||
if viewModel.snapshot.isActive {
|
||||
confirmStop { [weak self] in
|
||||
self?.operationTask?.cancel()
|
||||
self?.viewModel.stop()
|
||||
self?.render()
|
||||
}
|
||||
} else if viewModel.snapshot.canStart {
|
||||
pickerError = nil
|
||||
operationTask = Task { [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func previewTapped() {
|
||||
guard let video = viewModel.snapshot.video, !viewModel.snapshot.isActive else { return }
|
||||
let player = AVPlayerViewController()
|
||||
player.player = AVPlayer(url: video.url)
|
||||
present(player, animated: true) { player.player?.play() }
|
||||
}
|
||||
|
||||
@objc private func copyAddressTapped() {
|
||||
guard let url = viewModel.snapshot.session?.url else { return }
|
||||
UIPasteboard.general.setItems([[UIPasteboard.typeAutomatic: url.absoluteString]], options: [.localOnly: true, .expirationDate: Date().addingTimeInterval(120)])
|
||||
let alert = UIAlertController(title: "接收地址已复制", message: "请仅分享给同一 Wi-Fi 下的游客。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "知道了", style: .default))
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
@objc private func backTapped() {
|
||||
requestExit { [weak self] in self?.navigationController?.popViewController(animated: true) }
|
||||
}
|
||||
|
||||
@objc private func closeTapped() {
|
||||
requestExit { [weak self] in
|
||||
guard let self else { return }
|
||||
if let onClose = self.onClose { onClose() }
|
||||
else { self.dismiss(animated: true) }
|
||||
}
|
||||
}
|
||||
|
||||
private func requestExit(_ exit: @escaping () -> Void) {
|
||||
guard presentedViewController == nil else { return }
|
||||
let finish = { [weak self] in self?.finishForLeaving(); exit() }
|
||||
if viewModel.snapshot.isActive { confirmStop(finish) }
|
||||
else { finish() }
|
||||
}
|
||||
|
||||
private func confirmStop(_ completion: @escaping () -> Void) {
|
||||
let alert = UIAlertController(title: "结束本次闪传?", message: "正在下载的视频会停止,原接收二维码将失效。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续闪传", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "结束闪传", style: .destructive) { _ in completion() })
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
@objc private func enteredBackground() {
|
||||
guard viewModel.snapshot.isActive else { return }
|
||||
operationTask?.cancel()
|
||||
viewModel.stop(message: "App 已离开前台,本次闪传已结束。请重新生成二维码。")
|
||||
render()
|
||||
}
|
||||
|
||||
private func finishForLeaving() {
|
||||
operationTask?.cancel()
|
||||
metadataTask?.cancel()
|
||||
viewModel.stop()
|
||||
updateScreenAwake(active: false)
|
||||
navigationController?.isModalInPresentation = false
|
||||
if let enabled = previousGestureEnabled {
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = enabled
|
||||
previousGestureEnabled = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func updateScreenAwake(active: Bool) {
|
||||
if active {
|
||||
if previousIdleTimerDisabled == nil { previousIdleTimerDisabled = UIApplication.shared.isIdleTimerDisabled }
|
||||
UIApplication.shared.isIdleTimerDisabled = true
|
||||
} else if let previous = previousIdleTimerDisabled {
|
||||
UIApplication.shared.isIdleTimerDisabled = previous
|
||||
previousIdleTimerDisabled = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
import AVFoundation
|
||||
import Photos
|
||||
import PhotosUI
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 闪传专用本地视频选择器;缩略图与视频资源均禁止从 iCloud 下载。
|
||||
@MainActor
|
||||
final class DroneDockNearbyVideoPickerViewController: BaseViewController {
|
||||
private let onSelect: (DroneDockDeliveryVideo) -> Void
|
||||
private let onCancel: () -> Void
|
||||
private let manager = PHCachingImageManager()
|
||||
private var assets: [String: PHAsset] = [:]
|
||||
private var operation: Task<Void, Never>?
|
||||
private var hasFinished = false
|
||||
private var lastAuthorizationStatus: PHAuthorizationStatus?
|
||||
private var isObservingLibrary = false
|
||||
private var needsLibraryRefresh = false
|
||||
private let messageLabel = UILabel()
|
||||
private let spinner = UIActivityIndicatorView(style: .medium)
|
||||
private let accessButton = UIButton(type: .system)
|
||||
private lazy var collection = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Int, String>!
|
||||
|
||||
/// 只返回已经复制到 App 独占临时目录的视频,由调用页负责清理。
|
||||
init(onSelect: @escaping (DroneDockDeliveryVideo) -> Void, onCancel: @escaping () -> Void) {
|
||||
self.onSelect = onSelect
|
||||
self.onCancel = onCancel
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit {
|
||||
PHPhotoLibrary.shared().unregisterChangeObserver(self)
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "选择本地视频"
|
||||
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancel))
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .systemBackground
|
||||
messageLabel.font = .systemFont(ofSize: 13)
|
||||
messageLabel.textColor = .secondaryLabel
|
||||
messageLabel.numberOfLines = 0
|
||||
messageLabel.text = "仅发送本机已有视频,不下载 iCloud 视频。首次使用请允许访问需要交付的视频。"
|
||||
collection.backgroundColor = .systemBackground
|
||||
collection.accessibilityIdentifier = "drone.nearby.picker.list"
|
||||
collection.delegate = self
|
||||
collection.register(NearbyVideoCell.self, forCellWithReuseIdentifier: "video")
|
||||
accessButton.setTitle("选择更多可访问的视频", for: .normal)
|
||||
accessButton.addTarget(self, action: #selector(manageAccess), for: .touchUpInside)
|
||||
accessButton.isHidden = true
|
||||
[messageLabel, accessButton, collection, spinner].forEach(view.addSubview)
|
||||
dataSource = UICollectionViewDiffableDataSource<Int, String>(collectionView: collection) { [weak self] list, path, id in
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "video", for: path) as! NearbyVideoCell
|
||||
if let self, let asset = self.assets[id] { cell.apply(asset: asset, manager: self.manager) }
|
||||
return cell
|
||||
}
|
||||
PHPhotoLibrary.shared().register(self)
|
||||
isObservingLibrary = true
|
||||
operation = Task { @MainActor [weak self] in
|
||||
let status = await PHPhotoLibrary.requestAuthorization(for: .readWrite)
|
||||
guard !Task.isCancelled, let self else { return }
|
||||
self.loadAssets(status: status)
|
||||
self.operation = nil
|
||||
self.applyPendingLibraryRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
messageLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide).offset(16)
|
||||
make.leading.trailing.equalToSuperview().inset(20)
|
||||
}
|
||||
accessButton.snp.makeConstraints { make in
|
||||
make.top.equalTo(messageLabel.snp.bottom).offset(8)
|
||||
make.leading.trailing.equalToSuperview().inset(20)
|
||||
make.height.equalTo(36)
|
||||
}
|
||||
collection.snp.makeConstraints { make in
|
||||
make.top.equalTo(accessButton.snp.bottom).offset(8)
|
||||
make.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide)
|
||||
}
|
||||
spinner.snp.makeConstraints { make in make.center.equalToSuperview() }
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(refreshAuthorization),
|
||||
name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
refreshAuthorization()
|
||||
}
|
||||
|
||||
override func viewDidDisappear(_ animated: Bool) {
|
||||
super.viewDidDisappear(animated)
|
||||
if isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||||
operation?.cancel()
|
||||
stopObservingLibrary()
|
||||
if !hasFinished { hasFinished = true; onCancel() }
|
||||
}
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { _, environment in
|
||||
let side = (environment.container.effectiveContentSize.width - 32) / 3
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1.0 / 3), heightDimension: .fractionalHeight(1)))
|
||||
item.contentInsets = .init(top: 2, leading: 2, bottom: 2, trailing: 2)
|
||||
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(side)), subitems: [item])
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.contentInsets = .init(top: 0, leading: 14, bottom: 20, trailing: 14)
|
||||
return section
|
||||
}
|
||||
}
|
||||
|
||||
private func loadAssets(status: PHAuthorizationStatus) {
|
||||
lastAuthorizationStatus = status
|
||||
guard status == .authorized || status == .limited else {
|
||||
assets.removeAll()
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
|
||||
snapshot.appendSections([0])
|
||||
dataSource.apply(snapshot, animatingDifferences: true)
|
||||
messageLabel.text = "请在系统设置中允许访问相册,再选择手机中的视频。"
|
||||
accessButton.isHidden = false
|
||||
accessButton.setTitle("打开相册权限设置", for: .normal)
|
||||
return
|
||||
}
|
||||
accessButton.isHidden = status != .limited
|
||||
accessButton.setTitle("选择更多可访问的视频", for: .normal)
|
||||
let options = PHFetchOptions()
|
||||
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
|
||||
let result = PHAsset.fetchAssets(with: .video, options: options)
|
||||
assets.removeAll()
|
||||
var ids: [String] = []
|
||||
result.enumerateObjects { asset, _, _ in
|
||||
self.assets[asset.localIdentifier] = asset
|
||||
ids.append(asset.localIdentifier)
|
||||
}
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
|
||||
snapshot.appendSections([0]); snapshot.appendItems(ids)
|
||||
dataSource.apply(snapshot, animatingDifferences: true)
|
||||
messageLabel.text = ids.isEmpty ? "暂无可访问的视频。请先将成片保存在本机相册,或允许访问更多视频。" : "选择一段本地成片。仅存于 iCloud 的视频不会下载;单个视频不超过 2 GB。"
|
||||
}
|
||||
|
||||
@objc private func refreshAuthorization() {
|
||||
guard !hasFinished, isViewLoaded else { return }
|
||||
let status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
|
||||
guard status != .notDetermined, status != lastAuthorizationStatus || status == .limited else { return }
|
||||
requestLibraryRefresh()
|
||||
}
|
||||
|
||||
private func requestLibraryRefresh() {
|
||||
guard !hasFinished, isViewLoaded else { return }
|
||||
needsLibraryRefresh = true
|
||||
applyPendingLibraryRefresh()
|
||||
}
|
||||
|
||||
private func applyPendingLibraryRefresh() {
|
||||
guard needsLibraryRefresh, !hasFinished, operation == nil else { return }
|
||||
needsLibraryRefresh = false
|
||||
loadAssets(status: PHPhotoLibrary.authorizationStatus(for: .readWrite))
|
||||
}
|
||||
|
||||
private func stopObservingLibrary() {
|
||||
guard isObservingLibrary else { return }
|
||||
isObservingLibrary = false
|
||||
needsLibraryRefresh = false
|
||||
PHPhotoLibrary.shared().unregisterChangeObserver(self)
|
||||
}
|
||||
|
||||
@objc private func manageAccess() {
|
||||
if PHPhotoLibrary.authorizationStatus(for: .readWrite) == .limited {
|
||||
PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: self) { [weak self] _ in
|
||||
// 完成回调可能早于 Photos 可访问资产集合更新;后续库变化通知会再次刷新。
|
||||
Task { @MainActor [weak self] in self?.requestLibraryRefresh() }
|
||||
}
|
||||
} else if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
|
||||
}
|
||||
|
||||
@objc private func cancel() {
|
||||
operation?.cancel()
|
||||
guard !hasFinished else { return }
|
||||
hasFinished = true
|
||||
stopObservingLibrary()
|
||||
onCancel()
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockNearbyVideoPickerViewController: UICollectionViewDelegate {
|
||||
/// 选择后仅请求本地资源;资源在云端时保留选择界面并显示原因。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard operation == nil, let id = dataSource.itemIdentifier(for: indexPath), let asset = assets[id] else { return }
|
||||
spinner.startAnimating()
|
||||
collection.isUserInteractionEnabled = false
|
||||
messageLabel.text = "正在准备本地视频…"
|
||||
operation = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
var failureMessage: String?
|
||||
defer {
|
||||
self.operation = nil
|
||||
self.spinner.stopAnimating()
|
||||
self.collection.isUserInteractionEnabled = true
|
||||
self.applyPendingLibraryRefresh()
|
||||
if let failureMessage, !self.hasFinished { self.messageLabel.text = failureMessage }
|
||||
}
|
||||
do {
|
||||
let video = try await DroneDockNearbyVideoLoader.load(asset: asset)
|
||||
guard !Task.isCancelled, !self.hasFinished else { DroneDockDeliveryVideoLoader.discard(video.url); return }
|
||||
self.hasFinished = true
|
||||
self.stopObservingLibrary()
|
||||
self.onSelect(video)
|
||||
} catch {
|
||||
if !Task.isCancelled { failureMessage = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockNearbyVideoPickerViewController: PHPhotoLibraryChangeObserver {
|
||||
/// Photos 回调线程不固定;只刷新本地资产元数据,导出过程中合并到结束后处理。
|
||||
nonisolated func photoLibraryDidChange(_ changeInstance: PHChange) {
|
||||
Task { @MainActor [weak self] in self?.requestLibraryRefresh() }
|
||||
}
|
||||
}
|
||||
|
||||
/// 视频网格单元,取消复用中的缩略图请求,禁止图片从云端加载。
|
||||
@MainActor
|
||||
private final class NearbyVideoCell: UICollectionViewCell {
|
||||
private let thumbnail = UIImageView()
|
||||
private let duration = UILabel()
|
||||
private var representedID: String?
|
||||
private var request: PHImageRequestID = PHInvalidImageRequestID
|
||||
private weak var manager: PHImageManager?
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
contentView.backgroundColor = .secondarySystemBackground
|
||||
contentView.layer.cornerRadius = 8
|
||||
contentView.clipsToBounds = true
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
thumbnail.clipsToBounds = true
|
||||
duration.textColor = .white
|
||||
duration.font = .monospacedDigitSystemFont(ofSize: 12, weight: .medium)
|
||||
duration.backgroundColor = UIColor.black.withAlphaComponent(0.6)
|
||||
duration.textAlignment = .center
|
||||
contentView.addSubview(thumbnail); contentView.addSubview(duration)
|
||||
thumbnail.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
duration.snp.makeConstraints { make in make.trailing.bottom.equalToSuperview().inset(4); make.width.greaterThanOrEqualTo(42); make.height.equalTo(20) }
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
if request != PHInvalidImageRequestID { manager?.cancelImageRequest(request) }
|
||||
request = PHInvalidImageRequestID; representedID = nil; thumbnail.image = nil
|
||||
}
|
||||
|
||||
/// 只读取本地缩略图,异步回调核对资产身份,避免复用串图。
|
||||
func apply(asset: PHAsset, manager: PHImageManager) {
|
||||
prepareForReuse()
|
||||
self.manager = manager
|
||||
representedID = asset.localIdentifier
|
||||
let seconds = Int(asset.duration.rounded())
|
||||
duration.text = String(format: "%d:%02d", seconds / 60, seconds % 60)
|
||||
accessibilityLabel = "视频,\(duration.text ?? "")"
|
||||
thumbnail.image = UIImage(systemName: "video")
|
||||
let options = PHImageRequestOptions()
|
||||
options.isNetworkAccessAllowed = false
|
||||
options.deliveryMode = .opportunistic
|
||||
let id = asset.localIdentifier
|
||||
request = manager.requestImage(for: asset, targetSize: CGSize(width: 300, height: 300), contentMode: .aspectFill, options: options) { [weak self] image, _ in
|
||||
Task { @MainActor in
|
||||
guard let self, self.representedID == id, let image else { return }
|
||||
self.thumbnail.image = image
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 导出本机 Photos 资源,网络访问始终关闭,不借助系统文件提供器下载云端内容。
|
||||
enum DroneDockNearbyVideoLoader {
|
||||
/// 构造明确禁用云端下载的资源参数,供资源导出及回归测试共同使用。
|
||||
static func localResourceOptions() -> PHAssetResourceRequestOptions {
|
||||
DroneDockNearbyVideoResourceWriter.localResourceOptions()
|
||||
}
|
||||
|
||||
/// 导出当前视频资源后复用成片校验和独占文件生命周期。
|
||||
@MainActor
|
||||
static func load(asset: PHAsset) async throws -> DroneDockDeliveryVideo {
|
||||
let resources = PHAssetResource.assetResources(for: asset)
|
||||
guard let resource = resources.first(where: { $0.type == .fullSizeVideo }) ?? resources.first(where: { $0.type == .video }) else { throw LocalVideoError.unavailable }
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("nearby-video-import-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let name = URL(fileURLWithPath: resource.originalFilename).lastPathComponent
|
||||
let url = directory.appendingPathComponent(name)
|
||||
try Task.checkCancellation()
|
||||
do {
|
||||
try await DroneDockNearbyVideoResourceWriter.write(resource: resource, to: url)
|
||||
} catch is CancellationError { throw CancellationError() }
|
||||
catch let error as DroneDockFilmError { throw error }
|
||||
catch { throw LocalVideoError.unavailable }
|
||||
try Task.checkCancellation()
|
||||
return try await DroneDockDeliveryVideoLoader.load(documentURL: url)
|
||||
}
|
||||
|
||||
/// 本地不可读取时明确提示,不自动退回云端获取。
|
||||
private enum LocalVideoError: LocalizedError {
|
||||
case unavailable
|
||||
var errorDescription: String? { "无法读取本地视频,视频可能仅存于 iCloud。请选取已完整保存在本机的视频。" }
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,20 @@ import UIKit
|
||||
enum DroneDockPreview {
|
||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
if arguments.contains("--dock-nearby-preview") {
|
||||
if arguments.contains("--dock-nearby-library") {
|
||||
return UINavigationController(rootViewController: DroneDockNearbyTransferViewController(
|
||||
customerTitle: "本地相册测试 · 非游客订单"))
|
||||
}
|
||||
let nearby = DroneDockNearbyTransferViewController(customerTitle: "本地测试视频 · 非游客订单", videoPicker: {
|
||||
guard let source = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
|
||||
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock") else {
|
||||
throw DroneDockFilmError.invalidLocalFile
|
||||
}
|
||||
return try await DroneDockDeliveryVideoLoader.load(documentURL: source)
|
||||
})
|
||||
return UINavigationController(rootViewController: nearby)
|
||||
}
|
||||
if let materials = DroneDockMaterialsSimulation.makeController(arguments: arguments) {
|
||||
return UINavigationController(rootViewController: materials)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user