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 { canLoad && state == .idle } private(set) var rtcConfiguration: DroneDockVolcLiveConfiguration? /// 同一会话的机巢与无人机配置,可增补或续期而不重启正在播放的一路。 private(set) var rtcConfigurations: [DroneDockVolcLiveConfiguration] = [] private(set) var activeRole: String? /// 只在缺一路参数或凭证临期时请求 live;普通状态刷新不触发推流请求。 var nextParameterRefreshDelay: TimeInterval? { guard allowsDevicePlayback, !identityInvalidated, !rtcConfigurations.isEmpty else { return nil } let expiryDelay = rtcConfigurations.map { $0.expiresAt.timeIntervalSince(now()) - 30 }.min() ?? 30 let discoveryDelay = rtcConfigurations.count < 2 ? Double(min(max(response?.refreshHintMS ?? 30_000, 5_000), 60_000)) / 1000 : .infinity return max(5, min(expiryDelay, discoveryDelay)) } 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, 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 ? .unavailable("当前页面未配置图传服务") : .idle } /// 有明确注入服务且身份有效时允许发起请求。 var canLoad: Bool { service != nil && !isLoading && !identityInvalidated && context.canLoad && taskID > 0 } /// 仅返回明确注入且已经过本地文件检查的模拟视频,不使用后端未定义字段。 var playbackURL: URL? { if case .localPreview(let url) = state { return url } return nil } /// 图传区域主文案,不把接口受理视为设备连接成功。 var title: String { switch state { case .idle: return "实时图传" case .loading: return "正在获取图传信息" case .unavailable: return "图传暂不可用" case .failed: return "图传加载失败" case .localPreview: return "本地模拟画面" case .connecting: return "正在连接图传" case .playing: return "实时图传" } } /// 缺失协议时说明真实限制,不给示例视频贴上实时来源。 var message: String { switch state { 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 (activeRole ?? rtcConfiguration?.role) == "airport" ? "机巢摄像头" : "无人机摄像头" } } /// 操作名称跟随当前阶段,模拟来源始终显式标记。 var actionTitle: String? { guard service != nil else { return nil } if isLoading { return allowsDevicePlayback ? nil : "正在加载…" } switch state { case .idle: return nil case .loading: return allowsDevicePlayback ? nil : "正在加载…" case .failed, .unavailable: return "重试" case .localPreview: return "重新加载模拟图传" case .connecting: return nil case .playing: return nil } } /// 发起一次图传请求,拒绝重复点击、迟到响应、身份不符及远程模拟视频来源。 @MainActor func refresh(keepingPlayback: Bool = false, onRequestStarted: (@MainActor () -> Void)? = nil) async { guard canLoad, let service else { return } generation &+= 1 let requestGeneration = generation guard accepts(requestGeneration) else { return } isLoading = true if playbackURL == nil && rtcConfiguration == nil { state = .loading } onRequestStarted?() defer { if generation == requestGeneration { isLoading = false if Task.isCancelled, state == .loading { state = .idle } } } do { let value = try await service.live(taskID: taskID) guard accepts(requestGeneration) else { return } guard value.orderFlightTaskID == taskID, value.task?.id == nil || value.task?.id == taskID, value.task?.scenicID == nil || value.task?.scenicID == context.scenicID else { clearPlayback() throw APIError.decodeFailed("图传回执与当前拍摄任务不一致") } let previousResponse = response let sameDevice = previousResponse?.planeID == value.planeID && previousResponse?.airportSN == value.airportSN if previousResponse != nil && !sameDevice { clearPlayback() } response = value if allowsDevicePlayback { do { let configurations = try DroneDockVolcLiveConfiguration.parseSources(value, now: now()) let canKeepSession = keepingPlayback && playbackSessionID != nil && sameDevice && rtcConfigurations.first?.appID == configurations.first?.appID rtcConfigurations = configurations.map { incoming in // live 每次可能生成新 user_id;补流时保留尚未临期的原入房身份,避免销毁健康房间。 guard canKeepSession, let previous = rtcConfigurations.first(where: { $0.role == incoming.role }), previous.appID == incoming.appID, previous.roomID == incoming.roomID, previous.userID != incoming.userID, previous.expiresAt.timeIntervalSince(now()) > 30 else { return incoming } return previous } rtcConfiguration = rtcConfigurations.first if !canKeepSession { activeRole = nil playbackSessionID = UUID() state = .connecting } } catch { if !keepingPlayback || rtcConfigurations.isEmpty { clearPlayback() state = .unavailable(error.localizedDescription) } } return } guard let airportSN = DroneDockHomeMetric.usableText(value.airportSN), !airportSN.isEmpty else { state = .unavailable("当前任务尚未返回已锁定的机场信息") return } if let localPreviewURL { guard localPreviewURL.isFileURL, FileManager.default.fileExists(atPath: localPreviewURL.path) else { state = .failed("本地模拟视频不可用") return } state = .localPreview(localPreviewURL) } else { state = .unavailable("暂未提供图传播放参数") } } catch is CancellationError { guard generation == requestGeneration else { return } if rtcConfigurations.isEmpty { state = .idle } } catch { guard accepts(requestGeneration) else { return } let accessDenied: Bool if case APIError.serverCode(let code, _) = error { accessDenied = code == 100098 || code == 100099 } else { accessDenied = false } if !keepingPlayback || rtcConfigurations.isEmpty || accessDenied { clearPlayback() state = .failed(error.localizedDescription) } } } /// 离页、后台或取消时作废旧请求并清除本地播放来源,不向设备发送停止指令。 @MainActor func invalidate() { if playbackSessionID != nil { DroneDockDiagnostics.event("live.stopped", taskID: taskID) } generation &+= 1 isLoading = false response = nil clearPlayback() state = service == nil ? .unavailable("当前页面未配置图传服务") : .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 } DroneDockDiagnostics.event("live.playback_event", taskID: taskID, fields: ["playback_session": sessionID.uuidString, "result": String(describing: event)]) switch event { case .firstFrame: activeRole = rtcConfiguration?.role state = .playing case .sourceChanged(let role): activeRole = role state = role == nil ? .connecting : .playing case .failed(let message): clearPlayback() state = .failed(message) case .expired: clearPlayback() state = .unavailable("图传凭证即将或已经过期,请重新获取") } } private func clearPlayback() { rtcConfiguration = nil rtcConfigurations = [] activeRole = nil playbackSessionID = nil } /// 只接受当前页面与当前身份下的结果,身份变化后不允许重新请求旧任务。 @MainActor private func accepts(_ requestGeneration: Int) -> Bool { guard generation == requestGeneration else { return false } guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else { invalidate() identityInvalidated = true state = .failed("账号或景区已变化,请返回工作台重新进入") return false } return !Task.isCancelled } }