feat: 完善机巢模拟调试与素材交付交互
增加禁飞期间的设备指令拦截及本地模拟拍摄流程;适配订单素材库和景区空境库,完善素材筛选、预览与下载;订单交付入口改为方式选择弹窗并复用云端上传。补充单元测试、接口记录和模拟器截图。
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
|
||||
/// 朱工开始拍摄服务,只使用已创建并召唤的订单飞行任务身份。
|
||||
protocol DroneDockStartShooting: Sendable {
|
||||
/// 提交一次开拍请求;调用方负责校验执行门禁并阻止重复提交。
|
||||
@MainActor
|
||||
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse
|
||||
}
|
||||
|
||||
/// start-shoot 合同适配;禁飞期间真实传输仍由统一客户端阻断,仅用 Mock 验证。
|
||||
@MainActor
|
||||
final class DroneDockStartShootAPI: DroneDockStartShooting {
|
||||
private let client: APIClient
|
||||
|
||||
/// 注入统一客户端,测试使用不会联网的本地模拟传输。
|
||||
init(client: APIClient) { self.client = client }
|
||||
|
||||
/// 仅 POST 任务 ID,不附带飞机、航线或未约定的模拟参数,也不自动重试。
|
||||
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse {
|
||||
try Task.checkCancellation()
|
||||
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请返回任务页确认") }
|
||||
let response: DroneDockStartShootResponse = try await client.send(APIRequest(
|
||||
method: .post, path: "/api/app/airport/start-shoot", body: StartShootBody(taskID: taskID)
|
||||
))
|
||||
guard let returnedID = response.orderFlightTaskID, returnedID > 0, returnedID == taskID,
|
||||
response.orderFlightTask?.id == nil || response.orderFlightTask?.id == taskID else {
|
||||
throw APIError.decodeFailed("开始拍摄回执的任务身份缺失或不一致,请核对原任务状态")
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
/// 开拍只提交订单飞行任务身份,不使用航线任务 ID。
|
||||
private struct StartShootBody: Encodable {
|
||||
let taskID: Int
|
||||
|
||||
/// 朱工开拍请求的 JSON 字段。
|
||||
private enum CodingKeys: String, CodingKey { case taskID = "id" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
/// 原素材的选择身份;文件 ID 只在所属任务内唯一,成片不计入原素材选择。
|
||||
struct DroneDockMaterialSelectionID: Hashable, Sendable {
|
||||
/// 所属订单飞行任务。
|
||||
let taskID: Int
|
||||
/// 任务中的原素材 ID。
|
||||
let fileID: Int
|
||||
}
|
||||
@@ -22,7 +22,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
|
||||
let metrics: [DroneDockHomeMetric]
|
||||
/// 景区设备连接与轮询建议,不在客户端改选推荐飞机。
|
||||
let planeStatus: DroneDockShootingPlaneStatus?
|
||||
/// 服务端执行门禁只用于展示,本次接入不执行其动作。
|
||||
/// 执行门禁参与展示及本地模拟开拍校验,不能解除真实飞控禁令。
|
||||
let executeGate: DroneDockShootingExecuteGate?
|
||||
/// 服务端拍摄阶段和页面提示。
|
||||
let ui: DroneDockShootingUI?
|
||||
@@ -169,7 +169,7 @@ struct DroneDockShootingExecuteGate: Decodable, Equatable, Sendable {
|
||||
let code: String?
|
||||
/// 服务端门禁说明。
|
||||
let message: String?
|
||||
/// 服务端建议动作,本阶段仅展示。
|
||||
/// 服务端建议动作;本地模拟开拍要求明确为 start_shoot。
|
||||
let primaryAction: String?
|
||||
/// 服务端建议动作名称。
|
||||
let primaryActionLabel: String?
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import Foundation
|
||||
|
||||
/// start-shoot 的受理回执;不凭请求成功推断飞行、拍摄或素材已完成。
|
||||
struct DroneDockStartShootResponse: Decodable, Equatable, Sendable {
|
||||
/// 文档约定的订单飞行任务 ID,API 必须核对其与请求一致。
|
||||
let orderFlightTaskID: Int?
|
||||
/// 服务端提供的任务摘要,嵌套身份存在时同样参与核对。
|
||||
let orderFlightTask: DroneDockShootingTaskIdentity?
|
||||
/// 当前任务锁定的飞机,不由客户端选择或覆盖。
|
||||
let planeID: Int?
|
||||
/// 服务端任务 UUID,用于后续核对,不等于订单飞行任务 ID。
|
||||
let taskUUID: String?
|
||||
/// 服务端返回的机场标识,仅保留已有值。
|
||||
let airportSN: String?
|
||||
/// 服务端受理后的阶段文案,最新设备状态由 shooting 单次回查确认。
|
||||
let ui: DroneDockShootingUI?
|
||||
/// 完整 data 的格式化 JSON,保留未知字段与原始类型供模拟联调展示。
|
||||
let dataJSON: String
|
||||
|
||||
/// 朱工开拍回执字段映射。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case orderFlightTaskID = "order_flight_task_id", orderFlightTask = "order_flight_task"
|
||||
case planeID = "plane_id", taskUUID = "task_uuid", airportSN = "airport_sn", ui
|
||||
}
|
||||
|
||||
/// 仅解析响应实际提供的字段,不补造任务身份或成功状态。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID)
|
||||
orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask)
|
||||
planeID = try container.decodeIfPresent(Int.self, forKey: .planeID)
|
||||
taskUUID = try container.decodeIfPresent(String.self, forKey: .taskUUID)
|
||||
airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN)
|
||||
ui = try container.decodeIfPresent(DroneDockShootingUI.self, forKey: .ui)
|
||||
let raw = try DroneDockHomeJSONValue(from: decoder)
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
|
||||
dataJSON = String(decoding: try encoder.encode(DroneDockStartShootJSONSnapshot(value: raw)), as: UTF8.self)
|
||||
}
|
||||
}
|
||||
|
||||
/// 将已有 JSON 值完整格式化,不给模拟响应添加后端未提供的字段。
|
||||
private struct DroneDockStartShootJSONSnapshot: Encodable {
|
||||
let value: DroneDockHomeJSONValue
|
||||
|
||||
/// 保留字符串、数字、布尔、空值和嵌套对象,不追加业务码包裹。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
switch value {
|
||||
case .object(let object): try container.encode(object.mapValues { DroneDockStartShootJSONSnapshot(value: $0) })
|
||||
case .array(let array): try container.encode(array.map { DroneDockStartShootJSONSnapshot(value: $0) })
|
||||
case .string(let text): try container.encode(text)
|
||||
case .number(let number): try container.encode(number)
|
||||
case .bool(let flag): try container.encode(flag)
|
||||
case .null: try container.encodeNil()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,11 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
|
||||
case readError
|
||||
}
|
||||
|
||||
/// 任务状态区可呈现的动作;开始与恢复在本轮仅禁用展示,不发送飞控。
|
||||
/// 任务状态区可呈现的动作;开始仅在明确注入本地模拟服务时可用,真实飞控保持禁用。
|
||||
enum DroneDockTaskDisplayAction: Equatable, Sendable {
|
||||
/// 重新读取同一任务。
|
||||
case refresh
|
||||
/// 开始拍摄占位动作,本轮禁用。
|
||||
/// 开始拍摄动作;真实入口无服务,只有本地模拟可提交验证。
|
||||
case start
|
||||
/// 恢复拍摄占位动作,本轮禁用。
|
||||
case resume
|
||||
@@ -56,7 +56,7 @@ struct DroneDockTaskPresentation: Equatable, Sendable {
|
||||
let action: DroneDockTaskDisplayAction
|
||||
/// 主动作名称,无动作时为 nil。
|
||||
let actionTitle: String?
|
||||
/// 是否可触发动作;未对接的开始、恢复和重新召唤始终为 false。
|
||||
/// 是否可触发动作;真实开始、恢复和重新召唤保持禁用。
|
||||
let isActionEnabled: Bool
|
||||
/// 主动作下方的真实设备限制说明,未提供时不展示。
|
||||
let actionNote: String?
|
||||
|
||||
@@ -24,6 +24,25 @@ final class DroneDockMaterialsViewModel {
|
||||
private(set) var tasksErrorMessage: String?
|
||||
/// 点位标签始终来自整单购买快照,不从当前任务推导。
|
||||
var spots: [DroneDockMaterialSpot] { detail?.spots ?? [] }
|
||||
/// 当前范围内已选择的就绪原素材,不包含独立交付成片。
|
||||
private(set) var selectedMaterialIDs: Set<DroneDockMaterialSelectionID> = []
|
||||
/// 只有完整读取成功且具备有效文件地址的原素材允许选择。
|
||||
var selectableMaterialIDs: Set<DroneDockMaterialSelectionID> {
|
||||
guard detail != nil, !isLoading, !isLoadingTasks,
|
||||
detailErrorMessage == nil, tasksErrorMessage == nil else { return [] }
|
||||
return Set(tasks.flatMap { task in
|
||||
task.materials.filter { $0.previewURL != nil }.map {
|
||||
DroneDockMaterialSelectionID(taskID: task.id, fileID: $0.id)
|
||||
}
|
||||
})
|
||||
}
|
||||
/// 当前选择数量仅用于界面展示,不表示已经下载或保存。
|
||||
var selectedCount: Int { selectedMaterialIDs.count }
|
||||
/// 空列表不展示全选;全部当前可用原素材被选中时才标记全选。
|
||||
var allDownloadableSelected: Bool {
|
||||
let selectable = selectableMaterialIDs
|
||||
return !selectable.isEmpty && selectedMaterialIDs == selectable
|
||||
}
|
||||
|
||||
private let service: any DroneDockMaterialsServing
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
@@ -39,6 +58,38 @@ final class DroneDockMaterialsViewModel {
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 勾选只修改本地状态;无效、未就绪或其他任务的素材不会进入选择集合。
|
||||
@MainActor
|
||||
func toggleSelection(taskID: Int, fileID: Int) {
|
||||
guard acceptsSelectionContext() else { return }
|
||||
let identifier = DroneDockMaterialSelectionID(taskID: taskID, fileID: fileID)
|
||||
guard selectableMaterialIDs.contains(identifier) else { return }
|
||||
if selectedMaterialIDs.contains(identifier) {
|
||||
selectedMaterialIDs.remove(identifier)
|
||||
} else {
|
||||
selectedMaterialIDs.insert(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// 全选仅覆盖当前点位可用的原素材,不跨点位、订单或成片扩大范围。
|
||||
@MainActor
|
||||
func toggleSelectAll() {
|
||||
guard acceptsSelectionContext() else { return }
|
||||
let selectable = selectableMaterialIDs
|
||||
guard !selectable.isEmpty else { return }
|
||||
selectedMaterialIDs = selectedMaterialIDs == selectable ? [] : selectable
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func acceptsSelectionContext() -> Bool {
|
||||
guard context.hasSameIdentity(as: currentContext()) else {
|
||||
invalidate()
|
||||
detailErrorMessage = "账号或景区已变化,请返回工作台重新进入"
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// 先刷新整单摘要,再读取任务;保留仍在购买快照中的点位筛选。
|
||||
@MainActor
|
||||
func refresh() async {
|
||||
@@ -156,6 +207,7 @@ final class DroneDockMaterialsViewModel {
|
||||
@MainActor
|
||||
private func clearTasks() {
|
||||
tasks = []
|
||||
selectedMaterialIDs = []
|
||||
total = nil
|
||||
tasksErrorMessage = nil
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ final class DroneDockPreparationViewModel {
|
||||
private let planeStatusService: any DroneDockPlaneStatusServing
|
||||
private let taskCreationService: any DroneDockTaskCreating
|
||||
private let shootService: any DroneDockShootServing
|
||||
private let allowsTaskSubmission: Bool
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private var generation = 0
|
||||
private var planeStatusGeneration = 0
|
||||
@@ -62,6 +63,7 @@ final class DroneDockPreparationViewModel {
|
||||
planeStatusService: any DroneDockPlaneStatusServing,
|
||||
taskCreationService: any DroneDockTaskCreating,
|
||||
shootService: any DroneDockShootServing,
|
||||
allowsTaskSubmission: Bool = true,
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||
self.context = context
|
||||
self.order = order
|
||||
@@ -69,12 +71,13 @@ final class DroneDockPreparationViewModel {
|
||||
self.planeStatusService = planeStatusService
|
||||
self.taskCreationService = taskCreationService
|
||||
self.shootService = shootService
|
||||
self.allowsTaskSubmission = allowsTaskSubmission
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。
|
||||
var canCreateTask: Bool {
|
||||
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
|
||||
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
|
||||
!hasCreatedTask, !taskCreationOutcomeUnknown, errorMessage == nil,
|
||||
let info = projectInfo, info.order.canCreateTask == true,
|
||||
let total = info.order.shotTotal, total > 0,
|
||||
@@ -86,6 +89,9 @@ final class DroneDockPreparationViewModel {
|
||||
return info.order.orderNumber == number && info.order.projectID == projectID
|
||||
}
|
||||
|
||||
/// 当前入口是否被禁飞限制禁止提交,用于提供独立模拟入口而不放开真实写入。
|
||||
var isTaskSubmissionBlocked: Bool { !allowsTaskSubmission }
|
||||
|
||||
/// 提交中和已有回执/不确定结果时冻结点位航线,避免显示与任务归属不一致。
|
||||
var isTaskSelectionLocked: Bool {
|
||||
isCreatingTask || isSummoning || isPerformingPrimaryAction || hasCreatedTask || taskCreationOutcomeUnknown
|
||||
@@ -107,7 +113,7 @@ final class DroneDockPreparationViewModel {
|
||||
|
||||
/// 首次允许创建再召唤;明确业务拒绝后可对同任务重试,成功和未知结果锁定。
|
||||
var isPrimaryActionEnabled: Bool {
|
||||
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
|
||||
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
|
||||
!isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown,
|
||||
!hasSubmittedSummon, !summonOutcomeUnknown else { return false }
|
||||
if let createdTask { return createdTask.taskID > 0 }
|
||||
@@ -117,7 +123,8 @@ final class DroneDockPreparationViewModel {
|
||||
/// 主按钮串接创建与召唤;已有任务跳过创建,成功后的导航由页面处理。
|
||||
@MainActor
|
||||
func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
||||
guard isPrimaryActionEnabled else { return }
|
||||
// 禁飞调试在整条链开始前阻断,避免先残留真实待飞任务再拦截召唤。
|
||||
guard allowsTaskSubmission, isPrimaryActionEnabled else { return }
|
||||
primaryActionGeneration &+= 1
|
||||
let actionGeneration = primaryActionGeneration
|
||||
isPerformingPrimaryAction = true
|
||||
@@ -136,7 +143,7 @@ final class DroneDockPreparationViewModel {
|
||||
/// 对明确创建成功的任务发送一次召唤;只有明确业务拒绝允许之后再次提交。
|
||||
@MainActor
|
||||
private func summonCreatedTask(onStateChange: @escaping @MainActor () -> Void) async {
|
||||
guard !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown,
|
||||
guard allowsTaskSubmission, !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown,
|
||||
!hasSubmittedSummon, !summonOutcomeUnknown,
|
||||
let taskID = createdTask?.taskID, taskID > 0 else { return }
|
||||
summonGeneration &+= 1
|
||||
@@ -162,8 +169,13 @@ final class DroneDockPreparationViewModel {
|
||||
hasSubmittedSummon = true
|
||||
summonOutcomeUnknown = false
|
||||
} catch {
|
||||
if error is DeviceCommandDebugBlockedError, summonGeneration == requestGeneration {
|
||||
didSendSummon = false
|
||||
}
|
||||
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
|
||||
if case APIError.serverCode = error {
|
||||
if error is DeviceCommandDebugBlockedError {
|
||||
shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage
|
||||
} else if case APIError.serverCode = error {
|
||||
shootErrorMessage = error.localizedDescription
|
||||
} else {
|
||||
markSummonUnknown(reason: error.localizedDescription)
|
||||
@@ -189,7 +201,7 @@ final class DroneDockPreparationViewModel {
|
||||
/// 点击后先校验最新购买配置,再发送一次创建请求;成功留在准备页供核对。
|
||||
@MainActor
|
||||
func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
||||
guard canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID,
|
||||
guard allowsTaskSubmission, canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID,
|
||||
let number = order.orderNumber, let projectID = order.projectID else { return }
|
||||
taskCreationGeneration &+= 1
|
||||
let requestGeneration = taskCreationGeneration
|
||||
@@ -238,8 +250,13 @@ final class DroneDockPreparationViewModel {
|
||||
hasCreatedTask = true
|
||||
taskCreationOutcomeUnknown = false
|
||||
} catch {
|
||||
if error is DeviceCommandDebugBlockedError, taskCreationGeneration == requestGeneration {
|
||||
didSendTaskCreation = false
|
||||
}
|
||||
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||
if didSendTaskCreation {
|
||||
if error is DeviceCommandDebugBlockedError {
|
||||
taskCreationErrorMessage = DeviceCommandDebugPolicy.blockedMessage
|
||||
} else if didSendTaskCreation {
|
||||
if case APIError.serverCode = error {
|
||||
taskCreationErrorMessage = error.localizedDescription
|
||||
} else {
|
||||
@@ -414,6 +431,7 @@ final class DroneDockPreparationViewModel {
|
||||
if isCreatingTask { return "正在创建任务…" }
|
||||
if isSummoning { return "正在召唤无人机…" }
|
||||
if hasSubmittedSummon { return "查看拍摄任务" }
|
||||
if !allowsTaskSubmission { return "仅限模拟调试" }
|
||||
if summonOutcomeUnknown { return "召唤结果待核对" }
|
||||
if hasCreatedTask { return shootErrorMessage == nil ? "确认并召唤" : "重试召唤" }
|
||||
if taskCreationOutcomeUnknown { return "结果待核对" }
|
||||
@@ -426,6 +444,7 @@ final class DroneDockPreparationViewModel {
|
||||
if isCreatingTask { return "正在创建待飞任务,请勿重复点击" }
|
||||
if isSummoning { return "任务已创建,正在提交召唤请求" }
|
||||
if creationContextInvalidated, let errorMessage { return errorMessage }
|
||||
if !allowsTaskSubmission && !hasSubmittedSummon { return DeviceCommandDebugPolicy.blockedMessage }
|
||||
if let createdTask {
|
||||
if hasSubmittedSummon { return "任务 \(createdTask.taskID) 的召唤请求已提交,请等待任务状态更新" }
|
||||
if let shootErrorMessage { return shootErrorMessage }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// 真实拍摄任务页只读状态,只按准备页传入的既有任务 ID 读取 shooting。
|
||||
/// 拍摄任务状态及可选开拍流程,始终复用同一任务;禁飞调试仅为本地模拟注入开拍服务。
|
||||
final class DroneDockShootingTaskViewModel {
|
||||
/// 页面绑定的账号、景区和门店身份。
|
||||
let context: DroneDockHomeContext
|
||||
@@ -14,27 +14,47 @@ final class DroneDockShootingTaskViewModel {
|
||||
private(set) var isLoading = false
|
||||
/// 读取失败或身份变化时的提示。
|
||||
private(set) var errorMessage: String?
|
||||
/// 开拍提交及其后单次状态核对期间禁用重复操作,保留之前的显示快照。
|
||||
private(set) var isStartingShooting = false
|
||||
/// 开拍业务拒绝、本地拦截或结果待核对的说明。
|
||||
private(set) var startErrorMessage: String?
|
||||
/// 已发送但无法确认的开拍请求,不因后续读取仍允许开始而自动解除。
|
||||
private(set) var startOutcomeUnknown = false
|
||||
/// 当前页面是否已收到明确开拍受理回执,收到后不会再次提交。
|
||||
private(set) var hasSubmittedStart = false
|
||||
/// 同任务开拍回执;受理成功不直接替代 shooting 的完整状态快照。
|
||||
private(set) var startResponse: DroneDockStartShootResponse?
|
||||
|
||||
private let service: any DroneDockShootingServing
|
||||
private let startService: (any DroneDockStartShooting)?
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private var generation = 0
|
||||
private var identityInvalidated = false
|
||||
private var startGeneration = 0
|
||||
private var didSendStart = false
|
||||
|
||||
/// 只注入读取服务,不依赖创建、召唤、开始拍摄或控制服务。
|
||||
/// 默认只读;只有显式注入开拍服务才提供开拍动作,当前正式入口不注入该服务。
|
||||
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
|
||||
service: any DroneDockShootingServing,
|
||||
startService: (any DroneDockStartShooting)? = nil,
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||
self.context = context
|
||||
self.taskID = taskID
|
||||
self.order = order
|
||||
self.service = service
|
||||
self.startService = startService
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。
|
||||
@MainActor
|
||||
func refresh() async {
|
||||
guard !isLoading, !identityInvalidated else { return }
|
||||
await refreshSnapshot(allowWhileStarting: false)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func refreshSnapshot(allowWhileStarting: Bool) async {
|
||||
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting else { return }
|
||||
generation &+= 1
|
||||
let requestGeneration = generation
|
||||
isLoading = true
|
||||
@@ -68,11 +88,14 @@ final class DroneDockShootingTaskViewModel {
|
||||
/// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。
|
||||
@MainActor
|
||||
func invalidate(preservingSnapshot: Bool = false) {
|
||||
invalidateStartShooting()
|
||||
generation &+= 1
|
||||
isLoading = false
|
||||
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
|
||||
if identityInvalidated {
|
||||
response = nil
|
||||
startResponse = nil
|
||||
startErrorMessage = nil
|
||||
errorMessage = "账号或景区已变化,请返回工作台重新进入"
|
||||
} else {
|
||||
if !preservingSnapshot { response = nil }
|
||||
@@ -80,6 +103,83 @@ final class DroneDockShootingTaskViewModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。
|
||||
var canStartShooting: Bool {
|
||||
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
||||
&& !isLoading && !isStartingShooting && errorMessage == nil
|
||||
&& !hasSubmittedStart && !startOutcomeUnknown
|
||||
&& resolvedDisplayPhase().0 == .ready
|
||||
&& response?.executeGate?.canExecute == true
|
||||
&& response?.executeGate?.primaryAction == "start_shoot"
|
||||
&& (response?.currentPlane?.id ?? 0) > 0
|
||||
}
|
||||
|
||||
/// 提交一次开拍并单次读取同任务;失败保留原快照,不轮询、不重建、不自动重发。
|
||||
@MainActor
|
||||
func startShooting(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
||||
guard canStartShooting, let startService else { return }
|
||||
guard context.hasSameIdentity(as: currentContext()) else {
|
||||
identityInvalidated = true
|
||||
invalidate()
|
||||
onStateChange()
|
||||
return
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
let planeID = response?.currentPlane?.id
|
||||
startGeneration &+= 1
|
||||
let requestGeneration = startGeneration
|
||||
isStartingShooting = true
|
||||
didSendStart = false
|
||||
startErrorMessage = nil
|
||||
onStateChange()
|
||||
defer {
|
||||
if startGeneration == requestGeneration {
|
||||
if Task.isCancelled && didSendStart && !hasSubmittedStart { markStartUnknown() }
|
||||
isStartingShooting = false
|
||||
didSendStart = false
|
||||
onStateChange()
|
||||
}
|
||||
}
|
||||
guard acceptsStart(requestGeneration) else { return }
|
||||
do {
|
||||
didSendStart = true
|
||||
let value = try await startService.startShooting(taskID: taskID)
|
||||
guard acceptsStart(requestGeneration) else { return }
|
||||
guard value.orderFlightTaskID == taskID,
|
||||
value.orderFlightTask?.id == nil || value.orderFlightTask?.id == taskID,
|
||||
value.orderFlightTask?.orderNumber == nil || value.orderFlightTask?.orderNumber == order.orderNumber,
|
||||
value.orderFlightTask?.scenicID == nil || value.orderFlightTask?.scenicID == context.scenicID,
|
||||
value.planeID == nil || value.planeID == planeID else {
|
||||
throw APIError.decodeFailed("开始拍摄回执与当前任务或飞机不一致,请先核对任务状态")
|
||||
}
|
||||
startResponse = value
|
||||
hasSubmittedStart = true
|
||||
startOutcomeUnknown = false
|
||||
onStateChange()
|
||||
guard acceptsStart(requestGeneration) else { return }
|
||||
await refreshSnapshot(allowWhileStarting: true)
|
||||
} catch {
|
||||
if error is DeviceCommandDebugBlockedError, startGeneration == requestGeneration { didSendStart = false }
|
||||
guard acceptsStart(requestGeneration) else { return }
|
||||
if error is DeviceCommandDebugBlockedError {
|
||||
startErrorMessage = DeviceCommandDebugPolicy.blockedMessage
|
||||
} else if case APIError.serverCode = error {
|
||||
startErrorMessage = error.localizedDescription
|
||||
} else {
|
||||
markStartUnknown(reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 离页或进入后台后拒绝迟到回执;已发而未确认的请求保留待核对锁。
|
||||
@MainActor
|
||||
func invalidateStartShooting() {
|
||||
if isStartingShooting && didSendStart && !hasSubmittedStart { markStartUnknown() }
|
||||
startGeneration &+= 1
|
||||
isStartingShooting = false
|
||||
didSendStart = false
|
||||
}
|
||||
|
||||
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
|
||||
var title: String {
|
||||
if let title = usable(response?.header?.title) { return title }
|
||||
@@ -111,13 +211,18 @@ final class DroneDockShootingTaskViewModel {
|
||||
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
|
||||
}
|
||||
|
||||
/// 保留服务端阶段说明与执行门禁原因;本模块不执行门禁给出的动作。
|
||||
/// 保留服务端阶段说明;未确认的开拍结果明确提示核对,不伪装为正在拍摄。
|
||||
var statusMessage: String {
|
||||
if response == nil {
|
||||
if let errorMessage { return errorMessage }
|
||||
if isLoading { return "正在读取当前拍摄任务" }
|
||||
}
|
||||
if resolvedDisplayPhase().0 == .failed { return failureMessage }
|
||||
if startOutcomeUnknown, let startErrorMessage { return startErrorMessage }
|
||||
if resolvedDisplayPhase().0 == .ready {
|
||||
if let startErrorMessage { return startErrorMessage }
|
||||
if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" }
|
||||
}
|
||||
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
|
||||
}
|
||||
|
||||
@@ -138,10 +243,15 @@ final class DroneDockShootingTaskViewModel {
|
||||
let actionTitle: String?
|
||||
let enabled: Bool
|
||||
switch phase {
|
||||
case .ready where hasSubmittedStart || startOutcomeUnknown:
|
||||
action = .refresh
|
||||
actionTitle = "刷新状态"
|
||||
enabled = !identityInvalidated
|
||||
case .ready:
|
||||
action = .start
|
||||
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄"
|
||||
enabled = false
|
||||
actionTitle = isStartingShooting ? "正在提交开拍…"
|
||||
: startErrorMessage == nil ? (usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄") : "重试开始拍摄"
|
||||
enabled = canStartShooting
|
||||
case .paused where response?.executeGate?.canExecute == true:
|
||||
action = .resume
|
||||
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄"
|
||||
@@ -161,7 +271,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
}
|
||||
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
|
||||
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
|
||||
isActionEnabled: enabled && !isLoading && !identityInvalidated && (errorMessage == nil || action == .refresh),
|
||||
isActionEnabled: enabled && !isLoading && !isStartingShooting && !identityInvalidated && (errorMessage == nil || action == .refresh),
|
||||
actionNote: phase == .failed ? retryUnavailableNote : nil)
|
||||
}
|
||||
|
||||
@@ -189,6 +299,22 @@ final class DroneDockShootingTaskViewModel {
|
||||
return !Task.isCancelled
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func acceptsStart(_ requestGeneration: Int) -> Bool {
|
||||
guard startGeneration == requestGeneration else { return false }
|
||||
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
|
||||
identityInvalidated = true
|
||||
invalidate()
|
||||
return false
|
||||
}
|
||||
return !Task.isCancelled
|
||||
}
|
||||
|
||||
private func markStartUnknown(reason: String? = nil) {
|
||||
startOutcomeUnknown = true
|
||||
startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交"
|
||||
}
|
||||
|
||||
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
|
||||
let taskIDs = [value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
|
||||
let orderNumbers = [value.orderNumber, value.orderFlightTask?.orderNumber,
|
||||
|
||||
@@ -83,8 +83,7 @@ enum HomeRouteHandler {
|
||||
let context = ScenicMaterialContext(userID: session.userId,
|
||||
scenicID: String(session.currentScenicId),
|
||||
scenicName: session.currentScenicName)
|
||||
// 素材接口尚未接入,正式入口使用当前景区空态,避免生成预览素材。
|
||||
let viewModel = ScenicMaterialsViewModel(context: context, routes: [], groups: [])
|
||||
let viewModel = ScenicMaterialsViewModel(context: context, isRemote: true)
|
||||
viewController.navigationController?.pushViewController(ScenicMaterialsViewController(viewModel: viewModel), animated: true)
|
||||
case "checkin_points":
|
||||
viewController.navigationController?.pushViewController(PunchPointListViewController(), animated: true)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import Foundation
|
||||
|
||||
/// 景区空境库的只读场次及详情接口,素材下载不回写订单素材状态。
|
||||
protocol ScenicMaterialsServing: Sendable {
|
||||
/// 按当前景区及筛选分页读取场次。
|
||||
@MainActor
|
||||
func sessions(query: ScenicMaterialsQuery) async throws -> ScenicMaterialsSessionsResponse
|
||||
/// 使用场次身份读取完整片段信息和授权文件地址。
|
||||
@MainActor
|
||||
func sessionDetail(scenicMediaID: Int) async throws -> ScenicMaterialsSessionDetailResponse
|
||||
}
|
||||
|
||||
/// 朱工景区空境库接口,复用部署环境验证过的 token 鉴权和统一业务包。
|
||||
@MainActor
|
||||
final class ScenicMaterialsAPI: ScenicMaterialsServing {
|
||||
private let client: APIClient
|
||||
|
||||
/// 注入统一网络客户端,单元测试可使用 MockURLSession。
|
||||
init(client: APIClient) { self.client = client }
|
||||
|
||||
/// 验证请求范围及响应页码,避免拼入其他页或其他筛选的数据。
|
||||
func sessions(query: ScenicMaterialsQuery) async throws -> ScenicMaterialsSessionsResponse {
|
||||
let response: ScenicMaterialsSessionsResponse = try await client.send(APIRequest(
|
||||
method: .get, path: "/api/app/scenic-media/sessions", queryItems: try query.queryItems(), logsPayload: false
|
||||
))
|
||||
guard response.page == query.page, response.pageSize == query.pageSize,
|
||||
response.retentionDays == query.retentionDays,
|
||||
response.filter.airLineID == (query.airLineID ?? 0),
|
||||
response.filter.dateFrom == (query.dateFrom ?? ""), response.filter.dateTo == (query.dateTo ?? "") else {
|
||||
throw APIError.decodeFailed("空境库场次与当前查询条件不一致,请刷新重试")
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
/// 只传文档定义的 scenic_media_id,不传订单、任务或机巢身份。
|
||||
func sessionDetail(scenicMediaID: Int) async throws -> ScenicMaterialsSessionDetailResponse {
|
||||
guard scenicMediaID > 0 else { throw APIError.networkFailed("空境场次无效,请刷新重试") }
|
||||
return try await client.send(APIRequest(
|
||||
method: .get, path: "/api/app/scenic-media/session-detail",
|
||||
queryItems: [URLQueryItem(name: "scenic_media_id", value: String(scenicMediaID))], logsPayload: false
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import Foundation
|
||||
|
||||
/// 为月、日两列滚轮提供保留期内的真实日期,月份保留年份以正确处理跨年。
|
||||
struct ScenicMaterialDatePickerOptions {
|
||||
/// 一个月中实际可选的日期;首月和末月只包含保留期覆盖的部分。
|
||||
struct Month {
|
||||
/// 日历中的年份,供跨年识别及辅助功能使用。
|
||||
let year: Int
|
||||
/// 日历中的月份。
|
||||
let number: Int
|
||||
/// 当前月份内按先后排列且允许选择的日期。
|
||||
let dates: [Date]
|
||||
}
|
||||
|
||||
/// 包含端点、按日归一化的最早日期。
|
||||
let minimumDate: Date
|
||||
/// 包含端点、按日归一化的最晚日期。
|
||||
let maximumDate: Date
|
||||
/// 从最早到最晚排列的可选月份。
|
||||
let months: [Month]
|
||||
private let calendar: Calendar
|
||||
|
||||
/// 将闭区间展开为有限选项,不依赖每月天数或一天固定为 24 小时的假设。
|
||||
init(minimumDate: Date, maximumDate: Date, calendar: Calendar) {
|
||||
self.calendar = calendar
|
||||
let minimum = calendar.startOfDay(for: minimumDate)
|
||||
let maximum = max(minimum, calendar.startOfDay(for: maximumDate))
|
||||
self.minimumDate = minimum
|
||||
self.maximumDate = maximum
|
||||
var months: [Month] = []
|
||||
var day = minimum
|
||||
while day <= maximum {
|
||||
let year = calendar.component(.year, from: day)
|
||||
let number = calendar.component(.month, from: day)
|
||||
if let last = months.last, last.year == year, last.number == number {
|
||||
months[months.count - 1] = Month(year: year, number: number, dates: last.dates + [day])
|
||||
} else {
|
||||
months.append(Month(year: year, number: number, dates: [day]))
|
||||
}
|
||||
guard let next = calendar.date(byAdding: .day, value: 1, to: day), next > day else { break }
|
||||
day = next
|
||||
}
|
||||
self.months = months
|
||||
}
|
||||
|
||||
/// 将外部值归一到允许范围内的日历日。
|
||||
func clamped(_ date: Date) -> Date {
|
||||
min(max(calendar.startOfDay(for: date), minimumDate), maximumDate)
|
||||
}
|
||||
|
||||
/// 找到日期对应的月份行,保留期外值先收敛到边界。
|
||||
func monthIndex(for date: Date) -> Int {
|
||||
let value = clamped(date)
|
||||
return months.firstIndex { month in
|
||||
month.dates.first.map { $0 <= value } == true && month.dates.last.map { value <= $0 } == true
|
||||
} ?? 0
|
||||
}
|
||||
|
||||
/// 切换月份时尽量保留原日号;月末或截断的保留期会收敛到最近可选日。
|
||||
func date(inMonthAt index: Int, preferredDay: Int) -> Date {
|
||||
let month = months[min(max(index, 0), months.count - 1)]
|
||||
return month.dates.min {
|
||||
abs(calendar.component(.day, from: $0) - preferredDay)
|
||||
< abs(calendar.component(.day, from: $1) - preferredDay)
|
||||
} ?? minimumDate
|
||||
}
|
||||
|
||||
/// 普通范围只显示月份;范围含同名月份时补年份,避免用户混淆。
|
||||
func monthTitle(at index: Int) -> String {
|
||||
let month = months[index]
|
||||
let repeats = months.filter { $0.number == month.number }.count > 1
|
||||
return repeats ? "\(month.year)年\(month.number)月" : "\(month.number)月"
|
||||
}
|
||||
}
|
||||
@@ -70,12 +70,21 @@ struct ScenicMaterialClip: Hashable, Sendable {
|
||||
let resolution: String
|
||||
/// 本地演示封面资源名。
|
||||
let coverAssetName: String
|
||||
/// 正式素材原片地址;预览素材为空。
|
||||
let remoteURL: URL?
|
||||
/// 正式素材封面地址。
|
||||
let coverURL: URL?
|
||||
/// 后端返回的片段名称。
|
||||
let fileLabel: String?
|
||||
/// 是否来自正式接口,缺失地址时禁止回退到演示视频。
|
||||
let isRemote: Bool
|
||||
/// 文件是否仍可预览和下载;不可用文件仍可展示其元数据。
|
||||
let isAvailable: Bool
|
||||
|
||||
/// 创建片段元数据,不读取本地相册或请求网络。
|
||||
init(id: String, groupID: String, ordinal: Int, durationSeconds: Int, fileSizeBytes: Int64,
|
||||
resolution: String, coverAssetName: String, isAvailable: Bool = true) {
|
||||
resolution: String, coverAssetName: String, isAvailable: Bool = true,
|
||||
remoteURL: URL? = nil, coverURL: URL? = nil, fileLabel: String? = nil, isRemote: Bool = false) {
|
||||
self.id = id
|
||||
self.groupID = groupID
|
||||
self.ordinal = ordinal
|
||||
@@ -84,16 +93,22 @@ struct ScenicMaterialClip: Hashable, Sendable {
|
||||
self.resolution = resolution
|
||||
self.coverAssetName = coverAssetName
|
||||
self.isAvailable = isAvailable
|
||||
self.remoteURL = remoteURL
|
||||
self.coverURL = coverURL
|
||||
self.fileLabel = fileLabel
|
||||
self.isRemote = isRemote
|
||||
}
|
||||
|
||||
/// 用于封面与预览信息的分秒时长。
|
||||
var durationText: String {
|
||||
guard durationSeconds >= 0 else { return "时长未知" }
|
||||
let value = max(durationSeconds, 0)
|
||||
return String(format: "%02d:%02d", value / 60, value % 60)
|
||||
}
|
||||
|
||||
/// 使用十进制 MB 展示片段大小,避免将原文件与本地示例文件混淆。
|
||||
var sizeText: String {
|
||||
guard fileSizeBytes >= 0 else { return "大小未知" }
|
||||
let megabytes = Double(max(fileSizeBytes, 0)) / 1_000_000
|
||||
return megabytes.rounded() == megabytes ? String(format: "%.0fMB", megabytes) : String(format: "%.1fMB", megabytes)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import Foundation
|
||||
|
||||
/// 场次接口中已由部署响应确认的分页和保留策略;子项保留原始字段供合同映射使用。
|
||||
struct ScenicMaterialsSessionsResponse: Decodable, Equatable, Sendable {
|
||||
/// 当前页场次原始对象,不能把未确认的子项结构当成空列表。
|
||||
let list: [[String: ScenicMaterialsJSONValue]]
|
||||
/// 服务端航线分组原始对象。
|
||||
let groups: [[String: ScenicMaterialsJSONValue]]
|
||||
/// 当前筛选场次总数。
|
||||
let total: Int
|
||||
/// 服务端实际返回的页码。
|
||||
let page: Int
|
||||
/// 服务端实际返回的每页数量。
|
||||
let pageSize: Int
|
||||
/// 本次查询的素材保留窗口。
|
||||
let retentionDays: Int
|
||||
/// 服务端提供的保留期提示。
|
||||
let retentionTips: String
|
||||
/// 服务端实际应用的筛选。
|
||||
let filter: ScenicMaterialsFilter
|
||||
/// 当前景区可用的航线筛选对象。
|
||||
let airLines: [[String: ScenicMaterialsJSONValue]]
|
||||
|
||||
/// 部署接口的根字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case list, groups, total, page, pageSize = "page_size", retentionDays = "retention_days"
|
||||
case retentionTips = "retention_tips", filter, filterOptions = "filter_options"
|
||||
}
|
||||
|
||||
/// 只接受真实容器和有效分页,避免缺字段响应被误显示成空态。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
list = try container.decode([[String: ScenicMaterialsJSONValue]].self, forKey: .list)
|
||||
groups = try container.decode([[String: ScenicMaterialsJSONValue]].self, forKey: .groups)
|
||||
total = try container.decode(Int.self, forKey: .total)
|
||||
page = try container.decode(Int.self, forKey: .page)
|
||||
pageSize = try container.decode(Int.self, forKey: .pageSize)
|
||||
retentionDays = try container.decode(Int.self, forKey: .retentionDays)
|
||||
retentionTips = try container.decode(String.self, forKey: .retentionTips)
|
||||
filter = try container.decode(ScenicMaterialsFilter.self, forKey: .filter)
|
||||
airLines = try container.decode(ScenicMaterialsFilterOptions.self, forKey: .filterOptions).airLines
|
||||
guard total >= 0, page > 0, (1...100).contains(pageSize), (1...365).contains(retentionDays),
|
||||
list.count <= pageSize, list.count <= total else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .list, in: container, debugDescription: "空境库场次分页或保留期无效")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 后端实际应用的筛选,全部航线为 0、全部日期为空字符串。
|
||||
struct ScenicMaterialsFilter: Decodable, Equatable, Sendable {
|
||||
/// 当前航线筛选值。
|
||||
let airLineID: Int
|
||||
/// 当前起始日期筛选值。
|
||||
let dateFrom: String
|
||||
/// 当前结束日期筛选值。
|
||||
let dateTo: String
|
||||
|
||||
/// 部署响应中的筛选字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case airLineID = "air_line_id", dateFrom = "date_from", dateTo = "date_to"
|
||||
}
|
||||
}
|
||||
|
||||
/// filter_options 下独立返回当前景区的航线集合。
|
||||
private struct ScenicMaterialsFilterOptions: Decodable {
|
||||
let airLines: [[String: ScenicMaterialsJSONValue]]
|
||||
/// 部署响应中的航线容器。
|
||||
private enum CodingKeys: String, CodingKey { case airLines = "air_lines" }
|
||||
}
|
||||
|
||||
/// 场次详情的已确认素材数组及完整场次信息,不借用订单素材 ID 模型。
|
||||
struct ScenicMaterialsSessionDetailResponse: Decodable, Equatable, Sendable {
|
||||
/// 文档明确返回的全部素材项,保留服务端所有字段。
|
||||
let materials: [[String: ScenicMaterialsJSONValue]]
|
||||
/// 场次详情完整对象,供依据实际合同解码归属与展示信息。
|
||||
let fields: [String: ScenicMaterialsJSONValue]
|
||||
|
||||
/// 缺少 materials 或容器错误时报错,不伪装成没有素材。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
fields = try container.decode([String: ScenicMaterialsJSONValue].self)
|
||||
guard case let .array(values)? = fields["materials"] else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "空境场次详情缺少 materials 数组")
|
||||
}
|
||||
materials = try values.map { value in
|
||||
guard case let .object(fields) = value else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "空境素材必须为对象")
|
||||
}
|
||||
return fields
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 保留空境库尚未完整描述的子项 JSON,不猜测字段类型或单位。
|
||||
indirect enum ScenicMaterialsJSONValue: Decodable, Equatable, Sendable {
|
||||
case object([String: ScenicMaterialsJSONValue])
|
||||
case array([ScenicMaterialsJSONValue])
|
||||
case string(String)
|
||||
case number(Decimal)
|
||||
case bool(Bool)
|
||||
case null
|
||||
|
||||
/// 按真实 JSON 类型读取,未知字段不会静默丢失。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if container.decodeNil() { self = .null }
|
||||
else if let value = try? container.decode(Bool.self) { self = .bool(value) }
|
||||
else if let value = try? container.decode(String.self) { self = .string(value) }
|
||||
else if let value = try? container.decode(Decimal.self) { self = .number(value) }
|
||||
else if let value = try? container.decode([String: ScenicMaterialsJSONValue].self) { self = .object(value) }
|
||||
else { self = .array(try container.decode([ScenicMaterialsJSONValue].self)) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import Foundation
|
||||
|
||||
/// 朱工空境库场次查询范围,分页和筛选均由服务端执行。
|
||||
struct ScenicMaterialsQuery: Equatable, Sendable {
|
||||
/// 当前景区身份,不依赖订单、机巢或飞行任务。
|
||||
let scenicID: Int
|
||||
/// 从 1 开始的场次页码。
|
||||
let page: Int
|
||||
/// 每页场次数,接口允许 1 到 100。
|
||||
let pageSize: Int
|
||||
/// 指定航线;nil 表示全部航线。
|
||||
let airLineID: Int?
|
||||
/// 可选起始日期,格式为 yyyy-MM-dd。
|
||||
let dateFrom: String?
|
||||
/// 可选结束日期,格式为 yyyy-MM-dd。
|
||||
let dateTo: String?
|
||||
/// 保留期查询窗口,默认 90 天,部署接口允许 1 到 365。
|
||||
let retentionDays: Int
|
||||
|
||||
/// 创建完整查询快照,便于判断翻页和筛选请求是否过期。
|
||||
init(scenicID: Int, page: Int = 1, pageSize: Int = 20, airLineID: Int? = nil,
|
||||
dateFrom: String? = nil, dateTo: String? = nil, retentionDays: Int = 90) {
|
||||
self.scenicID = scenicID
|
||||
self.page = page
|
||||
self.pageSize = pageSize
|
||||
self.airLineID = airLineID
|
||||
self.dateFrom = dateFrom
|
||||
self.dateTo = dateTo
|
||||
self.retentionDays = retentionDays
|
||||
}
|
||||
|
||||
/// 校验范围后生成文档规定的 GET 参数,全部航线和全部日期不发送占位值。
|
||||
func queryItems() throws -> [URLQueryItem] {
|
||||
guard scenicID > 0 else { throw APIError.networkFailed("请先选择景区") }
|
||||
guard page > 0, (1...100).contains(pageSize), (1...365).contains(retentionDays),
|
||||
airLineID.map({ $0 > 0 }) ?? true else {
|
||||
throw APIError.networkFailed("景区空境库查询参数无效")
|
||||
}
|
||||
guard Self.isValidDate(dateFrom), Self.isValidDate(dateTo) else {
|
||||
throw APIError.networkFailed("请选择有效的日期范围")
|
||||
}
|
||||
if let dateFrom, let dateTo, dateFrom > dateTo {
|
||||
throw APIError.networkFailed("请选择有效的日期范围")
|
||||
}
|
||||
var result = [URLQueryItem(name: "scenic_id", value: String(scenicID)),
|
||||
URLQueryItem(name: "page", value: String(page)),
|
||||
URLQueryItem(name: "page_size", value: String(pageSize)),
|
||||
URLQueryItem(name: "retention_days", value: String(retentionDays))]
|
||||
if let airLineID { result.append(URLQueryItem(name: "air_line_id", value: String(airLineID))) }
|
||||
if let dateFrom { result.append(URLQueryItem(name: "date_from", value: dateFrom)) }
|
||||
if let dateTo { result.append(URLQueryItem(name: "date_to", value: dateTo)) }
|
||||
return result
|
||||
}
|
||||
|
||||
/// 严格校验公历日期,拒绝 DateFormatter 自动纠正的越界日期。
|
||||
private static func isValidDate(_ value: String?) -> Bool {
|
||||
guard let value else { return true }
|
||||
let formatter = DateFormatter()
|
||||
formatter.calendar = Calendar(identifier: .gregorian)
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.timeZone = TimeZone(secondsFromGMT: 0)
|
||||
formatter.dateFormat = "yyyy-MM-dd"
|
||||
formatter.isLenient = false
|
||||
guard let date = formatter.date(from: value) else { return false }
|
||||
return formatter.string(from: date) == value
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import Foundation
|
||||
import Photos
|
||||
|
||||
/// 一项待保存的空境素材;身份仅在当前账号、景区页面的服务实例内使用。
|
||||
struct ScenicMaterialDownloadItem: Sendable {
|
||||
/// 当前素材的稳定标识。
|
||||
let id: String
|
||||
/// 服务端提供的可下载原片地址。
|
||||
let remoteURL: URL
|
||||
/// 本地临时文件名,保留媒体扩展名以便 Photos 识别。
|
||||
let fileName: String
|
||||
/// 与相册保存器一致:1 为视频,其他值为图片。
|
||||
let fileType: Int
|
||||
|
||||
/// 创建下载项,不附加 App 登录凭证到 OSS 地址。
|
||||
init(id: String, remoteURL: URL, fileName: String = "scenic-material.mp4", fileType: Int = 1) {
|
||||
self.id = id
|
||||
self.remoteURL = remoteURL
|
||||
self.fileName = fileName
|
||||
self.fileType = fileType
|
||||
}
|
||||
}
|
||||
|
||||
/// 串行下载并保存真实空境素材;取消后屏蔽旧回执,已保存的文件不重复写入相册。
|
||||
@MainActor
|
||||
final class ScenicMaterialDownloadService {
|
||||
private let downloader: any CloudFileDownloading
|
||||
private let photoSaver: any CloudPhotoSaving
|
||||
private var task: Task<Void, Never>?
|
||||
private var activeBatchID: UUID?
|
||||
private var savedIDs = Set<String>()
|
||||
|
||||
/// 注入下载和相册保存依赖,测试不访问网络或系统相册。
|
||||
init(downloader: any CloudFileDownloading = ScenicMaterialURLSessionDownloader(),
|
||||
photoSaver: any CloudPhotoSaving = ScenicMaterialPhotoLibrarySaver()) {
|
||||
self.downloader = downloader
|
||||
self.photoSaver = photoSaver
|
||||
}
|
||||
|
||||
/// 开始当前批次;同一批次的重复启动无效,重新启动会等待前次相册事务结束。
|
||||
func start(items: [ScenicMaterialDownloadItem], batchID: UUID,
|
||||
onEvent: @escaping @MainActor @Sendable (String, UUID, ScenicMaterialTransferEvent) -> Void,
|
||||
onFailure: (@MainActor @Sendable (String, Error) -> Void)? = nil) {
|
||||
guard activeBatchID != batchID else { return }
|
||||
let previous = task
|
||||
previous?.cancel()
|
||||
activeBatchID = batchID
|
||||
task = Task { @MainActor [weak self] in
|
||||
// Photos 的已提交保存不可取消;先等旧事务落定,再决定是否需要重下。
|
||||
await previous?.value
|
||||
guard let self else { return }
|
||||
defer { if self.activeBatchID == batchID { self.activeBatchID = nil } }
|
||||
var visited = Set<String>()
|
||||
for item in items where visited.insert(item.id).inserted {
|
||||
guard self.isActive(batchID) else { return }
|
||||
if self.savedIDs.contains(item.id) {
|
||||
onEvent(item.id, batchID, .completed)
|
||||
continue
|
||||
}
|
||||
var localURL: URL?
|
||||
defer { if let localURL { try? FileManager.default.removeItem(at: localURL) } }
|
||||
do {
|
||||
localURL = try await self.downloader.downloadFile(remoteURL: item.remoteURL.absoluteString,
|
||||
fileName: item.fileName) { [weak self] percent in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.isActive(batchID), !self.savedIDs.contains(item.id) else { return }
|
||||
// 下载完成只占 90%,最后一步是系统相册保存成功。
|
||||
onEvent(item.id, batchID, .progress(Double(min(max(percent, 0), 100)) / 100 * 0.9))
|
||||
}
|
||||
}
|
||||
guard self.isActive(batchID), let localURL else { return }
|
||||
try await self.photoSaver.saveToPhotoLibrary(fileURL: localURL, fileType: item.fileType)
|
||||
// 保存已落定,即便用户此时暂停,也保留事实以免继续时重复保存。
|
||||
self.savedIDs.insert(item.id)
|
||||
guard self.isActive(batchID) else { return }
|
||||
onEvent(item.id, batchID, .completed)
|
||||
} catch {
|
||||
guard self.isActive(batchID) else { return }
|
||||
onEvent(item.id, batchID, .failed)
|
||||
onFailure?(item.id, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 停止下载并作废当前回执;正在提交的相册事务完成后会清理临时文件。
|
||||
func stop() {
|
||||
activeBatchID = nil
|
||||
task?.cancel()
|
||||
}
|
||||
|
||||
/// 等待已经启动的传输及临时文件清理完成。
|
||||
func waitForPendingOperations() async { await task?.value }
|
||||
|
||||
private func isActive(_ batchID: UUID) -> Bool {
|
||||
!Task.isCancelled && activeBatchID == batchID
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查 HTTP 状态与非空响应文件的空境原片下载器。
|
||||
struct ScenicMaterialURLSessionDownloader: CloudFileDownloading {
|
||||
private let session: URLSession
|
||||
|
||||
/// 注入 URLSession 便于使用 URLProtocol 验证状态码及错误响应。
|
||||
init(session: URLSession = .shared) { self.session = session }
|
||||
|
||||
/// 下载到唯一临时路径;失败响应及取消下载均清理 URLSession 临时文件。
|
||||
func downloadFile(remoteURL: String, fileName: String,
|
||||
onProgress: @escaping @Sendable (Int) -> Void) async throws -> URL {
|
||||
guard let url = URL(string: remoteURL), ["https", "http"].contains(url.scheme?.lowercased() ?? ""),
|
||||
url.host != nil else { throw ScenicMaterialDownloadError.invalidURL }
|
||||
let delegate = ScenicMaterialDownloadProgress(onProgress: onProgress)
|
||||
let (temporaryURL, response) = try await session.download(from: url, delegate: delegate)
|
||||
defer { try? FileManager.default.removeItem(at: temporaryURL) }
|
||||
try Task.checkCancellation()
|
||||
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
|
||||
throw ScenicMaterialDownloadError.httpFailure((response as? HTTPURLResponse)?.statusCode ?? 0)
|
||||
}
|
||||
let attributes = try FileManager.default.attributesOfItem(atPath: temporaryURL.path)
|
||||
guard (attributes[.size] as? NSNumber)?.int64Value ?? 0 > 0 else {
|
||||
throw ScenicMaterialDownloadError.emptyFile
|
||||
}
|
||||
let destination = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("\(UUID().uuidString)-\(CloudTransferFileName.sanitized(fileName))")
|
||||
try FileManager.default.moveItem(at: temporaryURL, to: destination)
|
||||
onProgress(100)
|
||||
return destination
|
||||
}
|
||||
}
|
||||
|
||||
/// 将 URLSession 的实际字节进度传回下载服务,不虚构中间进度。
|
||||
private final class ScenicMaterialDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
|
||||
private let onProgress: @Sendable (Int) -> Void
|
||||
|
||||
init(onProgress: @escaping @Sendable (Int) -> Void) { self.onProgress = onProgress }
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
guard totalBytesExpectedToWrite > 0 else { return }
|
||||
onProgress(Int(min(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite), 1) * 100))
|
||||
}
|
||||
}
|
||||
|
||||
/// 只请求添加相册权限,Photos 成功创建资产后才返回成功。
|
||||
struct ScenicMaterialPhotoLibrarySaver: CloudPhotoSaving {
|
||||
/// 保存本地真实图片或视频;授权期间取消操作不会继续提交相册事务。
|
||||
func saveToPhotoLibrary(fileURL: URL, fileType: Int) async throws {
|
||||
let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
|
||||
try Task.checkCancellation()
|
||||
guard status == .authorized || status == .limited else { throw CloudTransferError.photoPermissionDenied }
|
||||
guard FileManager.default.fileExists(atPath: fileURL.path) else { throw CloudTransferError.localFileMissing }
|
||||
try await PHPhotoLibrary.shared().performChanges {
|
||||
let request = PHAssetCreationRequest.forAsset()
|
||||
request.addResource(with: fileType == 1 ? .video : .photo, fileURL: fileURL, options: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 空境原片下载中可向用户解释的错误。
|
||||
enum ScenicMaterialDownloadError: LocalizedError, Equatable {
|
||||
case invalidURL
|
||||
case httpFailure(Int)
|
||||
case emptyFile
|
||||
|
||||
/// 下载失败原因,避免将服务端错误页作为素材保存。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidURL: "素材地址无效"
|
||||
case .httpFailure(let status): "素材下载失败(HTTP \(status))"
|
||||
case .emptyFile: "素材文件为空,请稍后重试"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,16 @@ import Foundation
|
||||
|
||||
/// 独立景区空镜库的筛选、选择和前台下载演示逻辑;不依赖 UIKit 或机巢业务。
|
||||
final class ScenicMaterialsViewModel {
|
||||
/// 正式模式使用网络素材与真实相册保存,预览模式使用本地演示。
|
||||
let isRemote: Bool
|
||||
/// 本次页面的独立账号与景区范围。
|
||||
let context: ScenicMaterialContext
|
||||
/// 用于筛选的日历及其时区。
|
||||
let calendar: Calendar
|
||||
/// 本地演示保留天数,正式对接后由服务端配置决定。
|
||||
let retentionDays = 90
|
||||
private(set) var retentionDays = 90
|
||||
/// 保留期首日零点,包含今天一共 90 个日历日。
|
||||
let minimumDate: Date
|
||||
private(set) var minimumDate: Date
|
||||
/// 可选的最后一天零点,不允许选择未来日期。
|
||||
let maximumDate: Date
|
||||
/// 当前景区的独立空镜航线,含暂无片段的航线。
|
||||
@@ -37,18 +39,29 @@ final class ScenicMaterialsViewModel {
|
||||
/// 当前批次的逐项演示进度。
|
||||
private(set) var progressByID: [String: Double] = [:]
|
||||
|
||||
/// 已确认接口的加载状态。
|
||||
private(set) var isLoading = false
|
||||
/// 请求失败或素材字段尚无法映射时的可重试提示。
|
||||
private(set) var loadError: String?
|
||||
/// 保留完整响应,非空且未确认字段时不能被当成空库。
|
||||
private(set) var remoteSessions: ScenicMaterialsSessionsResponse?
|
||||
/// 素材保留说明优先使用后端返回的文案。
|
||||
private(set) var retentionTips = "素材保留 90 天,请及时下载"
|
||||
private var loadID: UUID?
|
||||
|
||||
private let initialGroups: [ScenicMaterialGroup]
|
||||
|
||||
/// 创建演示库;可注入日历、日期和数据,测试不依赖时间、网络或登录单例。
|
||||
init(context: ScenicMaterialContext = .demo, now: Date = Date(), calendar: Calendar = .current,
|
||||
routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil) {
|
||||
routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil, isRemote: Bool = false) {
|
||||
self.isRemote = isRemote
|
||||
self.context = context
|
||||
self.calendar = calendar
|
||||
maximumDate = calendar.startOfDay(for: now)
|
||||
minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate
|
||||
let demoRoutes = Self.makeRoutes(context: context)
|
||||
let demoRoutes = isRemote ? [] : Self.makeRoutes(context: context)
|
||||
self.routes = routes ?? demoRoutes
|
||||
let data = groups ?? Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar)
|
||||
let data = groups ?? (isRemote ? [] : Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar))
|
||||
initialGroups = data
|
||||
allGroups = data
|
||||
}
|
||||
@@ -113,10 +126,55 @@ final class ScenicMaterialsViewModel {
|
||||
}
|
||||
}
|
||||
/// 当前空态标题,区分全库为空与有筛选但无结果。
|
||||
var emptyTitle: String { hasAnyMaterials ? "没有符合条件的素材" : "暂无景区素材" }
|
||||
var emptyTitle: String {
|
||||
if isLoading { return "正在加载素材" }
|
||||
if loadError != nil { return "素材加载失败" }
|
||||
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "没有符合条件的素材" : "暂无景区素材"
|
||||
}
|
||||
/// 当前空态说明。
|
||||
var emptyMessage: String {
|
||||
hasAnyMaterials ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
|
||||
if isLoading { return "请稍候" }
|
||||
if let loadError { return loadError }
|
||||
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
|
||||
}
|
||||
|
||||
/// 读取当前景区的真实列表;在有样本确认子项合同前保留原始响应并明确报错。
|
||||
func loadRemoteSessions(api: any ScenicMaterialsServing) async {
|
||||
guard isRemote, !isSelectionLocked else { return }
|
||||
let requestID = UUID()
|
||||
loadID = requestID
|
||||
defer { if loadID == requestID { isLoading = false } }
|
||||
isLoading = true
|
||||
loadError = nil
|
||||
let query = ScenicMaterialsQuery(scenicID: Int(context.scenicID) ?? 0,
|
||||
airLineID: selectedRouteID.flatMap(Int.init),
|
||||
dateFrom: dateRange.map { formatDate($0.start, format: "yyyy-MM-dd") },
|
||||
dateTo: dateRange.map { formatDate($0.end, format: "yyyy-MM-dd") }, retentionDays: retentionDays)
|
||||
do {
|
||||
let response = try await api.sessions(query: query)
|
||||
guard loadID == requestID, !Task.isCancelled else { return }
|
||||
remoteSessions = response
|
||||
retentionDays = response.retentionDays
|
||||
retentionTips = response.retentionTips
|
||||
minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate
|
||||
allGroups = []
|
||||
routes = []
|
||||
selectedIDs.removeAll()
|
||||
if response.total > 0 || !response.list.isEmpty || !response.groups.isEmpty || !response.airLines.isEmpty {
|
||||
// 当前文档没有非空场次/航线的字段合同,不使用猜测的 ID 下载或错配素材。
|
||||
loadError = "暂时无法显示素材,请稍后重试"
|
||||
}
|
||||
} catch is CancellationError {
|
||||
} catch {
|
||||
guard loadID == requestID else { return }
|
||||
loadError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 离页或身份变化后作废尚未返回的列表请求。
|
||||
func cancelRemoteLoad() {
|
||||
loadID = nil
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
/// 查找稳定航线,不依赖名称。
|
||||
@@ -171,7 +229,7 @@ final class ScenicMaterialsViewModel {
|
||||
|
||||
/// 当前可选状态;完成、不可用、隐藏片段或锁定批次均不可新选。
|
||||
func canSelect(id: String) -> Bool {
|
||||
!isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && !completedIDs.contains(id) }
|
||||
!isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains(id) }
|
||||
}
|
||||
|
||||
/// 切换单项选择,不涉及预览或下载。
|
||||
@@ -215,7 +273,7 @@ final class ScenicMaterialsViewModel {
|
||||
@discardableResult
|
||||
func startDownload() -> Bool {
|
||||
guard !isSelectionLocked else { return false }
|
||||
let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && !completedIDs.contains($0.id) }
|
||||
let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }
|
||||
guard !items.isEmpty else { return false }
|
||||
batchItemIDs = items.map(\.id)
|
||||
selectedIDs = Set(batchItemIDs)
|
||||
@@ -285,6 +343,7 @@ final class ScenicMaterialsViewModel {
|
||||
|
||||
/// 切换本地状态预览,不读取真实相册,也不更改登录身份或订单。
|
||||
func applyScenario(_ scenario: ScenicMaterialsScenario) {
|
||||
guard !isRemote else { return }
|
||||
clearBatch()
|
||||
completedIDs.removeAll()
|
||||
allGroups = initialGroups
|
||||
@@ -320,11 +379,11 @@ final class ScenicMaterialsViewModel {
|
||||
|
||||
private func selectableIDs(in groupID: String) -> Set<String> {
|
||||
guard let group = filteredGroups.first(where: { $0.id == groupID }) else { return [] }
|
||||
return Set(group.clips.filter { $0.isAvailable && !completedIDs.contains($0.id) }.map(\.id))
|
||||
return Set(group.clips.filter { $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }.map(\.id))
|
||||
}
|
||||
|
||||
private func pruneSelection() {
|
||||
let valid = Set(filteredClips.filter { $0.isAvailable && !completedIDs.contains($0.id) }.map(\.id))
|
||||
let valid = Set(filteredClips.filter { $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }.map(\.id))
|
||||
selectedIDs.formIntersection(valid)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user