feat(drone-dock): 接入火山实时图传并保留禁飞保护
This commit is contained in:
@@ -21,7 +21,8 @@ final class DroneDockLiveAPI: DroneDockLiveServing {
|
||||
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID") }
|
||||
let value: DroneDockLiveResponse = try await client.send(APIRequest(
|
||||
method: .get, path: "/api/app/airport/live",
|
||||
queryItems: [URLQueryItem(name: "id", value: String(taskID))]
|
||||
queryItems: [URLQueryItem(name: "id", value: String(taskID))],
|
||||
logsPayload: false
|
||||
))
|
||||
guard value.orderFlightTaskID == taskID, value.task?.id == nil || value.task?.id == taskID else {
|
||||
throw APIError.decodeFailed("图传回执与当前拍摄任务不一致")
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import Foundation
|
||||
|
||||
/// 经验证的火山接收端配置;只在内存传递,禁止写入日志或持久化。
|
||||
struct DroneDockVolcLiveConfiguration: Equatable, Sendable, CustomDebugStringConvertible {
|
||||
let appID: String
|
||||
let roomID: String
|
||||
let userID: String
|
||||
let token: String
|
||||
let expiresAt: Date
|
||||
let role: String
|
||||
|
||||
/// 调试器描述中不暴露连接凭证。
|
||||
var debugDescription: String { "DroneDockVolcLiveConfiguration(<redacted>)" }
|
||||
|
||||
/// 按 2026-11-02 已确认的 volc querystring 解析;不猜测其它厂商的字段。
|
||||
static func parse(_ response: DroneDockLiveResponse, now: Date) throws -> Self {
|
||||
guard response.playable == true else {
|
||||
throw DroneDockLiveConnectionError(response.unavailableMessage.flatMap(DroneDockHomeMetric.usableText)
|
||||
?? "图传暂不可用")
|
||||
}
|
||||
guard let stream = response.play, stream.available == true else {
|
||||
throw DroneDockLiveConnectionError("图传尚未提供可用的视频流")
|
||||
}
|
||||
guard stream.urlType == "volc" else {
|
||||
throw DroneDockLiveConnectionError("暂不支持当前图传类型,请联系后台确认使用火山图传")
|
||||
}
|
||||
guard let role = stream.role, ["drone", "airport"].contains(role),
|
||||
(response.planeID ?? 0) > 0,
|
||||
DroneDockHomeMetric.usableText(response.airportSN) != nil else {
|
||||
throw DroneDockLiveConnectionError("图传设备信息不完整")
|
||||
}
|
||||
guard let query = stream.url, !query.isEmpty, query.utf8.count <= 32_768 else {
|
||||
throw DroneDockLiveConnectionError("图传连接参数不完整")
|
||||
}
|
||||
var fields: [String: String] = [:]
|
||||
// Token 中的 + 保留为 +;百分号只解码一次,避免把 %252B 错解为 +。
|
||||
for item in query.split(separator: "&", omittingEmptySubsequences: false) {
|
||||
let pair = item.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
|
||||
guard pair.count == 2, let name = String(pair[0]).removingPercentEncoding,
|
||||
let value = String(pair[1]).removingPercentEncoding,
|
||||
!name.isEmpty, fields[name] == nil else {
|
||||
throw DroneDockLiveConnectionError("图传连接参数格式错误")
|
||||
}
|
||||
fields[name] = value
|
||||
}
|
||||
func required(_ key: String) throws -> String {
|
||||
guard let value = fields[key], !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
value.rangeOfCharacter(from: .controlCharacters) == nil else {
|
||||
throw DroneDockLiveConnectionError("图传缺少必要连接参数")
|
||||
}
|
||||
return value
|
||||
}
|
||||
guard let expiry = stream.expiresAt, expiry > 0 else {
|
||||
throw DroneDockLiveConnectionError("图传缺少凭证有效期")
|
||||
}
|
||||
var effectiveExpiry = expiry
|
||||
if let value = fields["expire_time"] {
|
||||
guard let parsed = Int(value), parsed > 0 else {
|
||||
throw DroneDockLiveConnectionError("图传凭证有效期格式错误")
|
||||
}
|
||||
effectiveExpiry = min(expiry, parsed)
|
||||
}
|
||||
let expiresAt = Date(timeIntervalSince1970: TimeInterval(effectiveExpiry))
|
||||
guard expiresAt.timeIntervalSince(now) > 5 else {
|
||||
throw DroneDockLiveConnectionError("图传凭证已过期,请重新获取")
|
||||
}
|
||||
return try Self(appID: required("app_id"), roomID: required("room_id"),
|
||||
userID: required("user_id"), token: required("token"), expiresAt: expiresAt, role: role)
|
||||
}
|
||||
}
|
||||
|
||||
/// 对用户只显示不含连接串的校验原因。
|
||||
struct DroneDockLiveConnectionError: Error, LocalizedError, Equatable, Sendable {
|
||||
let message: String
|
||||
init(_ message: String) { self.message = message }
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
|
||||
/// 播放器明确回调;只有首帧到达才算已显示真实画面。
|
||||
enum DroneDockLivePlaybackEvent: Equatable, Sendable {
|
||||
case firstFrame
|
||||
case failed(String)
|
||||
case expired
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// live 文档已明确的任务与设备回执;当前合同没有可用于播放的字段。
|
||||
/// 朱工 live 回执;任务身份与播放参数分别验证,凭证不进入展示 JSON。
|
||||
struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
/// 后端回显的订单飞行任务 ID,不能用请求值补齐。
|
||||
let orderFlightTaskID: Int
|
||||
@@ -12,15 +12,20 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
let task: DroneDockShootingTaskIdentity?
|
||||
/// 已锁定机场序列号,不用于客户端选择或重新绑定设备。
|
||||
let airportSN: String?
|
||||
let planeID: Int?
|
||||
let playable: Bool?
|
||||
let unavailableMessage: String?
|
||||
let play: DroneDockLiveStream?
|
||||
/// 随接口返回的展示读数,不触发额外实时采集。
|
||||
let metrics: [DroneDockHomeMetric]
|
||||
/// 完整回执,包含尚未建模字段,不解释成播放器配置。
|
||||
/// 脱敏回执,不包含 RTC 连接串或 Token。
|
||||
let dataJSON: String
|
||||
|
||||
/// live 文档中的已知字段映射。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case orderFlightTaskID = "order_flight_task_id", airport, drone, task
|
||||
case airportSN = "airport_sn", metrics
|
||||
case planeID = "plane_id", playable, play, unavailableMessage = "unavailable_message"
|
||||
}
|
||||
|
||||
/// 任务 ID 必须明确提供;未知字段及 null 留在完整 JSON 中供后续合同核对。
|
||||
@@ -31,6 +36,10 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
drone = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .drone)
|
||||
task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task)
|
||||
airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN)
|
||||
planeID = try container.decodeIfPresent(Int.self, forKey: .planeID)
|
||||
playable = try container.decodeIfPresent(Bool.self, forKey: .playable)
|
||||
unavailableMessage = try container.decodeIfPresent(String.self, forKey: .unavailableMessage)
|
||||
play = try container.decodeIfPresent(DroneDockLiveStream.self, forKey: .play)
|
||||
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
|
||||
let raw = try DroneDockHomeJSONValue(from: decoder)
|
||||
let encoder = JSONEncoder()
|
||||
@@ -47,7 +56,10 @@ private struct DroneDockLiveJSONSnapshot: Encodable {
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
switch value {
|
||||
case .object(let value): try container.encode(value.mapValues { Self(value: $0) })
|
||||
case .object(let value):
|
||||
try container.encode(value.mapValuesWithKeys { key, value in
|
||||
Self(value: ["url", "token"].contains(key.lowercased()) ? .string("<redacted>") : value)
|
||||
})
|
||||
case .array(let value): try container.encode(value.map { Self(value: $0) })
|
||||
case .string(let value): try container.encode(value)
|
||||
case .number(let value): try container.encode(value)
|
||||
@@ -65,4 +77,29 @@ enum DroneDockLiveState: Equatable, Sendable {
|
||||
case unavailable(String)
|
||||
case failed(String)
|
||||
case localPreview(URL)
|
||||
case connecting
|
||||
case playing
|
||||
}
|
||||
|
||||
/// live 的首选流,按 url_type 选择已明确支持的播放器。
|
||||
struct DroneDockLiveStream: Decodable, Equatable, Sendable {
|
||||
let available: Bool?
|
||||
let role: String?
|
||||
let deviceSN: String?
|
||||
let urlType: String?
|
||||
let url: String?
|
||||
let expiresAt: Int?
|
||||
|
||||
/// 后端播放字段映射。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case available, role, url
|
||||
case deviceSN = "device_sn", urlType = "url_type", expiresAt = "expire_ts"
|
||||
}
|
||||
}
|
||||
|
||||
/// 只用于递归脱敏 JSON,避免字典转换时丢失字段名。
|
||||
private extension Dictionary where Key == String {
|
||||
func mapValuesWithKeys<T>(_ transform: (String, Value) throws -> T) rethrows -> [String: T] {
|
||||
try Dictionary<String, T>(uniqueKeysWithValues: map { (key, value) in (key, try transform(key, value)) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,42 @@
|
||||
import Foundation
|
||||
|
||||
/// 任务图传区域的单次请求与生命周期;正式入口不注入操作服务,模拟来源单独注入。
|
||||
/// 任务图传的单次请求与生命周期;正式图传手动开启,模拟来源单独注入。
|
||||
final class DroneDockLiveViewModel {
|
||||
/// 当前图传所属的账号、景区与门店范围。
|
||||
let context: DroneDockHomeContext
|
||||
/// 固定订单飞行任务身份。
|
||||
let taskID: Int
|
||||
/// 最近一次通过身份核对的图传回执,不用作实时播放配置。
|
||||
/// 最近一次通过身份核对的回执;播放配置还需通过独立的协议校验。
|
||||
private(set) var response: DroneDockLiveResponse?
|
||||
/// 图传区域当前可展示状态。
|
||||
private(set) var state: DroneDockLiveState
|
||||
/// 请求期间阻止重复获取,不安排定时轮询。
|
||||
private(set) var isLoading = false
|
||||
/// 仅显式正式入口允许解析设备 RTC;本地模拟即使收到参数也不连接设备。
|
||||
let allowsDevicePlayback: Bool
|
||||
/// 正式图传必须手动开启;演示入口可自动载入本地样片。
|
||||
var loadsAutomatically: Bool { !allowsDevicePlayback }
|
||||
private(set) var rtcConfiguration: DroneDockVolcLiveConfiguration?
|
||||
private(set) var playbackSessionID: UUID?
|
||||
|
||||
private let service: (any DroneDockLiveServing)?
|
||||
private let localPreviewURL: URL?
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private var generation = 0
|
||||
private var identityInvalidated = false
|
||||
private let now: @Sendable () -> Date
|
||||
|
||||
/// 本地素材仅供明确的模拟入口注入,后端 JSON 不能生成此 URL。
|
||||
init(context: DroneDockHomeContext, taskID: Int, service: (any DroneDockLiveServing)? = nil,
|
||||
localPreviewURL: URL? = nil,
|
||||
localPreviewURL: URL? = nil, allowsDevicePlayback: Bool = false,
|
||||
now: @escaping @Sendable () -> Date = { Date() },
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||
self.context = context
|
||||
self.taskID = taskID
|
||||
self.service = service
|
||||
self.localPreviewURL = localPreviewURL
|
||||
self.allowsDevicePlayback = allowsDevicePlayback
|
||||
self.now = now
|
||||
self.currentContext = currentContext
|
||||
state = service == nil ? .restricted : .idle
|
||||
}
|
||||
@@ -49,6 +59,8 @@ final class DroneDockLiveViewModel {
|
||||
case .unavailable: return "图传暂不可用"
|
||||
case .failed: return "图传加载失败"
|
||||
case .localPreview: return "本地模拟画面"
|
||||
case .connecting: return "正在连接图传"
|
||||
case .playing: return "实时图传"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,10 +68,12 @@ final class DroneDockLiveViewModel {
|
||||
var message: String {
|
||||
switch state {
|
||||
case .restricted: return "禁飞调试期间不启动设备图传"
|
||||
case .idle: return "按当前任务获取图传信息"
|
||||
case .idle: return allowsDevicePlayback ? "点击开启当前任务的实时图传" : "按当前任务获取图传信息"
|
||||
case .loading: return "请稍候"
|
||||
case .unavailable(let reason), .failed(let reason): return reason
|
||||
case .localPreview: return "仅播放本地样片,未连接无人机"
|
||||
case .connecting: return "正在等待视频画面"
|
||||
case .playing: return rtcConfiguration?.role == "airport" ? "机巢摄像头" : "无人机摄像头"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,10 +83,12 @@ final class DroneDockLiveViewModel {
|
||||
if isLoading { return "正在加载…" }
|
||||
switch state {
|
||||
case .restricted: return nil
|
||||
case .idle: return localPreviewURL == nil ? "获取图传信息" : "查看模拟图传"
|
||||
case .idle: return allowsDevicePlayback ? "开启实时图传" : (localPreviewURL == nil ? "获取图传信息" : "查看模拟图传")
|
||||
case .loading: return "正在加载…"
|
||||
case .failed, .unavailable: return "重试"
|
||||
case .localPreview: return "重新加载模拟图传"
|
||||
case .connecting: return "重新连接"
|
||||
case .playing: return "刷新图传"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +100,7 @@ final class DroneDockLiveViewModel {
|
||||
let requestGeneration = generation
|
||||
guard accepts(requestGeneration) else { return }
|
||||
isLoading = true
|
||||
if playbackURL == nil { state = .loading }
|
||||
if playbackURL == nil && rtcConfiguration == nil { state = .loading }
|
||||
onRequestStarted?()
|
||||
defer {
|
||||
if generation == requestGeneration {
|
||||
@@ -100,6 +116,18 @@ final class DroneDockLiveViewModel {
|
||||
throw APIError.decodeFailed("图传回执与当前拍摄任务不一致")
|
||||
}
|
||||
response = value
|
||||
if allowsDevicePlayback {
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
do {
|
||||
rtcConfiguration = try DroneDockVolcLiveConfiguration.parse(value, now: now())
|
||||
playbackSessionID = UUID()
|
||||
state = .connecting
|
||||
} catch {
|
||||
state = .unavailable(error.localizedDescription)
|
||||
}
|
||||
return
|
||||
}
|
||||
guard let airportSN = DroneDockHomeMetric.usableText(value.airportSN), !airportSN.isEmpty else {
|
||||
state = .unavailable("当前任务尚未返回已锁定的机场信息")
|
||||
return
|
||||
@@ -118,6 +146,8 @@ final class DroneDockLiveViewModel {
|
||||
state = .idle
|
||||
} catch {
|
||||
guard accepts(requestGeneration) else { return }
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
state = .failed(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
@@ -128,9 +158,34 @@ final class DroneDockLiveViewModel {
|
||||
generation &+= 1
|
||||
isLoading = false
|
||||
response = nil
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
state = service == nil ? .restricted : .idle
|
||||
}
|
||||
|
||||
/// 只接受当前播放器会话的事件;首帧之前不显示已连接,旧回调不能恢复画面。
|
||||
@MainActor
|
||||
func receivePlaybackEvent(_ event: DroneDockLivePlaybackEvent, sessionID: UUID) {
|
||||
guard sessionID == playbackSessionID, rtcConfiguration != nil else { return }
|
||||
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
|
||||
invalidate()
|
||||
identityInvalidated = true
|
||||
state = .failed("账号或景区已变化,请返回工作台重新进入")
|
||||
return
|
||||
}
|
||||
switch event {
|
||||
case .firstFrame: state = .playing
|
||||
case .failed(let message):
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
state = .failed(message)
|
||||
case .expired:
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
state = .unavailable("图传凭证即将或已经过期,请重新获取")
|
||||
}
|
||||
}
|
||||
|
||||
/// 只接受当前页面与当前身份下的结果,身份变化后不允许重新请求旧任务。
|
||||
@MainActor
|
||||
private func accepts(_ requestGeneration: Int) -> Bool {
|
||||
|
||||
@@ -24,6 +24,18 @@ final class DroneDockMaterialsViewModel {
|
||||
private(set) var tasksErrorMessage: String?
|
||||
/// 点位标签始终来自整单购买快照,不从当前任务推导。
|
||||
var spots: [DroneDockMaterialSpot] { detail?.spots ?? [] }
|
||||
/// 已完整读取的任务可进入状态与图传页,不因素材尚未上传而隐藏。
|
||||
var canViewRecordedTasks: Bool {
|
||||
detail != nil && !isLoading && !isLoadingTasks && detailErrorMessage == nil
|
||||
&& tasksErrorMessage == nil && !tasks.isEmpty
|
||||
}
|
||||
|
||||
/// 打开任务前重新核对账号和景区,并且只允许当前已加载订单中的任务。
|
||||
@MainActor
|
||||
func taskForViewing(id: Int) -> DroneDockMaterialTask? {
|
||||
guard acceptsSelectionContext(), canViewRecordedTasks else { return nil }
|
||||
return tasks.first { $0.id == id && $0.orderNumber == order.orderNumber }
|
||||
}
|
||||
/// 当前范围内已选择的就绪原素材,不包含独立交付成片。
|
||||
private(set) var selectedMaterialIDs: Set<DroneDockMaterialSelectionID> = []
|
||||
/// 只有完整读取成功且具备有效文件地址的原素材允许选择。
|
||||
|
||||
@@ -107,7 +107,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
return
|
||||
}
|
||||
do {
|
||||
let value = try await service.shooting(taskID: taskID, liveBattery: true)
|
||||
let value = try await service.shooting(taskID: taskID, liveBattery: false)
|
||||
guard accepts(requestGeneration) else { return }
|
||||
guard matchesIdentity(value) else {
|
||||
response = nil
|
||||
|
||||
Reference in New Issue
Block a user