feat(drone-dock): 完善真实联调、状态轮询与准备页反馈

开放 Release 真实操作并保留 Debug 拦截;恢复前台 shooting 串行轮询;统一打印机巢请求与完整原值响应;优化长点位名称、未拍摄文案、报备失败及已结束任务提示,移除成功回执 UI。补充相关测试、离线策略检查和联调说明。
This commit is contained in:
2026-11-02 16:26:50 +08:00
parent b21a3b6cb6
commit 2d86ec8cd7
37 changed files with 1298 additions and 411 deletions
+15
View File
@@ -107,3 +107,18 @@ Swift · UIKit · SnapKit(代码布局,约束写在 `setupUI()` / `setupCons
- Release 任务页提供手动开启火山 RTC 图传的入口;进页、回前台、异常或凭证过期均不自动调用 `live`。这不授权召唤、起飞、开拍、暂停、恢复或返航。
- Debug 的 `live` 网络拦截继续保持,RTC 引擎连接前也必须拦截;没有运行时放行开关。状态读取继续关闭设备实时采集。
- 真实 `tasks/create` 和飞控请求在 Debug、Release 均拦截;通过“订单素材库 → 查看任务”进入已有任务,不为测试图传创建或召唤新任务。
## Release 真实操作与日志(2026-11-02 后续用户明确授权)
- 用户明确回复:“开放 Release 真实操作,Debug 保持拦截”。本节覆盖上文“Release 禁止创建和飞控”的旧限制。
- Release 可由用户自行真机执行 `tasks/create`、`shoot`(含重新召唤)、`start-shoot`、`command` 及手动 `live`;保持原有门禁、同任务身份校验、防重复提交和结果未知时不自动重发。
- 代理本次仍只编译、使用模拟器和隔离网络替身,不主动调用真实飞控、创建待飞任务或开启图传。用户自行打包、连接真实环境测试。
- Debug 真实操作仍在网络层拦截,没有运行时放行开关;未知机场操作仍阻断。
- `shooting` 按用户要求恢复前台可见时串行轮询,默认 5 秒,后端建议限制为 2~30 秒;离页/后台停止,旧快照保留。`live_battery=0`,`status` 仍为 `live_metrics=0`。
- Release 机巢诊断使用 `[DroneDock]` 系统日志;保留任务身份和脱敏业务回包,禁止输出登录 Header、RTC token 或有效播放 URL。
## 机巢控制台完整日志(2026-11-02 最新用户要求)
- 用户明确要求:“打印到控制台的日志信息,不需要 redacted,我要全部显示出来”。本节覆盖上文机巢控制台日志脱敏限制。
- Debug/Release 的机巢接口请求头、参数、JSON/文本响应按原值记录,包含 URL、RTC/STS 参数;保持 `[DroneDock]`、请求关联和完整分段。视频/图片二进制仍记录传输摘要。
- 此调整仅涉及日志,不解除 Debug 禁飞保护;代理继续仅使用隔离替身和模拟器验证。
@@ -0,0 +1,54 @@
# Release 机巢日志与 shooting 轮询
日期:2026-11-02。以下为客户端实现说明,模拟结果不代表真实设备已执行。
## 收集真机日志
1. 将安装本次 Release 包的 iPhone 连接 Mac,解锁并信任电脑。
2. 打开 macOS「控制台」,在设备列表选择这台 iPhone,开始实时流式传输。
3. 搜索 `[DroneDock]`(系统日志 subsystem 为 `com.yuanzhixiang.suixinkan`,category 为 `DroneDock`)。先开始收集,再在 App 操作。
4. 将从进入准备页到异常出现后的日志完整复制为 txt 发回,同时附操作时间、订单号、页面现象。通过 Xcode 启动时也可在调试控制台筛选同一标签。
使用 `Logger.notice`,代码不受 `#if DEBUG` 限制;不依赖 `print` 或调试器连接。App 未连接电脑时,系统日志是否仍可导出由 iOS 日志保留策略决定,本次没有新增 App 内文件导出功能。
## 日志字段
- 当前范围:`/api/app/airport/*`、`/api/yf-handset-app/photog/multi-plane/*`、`/api/app/scenic-media/*` 和共用的 `/api/app/config/get-sts-token`。覆盖首页、订单、今日统计、收款套餐/付款码/记录、准备与飞行任务、订单素材、云端交付、游客确认和景区空境库。
- Debug 和 Release 均记录每一次实际请求及响应,包括相同内容的轮询。JSON 按原值完整分段,不做字段摘要、采样、去重或长度截断;接口关闭普通正文日志也不会屏蔽机巢的完整诊断。
- 外层 `session`:本次 App 进程;`entry`:一条事件;`part=1/N`:按 UTF-8 字节分段的序号。收集所有分段,JSON 才完整。
- HTTP 事件:`request_id` 关联同一次请求的开始/回包/解析;`elapsed_ms` 是累计耗时;`host` 区分生产与测试环境;`source` 为 `network` 或 `local_simulation`;`build` 与 `flight_blocked/live_blocked` 显示构建和拦截策略。
- 参数/回包:`method/url/path/query/request_headers/body/http_status/response_headers`,保留任务 ID、订单号、点位、航线、状态、门禁、业务码与错误说明。
- `request.blocked` + `sent=false` 表示本机阻止请求,未发给后端。`response.decoded` 只表示 HTTP/业务解包成功。`*.receipt_accepted` 只表示同任务回执验证通过,均不代表无人机已经执行;实际阶段看 `shooting.snapshot_applied` 及后端状态。
- 页面与流程:确认按钮、跳转任务页、状态刷新、下一次轮询时间、离页/前后台、开拍/控制/重召唤结果待核对。
- 图传:手动请求、参数是否可用、进房返回码、订阅返回码、首帧、错误、过期与停止。不会记录 SDK 的原始 extraInfo。
- 文件传输:成片 OSS 上传使用 `file_upload.*`,订单素材和空境素材下载使用 `file_download.*`;记录请求方法、完整地址、对象键、请求关联、耗时、字节数、HTTP 状态、响应头、失败或取消。视频/图片二进制不写入日志,OSS 回调 JSON 如有返回也会原样记录。
按用户最新要求取消控制台脱敏:请求头、Token、签名、STS 临时凭证、RTC 播放串、媒体 URL、手机号和设备序列号均按接口原值输出,不再替换为 `<redacted>`。非 JSON 的文本错误页也完整输出,二进制仅记录大小。日志不改变业务请求/响应;其他模块除共用 STS 外保持原日志策略。测试及文档示例仍使用虚构数据,不写入真实凭证。
## 本次授权范围
用户明确授权“开放 Release 真实操作,Debug 保持拦截”。Release 首页/订单准备入口允许 `tasks/create → shoot`,任务页注入 `start-shoot/command/shoot restart=true` 服务;使用原有门禁、任务校验、防重和返航确认。真实按钮不再显示“本地模拟”。`live` 仍需手动点击,未知设备操作和不匹配的 HTTP 方法仍被拦截。
Debug 网络保护与 RTC 初始化前保护不变。代理不会调用真实创建、飞控或图传;真实设备测试由用户自行打包执行。
## shooting 轮询
- 页面完整出现/可见时回前台立即 GET;随后上次 GET 结束后再等默认 5 秒。
- 使用后端 `plane_status.poll_hint_ms`,正数限制为 2~30 秒,无效/缺失回退 5 秒。
- 串行读取同一任务,不并发;手动刷新替换尚未开始的下一次计时。
- 离页/后台取消,身份变更终止;刷新及普通失败保留旧快照,下周期可恢复。自动刷新失败不反复弹 Toast。
- 控制流程暂停轮询,受理后的回查完成再恢复。绝不自动重发 `tasks/create/shoot/start-shoot/command`。
- `live_battery=0`,不启动实时采集;轮询不请求 `live`、不重启播放器。
## 验证
- 取消脱敏后:52 项相关模拟器测试通过,验证原始 Header、RTC/STS 参数、签名 URL、嵌套 JSON、文本错误页、长日志分段和原有飞控保护。Release 无签名编译通过,Debug/Release 离线策略脚本均通过。结果:`test_sim_2026-11-02T08-20-39-894Z_pid2672_0db869c5.xcresult`;构建日志:`/private/tmp/suixinkan-raw-api-logging-release-build.log`。
- 历史验证(取消脱敏前):全接口日志补齐后,83 项相关模拟器测试通过,覆盖接口范围、完整请求/响应、重复请求、STS/RTC 脱敏、文件摘要、网络客户端、业务 API 和上传/下载回归;Release 无签名编译通过。结果:`test_sim_2026-11-02T08-08-11-112Z_pid2672_6a9a831c.xcresult`;构建日志:`/private/tmp/suixinkan-all-api-logging-release-build.log`。
- 历史验证(取消脱敏前):模拟器 151 项测试通过,0 失败、0 跳过。覆盖轮询生命周期/并发/旧快照/失败恢复、图传不随轮询开启、日志脱敏及大 JSON 分段、准备页创建/召唤与安全控制防重、Debug 禁飞保护和统一网络客户端。
- Release `generic/platform=iOS` 无签名构建通过,没有安装或启动 Release App。
- `scripts/verify-drone-dock-build-policy.swift` 分别按 Debug/Release 编译并运行:验证已知操作 POST 在 Debug 拦截、Release 放行,错误方法/未知操作始终拦截,状态仍关闭实时采集,诊断日志按原值输出。此脚本没有网络传输实现。
- 代理仅使用隔离网络替身和模拟器,没有执行真实创建、召唤、拍摄、控制或图传。
模拟器结果:`/Users/hanqiu/Library/Developer/XcodeBuildMCP/workspaces/suixinkan-a3033d697ba3/result-bundles/test_sim_2026-11-02T03-58-41-113Z_pid7237_4d1daf27.xcresult`。
Release 构建日志:`/private/tmp/suixinkan-release-diagnostics-final-build.log`。
@@ -0,0 +1,49 @@
import Foundation
/// 离线验证两种编译模式的设备请求策略;不创建 URLSession、不发送网络请求。
@main
struct DroneDockBuildPolicyCheck {
static func main() throws {
#if DEBUG
let blocked = true
let mode = "Debug"
#else
let blocked = false
let mode = "Release"
#endif
precondition(DeviceCommandDebugPolicy.blocksFlightRequests == blocked)
precondition(DeviceCommandDebugPolicy.blocksLiveRequests == blocked)
let paths = ["/api/yf-handset-app/photog/multi-plane/tasks/create",
"/api/app/airport/shoot", "/api/app/airport/start-shoot", "/api/app/airport/command"]
for path in paths {
try check(path, method: "POST", shouldBlock: blocked)
try check(path, method: "GET", shouldBlock: true)
}
try check("/api/app/airport/live", method: "GET", shouldBlock: blocked)
try check("/api/app/airport/live", method: "POST", shouldBlock: true)
try check("/api/app/airport/future-control", method: "POST", shouldBlock: true)
let read = request("/api/app/airport/shooting?id=501&live_battery=1", method: "GET")
let prepared = try DeviceCommandDebugPolicy.prepare(read, isLocalSimulation: false)
precondition(prepared.url?.query?.contains("live_battery=0") == true)
let trace = DroneDockRequestTrace(request: prepared, isSimulation: true)!
let logged = trace.message("offline_check", fields: ["token": "TEST_TOKEN", "play": ["url": "TEST_RTC"]])
precondition(logged.contains("TEST_TOKEN") && logged.contains("TEST_RTC"))
precondition(logged.contains(mode) && logged.contains("501"))
print("PASS \(mode): flight_blocked=\(blocked), unknown operations blocked, cached status, complete diagnostics. No network sent.")
}
private static func request(_ path: String, method: String) -> URLRequest {
var value = URLRequest(url: URL(string: "https://example.invalid" + path)!)
value.httpMethod = method
return value
}
private static func check(_ path: String, method: String, shouldBlock: Bool) throws {
do {
_ = try DeviceCommandDebugPolicy.prepare(request(path, method: method), isLocalSimulation: false)
precondition(!shouldBlock, "Unexpected allow: \(method) \(path)")
} catch is DeviceCommandDebugBlockedError {
precondition(shouldBlock, "Unexpected block: \(method) \(path)")
}
}
}
+8 -4
View File
@@ -64,15 +64,11 @@
};
9A01B8E22FFB84950033C402 /* Vendor */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
);
path = Vendor;
sourceTree = "<group>";
};
A1B2C3D42FFB84950033C305 /* suixinkanTests */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
);
path = suixinkanTests;
sourceTree = "<group>";
};
@@ -372,10 +368,14 @@
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-suixinkan/Pods-suixinkan-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
inputPaths = (
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-suixinkan/Pods-suixinkan-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-suixinkan/Pods-suixinkan-frameworks.sh\"\n";
@@ -389,10 +389,14 @@
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-suixinkan/Pods-suixinkan-resources-${CONFIGURATION}-input-files.xcfilelist",
);
inputPaths = (
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-suixinkan/Pods-suixinkan-resources-${CONFIGURATION}-output-files.xcfilelist",
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-suixinkan/Pods-suixinkan-resources.sh\"\n";
@@ -53,7 +53,7 @@
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
+48 -12
View File
@@ -24,6 +24,7 @@ final class APIClient {
private let decoder: JSONDecoder
private let notificationCenter: NotificationCenter
private let debugLogSink: (String) -> Void
private let droneDockLogSink: (String) -> Void
private var authTokenProvider: (() -> String?)?
private let environment: APIEnvironment
@@ -39,7 +40,8 @@ final class APIClient {
appVersion: String = AppClientInfo.appVersion(),
osType: String = AppClientInfo.osType,
notificationCenter: NotificationCenter = .default,
debugLogSink: @escaping (String) -> Void = { print($0) }
debugLogSink: @escaping (String) -> Void = { print($0) },
droneDockLogSink: @escaping (String) -> Void = DroneDockDiagnostics.write
) {
self.environment = environment
self.session = session
@@ -47,6 +49,7 @@ final class APIClient {
self.decoder = decoder
self.notificationCenter = notificationCenter
self.debugLogSink = debugLogSink
self.droneDockLogSink = droneDockLogSink
self.appVersion = appVersion.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? "1.0.0"
self.osType = osType.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? AppClientInfo.osType
}
@@ -69,36 +72,69 @@ final class APIClient {
_ apiRequest: APIRequest<Response>,
tokenOverride: String? = nil
) async throws -> Response {
let request = try DeviceCommandDebugPolicy.prepare(
makeURLRequest(apiRequest, tokenOverride: tokenOverride),
isLocalSimulation: session is any LocalSimulationURLSession)
logRequest(request, includeBody: apiRequest.logsPayload, category: apiRequest.redactedLogCategory)
let original = try makeURLRequest(apiRequest, tokenOverride: tokenOverride)
let isSimulation = session is any LocalSimulationURLSession
let request: URLRequest
do {
request = try DeviceCommandDebugPolicy.prepare(original, isLocalSimulation: isSimulation)
} catch {
if let trace = DroneDockRequestTrace(request: original, isSimulation: isSimulation) {
var fields = DroneDockDiagnostics.errorFields(error)
fields["body"] = DroneDockDiagnostics.payload(original.httpBody)
droneDockLogSink(trace.message("request.blocked", fields: fields))
}
throw error
}
let trace = DroneDockRequestTrace(request: request, isSimulation: isSimulation)
if let trace {
droneDockLogSink(trace.message("request.started", fields: ["body": DroneDockDiagnostics.payload(request.httpBody)]))
} else {
logRequest(request, includeBody: apiRequest.logsPayload, category: apiRequest.redactedLogCategory)
}
let data: Data
let response: URLResponse
do {
(data, response) = try await session.data(for: request)
} catch is CancellationError {
logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory)
if let trace { droneDockLogSink(trace.message("request.cancelled")) }
else { logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory) }
throw CancellationError()
} catch let error as URLError {
if let trace { droneDockLogSink(trace.message(error.code == .cancelled ? "request.cancelled" : "request.failed",
fields: DroneDockDiagnostics.errorFields(error))) }
if error.code == .cancelled {
logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory)
if trace == nil { logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory) }
throw CancellationError()
}
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
throw APIError.networkFailed(networkErrorMessage(for: error))
} catch {
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
if let trace { droneDockLogSink(trace.message("request.failed", fields: DroneDockDiagnostics.errorFields(error))) }
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
throw APIError.networkFailed(error.localizedDescription)
}
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload,
category: apiRequest.redactedLogCategory)
if let trace {
// 用户要求机巢接口原样记录请求和响应,含 live / STS;统一通路避免重复打印。
droneDockLogSink(trace.message("response.received", fields: [
"http_status": (response as? HTTPURLResponse)?.statusCode ?? 0,
"response_headers": (response as? HTTPURLResponse)?.allHeaderFields.reduce(into: [String: String]()) {
$0[String(describing: $1.key)] = String(describing: $1.value)
} ?? [:],
"body": DroneDockDiagnostics.payload(data)
]))
} else {
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload,
category: apiRequest.redactedLogCategory)
}
do {
try validateHTTPResponse(response, data: data)
return try decodeEnvelope(Response.self, from: data)
let value = try decodeEnvelope(Response.self, from: data)
if let trace { droneDockLogSink(trace.message("response.decoded")) }
return value
} catch let error as APIError {
if let trace { droneDockLogSink(trace.message("response.rejected", fields: DroneDockDiagnostics.errorFields(error))) }
notifySessionErrorIfNeeded(for: error, request: request)
throw error
}
+1 -1
View File
@@ -21,7 +21,7 @@ nonisolated struct APIRequest<Response: Decodable> {
var queryItems: [URLQueryItem]
var headers: [String: String]
var body: AnyEncodable?
/// 敏感请求关闭正文日志,避免验证码和注销资产进入调试日志。
/// 控制普通正文日志;机巢范围按用户要求始终记录完整请求和响应。
var logsPayload: Bool
/// 为指定模块输出带标签的脱敏日志;隐藏凭证字段和响应中媒体 URL 的查询参数。
var redactedLogCategory: String?
@@ -1,9 +1,15 @@
import Foundation
/// 禁飞期间的请求边界;正式包仅允许用户手动图传,不允许创建或飞控。
/// 调试请求边界:Debug 禁止真实设备操作,Release 按用户授权开放已对接的操作。
enum DeviceCommandDebugPolicy {
/// 飞控与真实待飞任务在所有构建中关闭,不因打 Release 包而解除禁飞。
static let blocksFlightRequests = true
/// 2026-11-02 用户授权 Release 真机联调;Debug 仍无运行时放行开关。
static var blocksFlightRequests: Bool {
#if DEBUG
true
#else
false
#endif
}
/// 所有 Debug 构建禁止真实设备操作,没有启动参数或设置开关可临时放行。
static var blocksLiveRequests: Bool {
#if DEBUG
@@ -20,12 +26,15 @@ enum DeviceCommandDebugPolicy {
static func prepare(_ request: URLRequest, isLocalSimulation: Bool) throws -> URLRequest {
guard !isLocalSimulation, let url = request.url else { return request }
let path = "/" + url.path.split(separator: "/").joined(separator: "/")
// 创建虽不直接起飞,但会改变真实订单状态;禁飞调试使用本地待飞任务。
// Debug 创建也必须拦截,避免调试残留真实待飞任务。
if path == "/api/yf-handset-app/photog/multi-plane/tasks/create" {
throw DeviceCommandDebugBlockedError()
guard !blocksFlightRequests, request.httpMethod == "POST" else { throw DeviceCommandDebugBlockedError() }
return request
}
guard path == "/api/app/airport" || path.hasPrefix("/api/app/airport/") else { return request }
// 2026-11-02 仅为用户后续手动图传测试提供 Release 入口;Debug 仍禁止开流。
let flightPaths: Set<String> = ["/api/app/airport/shoot", "/api/app/airport/start-shoot", "/api/app/airport/command"]
if !blocksFlightRequests, request.httpMethod == "POST", flightPaths.contains(path) { return request }
// 仅允许已确认的图传和飞控接口;未知设备操作仍阻断。
if request.httpMethod == "GET", path == "/api/app/airport/live", !blocksLiveRequests { return request }
let readablePaths: Set<String> = [
"/api/app/airport/home", "/api/app/airport/plane-status",
@@ -0,0 +1,153 @@
import Foundation
import OSLog
/// 机巢联调日志:按用户要求在 Debug 与 Release 控制台原样记录字段,不做脱敏。
enum DroneDockDiagnostics {
private static let logger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "DroneDock")
private static let sessionID = String(UUID().uuidString.prefix(8))
/// 按 UTF-8 字节分段,避免系统日志截断大响应;每段携带同一事件 ID 和序号。
static func write(_ message: String) {
let entry = String(UUID().uuidString.prefix(8))
let chunks = chunks(message)
for (index, chunk) in chunks.enumerated() {
let line = "[DroneDock] session=\(sessionID) entry=\(entry) part=\(index + 1)/\(chunks.count) \(chunk)"
logger.notice("\(line, privacy: .public)")
}
}
/// 页面、业务与 RTC 事件以结构化字段记录。
static func event(_ name: String, taskID: Int? = nil, fields: [String: Any] = [:]) {
var fields = fields
fields["task_id"] = taskID
fields["event"] = name
write(json(fields))
}
/// 覆盖机巢全部业务接口、景区空境库及共用 STS;不依赖页面或构建环境开关。
static func includes(path: String) -> Bool {
["/api/app/airport/", "/api/yf-handset-app/photog/multi-plane/", "/api/app/scenic-media/"]
.contains(where: path.hasPrefix) || path == "/api/app/config/get-sts-token"
}
/// JSON 保留完整字段,文本错误页原样记录;二进制正文只记录字节数。
static func payload(_ data: Data?) -> Any {
guard let data, !data.isEmpty else { return "<empty>" }
return (try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed))
?? String(data: data, encoding: .utf8)
?? "<binary: \(data.count) bytes>"
}
/// 排序 JSON 便于复制比对,所有字段值保持原样。
static func json(_ object: Any) -> String {
guard let data = try? JSONSerialization.data(withJSONObject: object,
options: [.sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes]),
let text = String(data: data, encoding: .utf8) else { return "<invalid diagnostic fields>" }
return text
}
/// 记录业务码、HTTP 状态及原始错误说明,便于与后端回包对应。
static func errorFields(_ error: Error) -> [String: Any] {
if error is CancellationError { return ["kind": "cancelled"] }
if error is DeviceCommandDebugBlockedError { return ["kind": "locally_blocked", "sent": false] }
if case APIError.serverCode(let code, let message) = error {
return ["kind": "business_rejected", "code": code, "message": message]
}
if case APIError.decodeFailed(let message) = error { return ["kind": "decode_failed", "message": message] }
if case APIError.httpStatus(let code, let message) = error {
return ["kind": "http_rejected", "http_status": code, "message": message]
}
if case APIError.emptyData = error { return ["kind": "empty_data"] }
let value = error as NSError
var fields: [String: Any] = ["kind": "error", "domain": value.domain, "code": value.code,
"message": value.localizedDescription]
fields["failing_url"] = value.userInfo[NSURLErrorFailingURLStringErrorKey] as? String
return fields
}
/// 单段最多 600 字节,长 JSON 可按 entry 和 part 拼回完整响应。
static func chunks(_ text: String) -> [String] {
var result: [String] = []
var current = ""
var bytes = 0
for scalar in text.unicodeScalars {
let next = String(scalar)
if bytes + next.utf8.count > 600 { result.append(current); current = ""; bytes = 0 }
current += next
bytes += next.utf8.count
}
if !current.isEmpty { result.append(current) }
return result.isEmpty ? [""] : result
}
}
/// 视频上传和素材下载的网络摘要,保留完整地址和传输状态。
struct DroneDockFileTransferTrace: Sendable {
private let requestID = UUID().uuidString
private let started = ProcessInfo.processInfo.systemUptime
private let operation: String
private let method: String
private let remoteURL: URL?
/// 仅在实际文件传输边界创建,记录传入的完整目标地址。
init(operation: String, method: String, remoteURL: URL?) {
self.operation = operation
self.method = method
self.remoteURL = remoteURL
}
/// 请求、响应和错误共用同一关联 ID;文件响应仅记录状态与大小。
func message(_ event: String, fields: [String: Any] = [:]) -> String {
var fields = fields
fields["event"] = operation + "." + event
fields["request_id"] = requestID
fields["elapsed_ms"] = Int((ProcessInfo.processInfo.systemUptime - started) * 1_000)
fields["source"] = "network"
fields["method"] = method
fields["host"] = remoteURL?.host
fields["url"] = remoteURL?.absoluteString
return DroneDockDiagnostics.json(fields)
}
}
/// 一次请求的关联 ID 与耗时;模拟/真实传输明确区分,不把 HTTP 成功当作设备执行成功。
struct DroneDockRequestTrace {
private let requestID = UUID().uuidString
private let started = ProcessInfo.processInfo.systemUptime
private let request: URLRequest
private let isSimulation: Bool
/// 未在机巢范围的请求不生成日志。
init?(request: URLRequest, isSimulation: Bool) {
guard DroneDockDiagnostics.includes(path: request.url?.path ?? "") else { return nil }
self.request = request
self.isSimulation = isSimulation
}
/// 保留完整地址、请求头、业务参数与固定身份。
func message(_ event: String, fields: [String: Any] = [:]) -> String {
var fields = fields
fields["event"] = event
fields["request_id"] = requestID
fields["elapsed_ms"] = Int((ProcessInfo.processInfo.systemUptime - started) * 1_000)
fields["source"] = isSimulation ? "local_simulation" : "network"
fields["host"] = request.url?.host
fields["path"] = request.url?.path
fields["method"] = request.httpMethod
fields["url"] = request.url?.absoluteString
fields["request_headers"] = request.allHTTPHeaderFields ?? [:]
fields["app_version"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
fields["app_build"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
#if DEBUG
fields["build"] = "Debug"
#else
fields["build"] = "Release"
#endif
fields["flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests
fields["live_blocked"] = DeviceCommandDebugPolicy.blocksLiveRequests
let items = request.url.flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false)?.queryItems } ?? []
fields["query"] = items.map { [$0.name: $0.value ?? ""] }
return DroneDockDiagnostics.json(fields)
}
}
@@ -1,6 +1,6 @@
import Foundation
/// 基于既有订单飞行任务发送单次安全指令;禁飞期间仅向本地模拟页面注入。
/// 基于既有订单飞行任务发送单次安全指令;Release 注入真实页面,Debug 仅向本地模拟页面注入。
protocol DroneDockCommandSending: Sendable {
/// 提交任务 ID 和白名单指令,不创建任务、不选机,也不自动重试。
@MainActor
@@ -1,6 +1,6 @@
import Foundation
/// 朱工任务图传参数服务;请求可能启动设备图传,禁飞期间只允许隔离模拟注入。
/// 朱工任务图传参数服务;请求可能启动设备图传,Release 可手动开启,Debug 只允许隔离模拟注入。
protocol DroneDockLiveServing: Sendable {
/// 读取同一订单飞行任务的图传回执,不创建任务或更换飞机。
@MainActor
@@ -27,7 +27,7 @@ final class DroneDockShootAPI: DroneDockShootServing, DroneDockResummonServing {
try await send(taskID: taskID, restart: false)
}
/// 复用同一订单飞行任务请求重启;当前仅由隔离模拟入口注入,真实传输仍受禁飞保护。
/// 复用同一订单飞行任务请求重启;Release 真实入口及隔离模拟入口按策略注入。
func resummon(taskID: Int) async throws -> DroneDockShootResponse {
try await send(taskID: taskID, restart: true)
}
@@ -7,7 +7,7 @@ protocol DroneDockStartShooting: Sendable {
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse
}
/// start-shoot 合同适配;禁飞期间真实传输仍由统一客户端阻断,仅用 Mock 验证。
/// start-shoot 合同适配;Debug 真实传输由统一客户端阻断,Release 按用户授权开放。
@MainActor
final class DroneDockStartShootAPI: DroneDockStartShooting {
private let client: APIClient
@@ -0,0 +1,43 @@
import Foundation
/// 准备页的业务失败提示;区分创建与召唤,不把通用业务错误码当作未报备。
struct DroneDockPreparationFailure: Equatable, Sendable {
/// 失败发生的提交步骤。
enum Stage: Sendable { case creation, summon }
/// 面向工作人员的标题。
let title: String
/// 原因及下一步操作,不包含接口 JSON。
let message: String
/// 后端文字明确指出报备问题时,额外弹出提醒。
let requiresFiling: Bool
/// 未获得专用错误码前,仅匹配明确报备/备案失败的文字,其他原因保持后端原意。
init(message: String, stage: Stage, outcomeUnknown: Bool) {
requiresFiling = !outcomeUnknown && Self.isFilingFailure(message)
if outcomeUnknown {
title = stage == .creation ? "任务创建结果待核对" : "召唤结果待核对"
self.message = message
} else if requiresFiling {
title = "请先完成飞行报备"
self.message = message + "\n请联系相关负责人核实并完成飞行报备,确认生效后再重试。"
} else if stage == .summon && Self.requiresTaskReview(message) {
title = "任务已结束"
self.message = "当前任务已结束,无法直接召唤。请先查看拍摄任务状态;如需重新召唤,在任务页确认后操作。"
} else {
title = stage == .creation ? "任务创建失败" : "召唤失败"
self.message = message
}
}
/// 仅识别实际返回的明确终止提示;不会据此自动发送 restart=true。
static func requiresTaskReview(_ message: String) -> Bool {
message.contains("任务已结束") && message.contains("无法召唤")
}
private static func isFilingFailure(_ message: String) -> Bool {
["未报备", "未完成报备", "报备未", "报备失败", "报备过期", "报备已过期",
"报备失效", "报备已失效", "无有效报备", "没有报备", "无报备", "请先报备", "需要报备",
"未备案", "未完成备案", "备案未", "备案失败", "备案已过期", "请先备案"]
.contains(where: message.contains)
}
}
@@ -92,7 +92,7 @@ struct DroneDockShootingPlaneStatus: Decodable, Equatable, Sendable {
let scenicID: Int?
/// 后端景区连接状态。
let connected: Bool?
/// 保留后端建议间隔;当前任务页不据此安排定时请求。
/// 后端建议轮询间隔,任务页校验并限制频率后使用。
let pollHintMS: Int?
/// 设备快照字段映射,其余字段仍保留在完整 dataJSON 中。
@@ -92,14 +92,33 @@ struct DroneDockOSSFilmTransport: DroneDockFilmTransporting {
let sdkConfiguration = Configuration.default().withRegion(configuration.region).withCredentialsProvider(credentials)
sdkConfiguration.withEndpoint(configuration.endpoint)
let client = Client(sdkConfiguration)
_ = try await client.putObject(PutObjectRequest(
bucket: configuration.bucket, key: objectKey, contentType: contentType, body: .file(fileURL),
progress: ProgressClosure { _, transferred, expected in
guard expected > 0 else { return }
let value = Int(min(100, max(0, Double(transferred) / Double(expected) * 100)))
Task { @MainActor in onProgress(value) }
}
))
let trace = DroneDockFileTransferTrace(operation: "file_upload", method: "PUT",
remoteURL: URL(string: configuration.endpoint))
let fileSize = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0
DroneDockDiagnostics.write(trace.message("request.started", fields: [
"bucket": configuration.bucket, "object_key": objectKey,
"bytes": fileSize, "content_type": contentType, "body": "<binary omitted>"
]))
do {
let result = try await client.putObject(PutObjectRequest(
bucket: configuration.bucket, key: objectKey, contentType: contentType, body: .file(fileURL),
progress: ProgressClosure { _, transferred, expected in
guard expected > 0 else { return }
let value = Int(min(100, max(0, Double(transferred) / Double(expected) * 100)))
Task { @MainActor in onProgress(value) }
}
))
DroneDockDiagnostics.write(trace.message("response.received", fields: [
"http_status": result.statusCode, "oss_request_id": result.requestId,
"response_headers": result.headers ?? [:],
"body": DroneDockDiagnostics.payload(result.callbackResult)
]))
} catch {
let cancelled = error is CancellationError || (error as? URLError)?.code == .cancelled
DroneDockDiagnostics.write(trace.message(cancelled ? "request.cancelled" : "request.failed",
fields: DroneDockDiagnostics.errorFields(error)))
throw error
}
try Task.checkCancellation()
#else
throw OSSUploadError.sdkUnavailable
@@ -123,8 +123,10 @@ final class DroneDockLiveViewModel {
rtcConfiguration = try DroneDockVolcLiveConfiguration.parse(value, now: now())
playbackSessionID = UUID()
state = .connecting
DroneDockDiagnostics.event("live.parameters_valid", taskID: taskID, fields: ["provider": "volc", "playback_session": playbackSessionID?.uuidString ?? ""])
} catch {
state = .unavailable(error.localizedDescription)
DroneDockDiagnostics.event("live.parameters_rejected", taskID: taskID, fields: ["reason": error.localizedDescription])
}
return
}
@@ -155,6 +157,7 @@ final class DroneDockLiveViewModel {
/// 离页、后台或取消时作废旧请求并清除本地播放来源,不向设备发送停止指令。
@MainActor
func invalidate() {
if playbackSessionID != nil { DroneDockDiagnostics.event("live.stopped", taskID: taskID) }
generation &+= 1
isLoading = false
response = nil
@@ -173,6 +176,8 @@ final class DroneDockLiveViewModel {
state = .failed("账号或景区已变化,请返回工作台重新进入")
return
}
DroneDockDiagnostics.event("live.playback_event", taskID: taskID,
fields: ["playback_session": sessionID.uuidString, "result": String(describing: event)])
switch event {
case .firstFrame: state = .playing
case .failed(let message):
@@ -38,6 +38,20 @@ final class DroneDockPreparationViewModel {
private(set) var shootErrorMessage: String?
/// 召唤写请求结果不明确时禁止重发,等待后续核对任务状态。
private(set) var summonOutcomeUnknown = false
/// 后端明确说明原任务已结束时,转为查看原任务,禁止继续重复首次召唤。
private(set) var summonRequiresTaskReview = false
/// 创建失败的用户提示;成功回执仅供业务与日志使用,不在页面输出。
var creationFailure: DroneDockPreparationFailure? {
guard createdTask == nil, let message = taskCreationErrorMessage else { return nil }
return DroneDockPreparationFailure(message: message, stage: .creation, outcomeUnknown: taskCreationOutcomeUnknown)
}
/// 召唤失败与创建失败分开表达,保留已经创建的任务。
var summonFailure: DroneDockPreparationFailure? {
guard let message = shootErrorMessage else { return nil }
return DroneDockPreparationFailure(message: message, stage: .summon, outcomeUnknown: summonOutcomeUnknown)
}
private let service: any DroneDockPreparationServing
private let planeStatusService: any DroneDockPlaneStatusServing
@@ -96,18 +110,18 @@ final class DroneDockPreparationViewModel {
var isTaskSelectionLocked: Bool {
isCreatingTask || isSummoning || isPerformingPrimaryAction || hasCreatedTask || taskCreationOutcomeUnknown
}
/// 仅展示真实返回的 data JSON,不拼造业务包裹或召唤结果。
/// 为诊断保留实际 data JSON,正式准备页不展示此内容。
var creationDataJSON: String? { createdTask?.dataJSON }
/// 仅保留 shoot 实际返回的 data;缺失时不拼造成功 JSON。
var shootDataJSON: String? { shootResponse?.dataJSON }
/// 创建回执携带的最新订单摘要优先于创建前购买摘要。
var latestOrderSummary: DroneDockHomeOrder? { createdTask?.order ?? projectInfo?.order }
/// 召唤已明确受理后只允许查看原任务,导航与再次提交召唤分开判断。
/// 已受理或后端明确要求核对已结束的任务时允许查看,导航不重复提交召唤。
var canOpenShootingTask: Bool {
context.canLoad && !creationContextInvalidated && !isLoading && !isCreatingTask
&& !isSummoning && !isPerformingPrimaryAction && !taskCreationOutcomeUnknown
&& !summonOutcomeUnknown && hasSubmittedSummon && shootResponse != nil
&& !summonOutcomeUnknown && ((hasSubmittedSummon && shootResponse != nil) || summonRequiresTaskReview)
&& (createdTask?.taskID ?? 0) > 0
}
@@ -115,7 +129,7 @@ final class DroneDockPreparationViewModel {
var isPrimaryActionEnabled: Bool {
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
!isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown,
!hasSubmittedSummon, !summonOutcomeUnknown else { return false }
!hasSubmittedSummon, !summonOutcomeUnknown, !summonRequiresTaskReview else { return false }
if let createdTask { return createdTask.taskID > 0 }
return canCreateTask
}
@@ -166,6 +180,7 @@ final class DroneDockPreparationViewModel {
let response = try await shootService.shoot(taskID: taskID)
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
shootResponse = response
DroneDockDiagnostics.event("summon.receipt_accepted", taskID: taskID)
hasSubmittedSummon = true
summonOutcomeUnknown = false
} catch {
@@ -177,6 +192,7 @@ final class DroneDockPreparationViewModel {
shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if case APIError.serverCode = error {
shootErrorMessage = error.localizedDescription
summonRequiresTaskReview = DroneDockPreparationFailure.requiresTaskReview(error.localizedDescription)
} else {
markSummonUnknown(reason: error.localizedDescription)
}
@@ -195,6 +211,7 @@ final class DroneDockPreparationViewModel {
if creationContextInvalidated {
shootResponse = nil
shootErrorMessage = nil
summonRequiresTaskReview = false
}
}
@@ -247,6 +264,7 @@ final class DroneDockPreparationViewModel {
throw APIError.decodeFailed("创建回执与当前订单或项目不一致,请核对任务")
}
createdTask = response
DroneDockDiagnostics.event("create.receipt_accepted", taskID: response.taskID)
hasCreatedTask = true
taskCreationOutcomeUnknown = false
} catch {
@@ -430,7 +448,7 @@ final class DroneDockPreparationViewModel {
var primaryButtonTitle: String {
if isCreatingTask { return "正在创建任务…" }
if isSummoning { return "正在召唤无人机…" }
if hasSubmittedSummon { return "查看拍摄任务" }
if hasSubmittedSummon || summonRequiresTaskReview { return "查看拍摄任务" }
if !allowsTaskSubmission { return "仅限模拟调试" }
if summonOutcomeUnknown { return "召唤结果待核对" }
if hasCreatedTask { return shootErrorMessage == nil ? "确认并召唤" : "重试召唤" }
@@ -445,13 +463,13 @@ final class DroneDockPreparationViewModel {
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 }
if createdTask != nil {
if hasSubmittedSummon { return "召唤请求已提交,请等待任务状态更新" }
if let summonFailure { return summonFailure.message }
if summonOutcomeUnknown { return "召唤结果待核对,请勿重复提交" }
return "任务 \(createdTask.taskID) 已创建,等待召唤"
return "任务已创建,等待召唤"
}
if let taskCreationErrorMessage { return taskCreationErrorMessage }
if let creationFailure { return creationFailure.message }
if taskCreationOutcomeUnknown { return "创建结果待核对,请勿重复提交" }
if isLoading { return "正在获取拍摄准备信息" }
if let errorMessage { return errorMessage }
@@ -555,11 +573,13 @@ final class DroneDockPreparationViewModel {
}
private func markSummonUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("summon.outcome_unknown", taskID: createdTask?.taskID)
summonOutcomeUnknown = true
shootErrorMessage = (reason.map { "\($0)。" } ?? "") + "召唤结果待核对,请先核对任务状态,勿重复提交"
}
private func markTaskCreationUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("taskcreation.outcome_unknown", taskID: createdTask?.taskID)
taskCreationOutcomeUnknown = true
taskCreationErrorMessage = (reason.map { "\($0)。" } ?? "") + "创建结果待核对,请先查看订单任务,勿重复提交"
}
@@ -1,6 +1,6 @@
import Foundation
/// 拍摄任务状态及可选控制流程,始终复用同一任务;禁飞调试仅为本地模拟注入操作服务。
/// 拍摄任务状态及可选控制流程,始终复用同一任务;Release 真实入口与隔离模拟入口按策略注入操作服务。
final class DroneDockShootingTaskViewModel {
/// 页面绑定的账号、景区和门店身份。
let context: DroneDockHomeContext
@@ -62,7 +62,7 @@ final class DroneDockShootingTaskViewModel {
// 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。
private var pendingAcceptedCommands: Set<DroneDockSafetyCommand> = []
/// 默认只读;仅显式注入模拟操作服务时开放对应动作,当前正式入口不注入。
/// 默认只读;仅显式注入操作服务时开放对应动作,Release 入口按授权注入。
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
service: any DroneDockShootingServing,
startService: (any DroneDockStartShooting)? = nil,
@@ -85,6 +85,18 @@ final class DroneDockShootingTaskViewModel {
await refreshSnapshot(allowWhileStarting: false)
}
/// 后端建议间隔限制为 2~30 秒;缺失或无效时默认 5 秒,从上次请求结束后计时。
var pollIntervalNanoseconds: UInt64 {
let hint = response?.planeStatus?.pollHintMS ?? 5_000
return UInt64(min(max(hint > 0 ? hint : 5_000, 2_000), 30_000)) * 1_000_000
}
/// 身份失效或缺少任务信息时停止安排下一次读取。
var canContinuePolling: Bool {
!identityInvalidated && context.canLoad && taskID > 0
&& DroneDockHomeMetric.usableText(order.orderNumber) != nil
}
@MainActor
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
allowWhileResummoning: Bool = false) async {
@@ -114,6 +126,12 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [
"phase": presentation.phase.rawValue,
"plane_id": value.currentPlane?.id as Any? ?? NSNull(),
"can_execute": value.executeGate?.canExecute as Any? ?? NSNull(),
"primary_action": value.executeGate?.primaryAction as Any? ?? NSNull()
])
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
@@ -121,6 +139,9 @@ final class DroneDockShootingTaskViewModel {
} catch {
guard accepts(requestGeneration) else { return }
errorMessage = error is CancellationError ? nil : error.localizedDescription
DroneDockDiagnostics.event("shooting.refresh_failed", taskID: taskID, fields: [
"retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error)
])
}
}
@@ -149,7 +170,7 @@ final class DroneDockShootingTaskViewModel {
}
}
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
@@ -161,7 +182,7 @@ final class DroneDockShootingTaskViewModel {
&& (response?.currentPlane?.id ?? 0) > 0
}
/// 提交一次开拍并单次读取同任务;失败保留原快照,不轮询、不重建、不自动重发。
/// 提交一次开拍并单次读取同任务;失败保留原快照,不重建、不自动重发控制请求。
@MainActor
func startShooting(onStateChange: @escaping @MainActor () -> Void = {}) async {
guard canStartShooting, let startService else { return }
@@ -200,6 +221,7 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("开始拍摄回执与当前任务或飞机不一致,请先核对任务状态")
}
startResponse = value
DroneDockDiagnostics.event("start.receipt_accepted", taskID: taskID)
hasSubmittedStart = true
startOutcomeUnknown = false
onStateChange()
@@ -287,6 +309,7 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("安全指令回执与当前任务或指令不一致,请先核对任务状态")
}
commandResponse = value
DroneDockDiagnostics.event("command.receipt_accepted", taskID: taskID)
pendingAcceptedCommands.insert(command)
commandOutcomeUnknown = false
onStateChange()
@@ -363,6 +386,7 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("重新召唤回执与当前任务或订单不一致,请先核对任务状态")
}
resummonResponse = value
DroneDockDiagnostics.event("resummon.receipt_accepted", taskID: taskID)
hasSubmittedResummon = true
resummonOutcomeUnknown = false
awaitingResummonSnapshot = true
@@ -557,6 +581,7 @@ final class DroneDockShootingTaskViewModel {
}
private func markResummonUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("resummon.outcome_unknown", taskID: taskID)
resummonOutcomeUnknown = true
resummonErrorMessage = (reason.map { "\($0)。" } ?? "") + "重新召唤结果待核对,请刷新任务状态,勿重复提交"
}
@@ -575,11 +600,13 @@ final class DroneDockShootingTaskViewModel {
}
private func markCommandUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("command.outcome_unknown", taskID: taskID)
commandOutcomeUnknown = true
commandErrorMessage = (reason.map { "\($0)。" } ?? "") + "安全指令结果待核对,请刷新任务状态,勿重复提交"
}
private func markStartUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("start.outcome_unknown", taskID: taskID)
startOutcomeUnknown = true
startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交"
}
@@ -100,18 +100,41 @@ final class ScenicMaterialDownloadService {
/// 检查 HTTP 状态与非空响应文件的空境原片下载器。
struct ScenicMaterialURLSessionDownloader: CloudFileDownloading {
private let session: URLSession
private let logSink: @Sendable (String) -> Void
/// 注入 URLSession 便于使用 URLProtocol 验证状态码及错误响应。
init(session: URLSession = .shared) { self.session = session }
init(session: URLSession = .shared, logSink: @escaping @Sendable (String) -> Void = DroneDockDiagnostics.write) {
self.session = session
self.logSink = logSink
}
/// 下载到唯一临时路径;失败响应及取消下载均清理 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)
let trace = DroneDockFileTransferTrace(operation: "file_download", method: "GET", remoteURL: url)
logSink(trace.message("request.started"))
let temporaryURL: URL
let response: URLResponse
do {
let delegate = ScenicMaterialDownloadProgress(onProgress: onProgress)
(temporaryURL, response) = try await session.download(from: url, delegate: delegate)
} catch {
let cancelled = error is CancellationError || (error as? URLError)?.code == .cancelled
logSink(trace.message(cancelled ? "request.cancelled" : "request.failed",
fields: DroneDockDiagnostics.errorFields(error)))
throw error
}
defer { try? FileManager.default.removeItem(at: temporaryURL) }
let receivedSize = (try? FileManager.default.attributesOfItem(atPath: temporaryURL.path)[.size] as? NSNumber)?.int64Value ?? 0
logSink(trace.message("response.received", fields: [
"http_status": (response as? HTTPURLResponse)?.statusCode ?? 0,
"response_headers": (response as? HTTPURLResponse)?.allHeaderFields.reduce(into: [String: String]()) {
$0[String(describing: $1.key)] = String(describing: $1.value)
} ?? [:],
"bytes": receivedSize, "content_type": response.mimeType ?? "unknown", "body": "<binary omitted>"
]))
try Task.checkCancellation()
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
throw ScenicMaterialDownloadError.httpFailure((response as? HTTPURLResponse)?.statusCode ?? 0)
@@ -181,6 +181,14 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
/// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。
private func createSelectedTask() {
DroneDockDiagnostics.event("preparation.confirm_tapped", taskID: viewModel.createdTask?.taskID, fields: [
"order_number": viewModel.order.orderNumber as Any? ?? NSNull(),
"scenic_id": viewModel.context.scenicID,
"spot_id": viewModel.selectedSpotID as Any? ?? NSNull(),
"air_line_id": viewModel.selectedRouteID as Any? ?? NSNull(),
"enabled": viewModel.isPrimaryActionEnabled,
"blocked": viewModel.isTaskSubmissionBlocked
])
guard !isRefreshing, !isStartingCreation else { return }
if viewModel.canOpenShootingTask {
_ = openShootingTask(automatically: false)
@@ -199,17 +207,29 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
guard let self,
let path = self.dataSource.indexPath(for: .shootResult) ?? self.dataSource.indexPath(for: .creationResult) else { return }
self.collectionView.scrollToItem(at: path, at: .top, animated: true)
self.showFilingFailureIfNeeded()
}
}
}
/// 只在准备页可见且召唤已成功时导航一次;返回后允许主动查看同一任务。
/// 报备问题在明确提交失败后提示一次,后台及设备轮询不会反复弹窗。
private func showFilingFailureIfNeeded() {
guard isPageVisible, isApplicationActive, presentedViewController == nil,
let failure = viewModel.summonFailure ?? viewModel.creationFailure,
failure.requiresFiling else { return }
let alert = UIAlertController(title: failure.title, message: failure.message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "我知道了", style: .default))
present(alert, animated: true)
}
/// 成功后自动导航一次;失败的已结束任务只在用户明确点击时查看原任务。
@discardableResult
private func openShootingTask(automatically: Bool) -> Bool {
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
let taskID = viewModel.createdTask?.taskID,
let navigationController, navigationController.topViewController === self,
!automatically || automaticallyOpenedTaskID != taskID else { return false }
!automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else { return false }
DroneDockDiagnostics.event("navigation.open_task", taskID: taskID)
automaticallyOpenedTaskID = taskID
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
navigationController.pushViewController(controller, animated: true)
@@ -284,17 +304,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
return cell
case .creationResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.apply(task: self.viewModel.createdTask, errorMessage: self.viewModel.taskCreationErrorMessage,
outcomeUnknown: self.viewModel.taskCreationOutcomeUnknown)
if let failure = self.viewModel.creationFailure {
cell.apply(failure: failure, identifier: "drone.preparation.creationResponse")
}
return cell
case .shootResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.applyShoot(taskID: self.viewModel.createdTask?.taskID,
dataJSON: self.viewModel.shootDataJSON,
errorMessage: self.viewModel.shootErrorMessage,
isLoading: self.viewModel.isSummoning,
hasSucceeded: self.viewModel.shootResponse != nil,
outcomeUnknown: self.viewModel.summonOutcomeUnknown)
if let failure = self.viewModel.summonFailure {
cell.apply(failure: failure, identifier: "drone.preparation.shootResponse")
}
return cell
case .emptyPoints, .emptyRoutes, .status:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
@@ -344,11 +362,10 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
} else {
snapshot.appendItems([.status], toSection: .status)
}
if viewModel.createdTask != nil || (viewModel.errorMessage == nil && viewModel.projectInfo != nil && viewModel.taskCreationErrorMessage != nil) {
if viewModel.creationFailure != nil {
snapshot.appendItems([.creationResult], toSection: .creationResult)
}
if viewModel.createdTask != nil,
viewModel.isSummoning || viewModel.shootResponse != nil || viewModel.shootErrorMessage != nil {
if viewModel.summonFailure != nil {
snapshot.appendItems([.shootResult], toSection: .shootResult)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
@@ -360,7 +377,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|| previous.itemIdentifiers.contains(.emptyPoints) != snapshot.itemIdentifiers.contains(.emptyPoints)
|| previous.itemIdentifiers.contains(.emptyRoutes) != snapshot.itemIdentifiers.contains(.emptyRoutes)
|| previousRouteCount != snapshot.numberOfItems(inSection: .routes)
if layoutChanged { collectionView.collectionViewLayout.invalidateLayout() }
if layoutChanged || viewModel.projectInfo != nil { collectionView.collectionViewLayout.invalidateLayout() }
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
guard let self else { return }
let kind = UICollectionView.elementKindSectionHeader
@@ -374,21 +391,21 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, _ in
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let self, let section = Section(rawValue: index) else { return nil }
let height: NSCollectionLayoutDimension
let width: NSCollectionLayoutDimension
switch section {
case .order: height = .estimated(100); width = .fractionalWidth(1)
case .points:
height = .absolute(self.viewModel.spots.isEmpty ? 150 : 64)
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(160)
height = .absolute(self.viewModel.spots.isEmpty ? 150 : DronePreparationPointCell.preferredHeight(
names: self.viewModel.spots.map(\.name), width: 200))
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(200)
case .routes:
height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64)
width = .fractionalWidth(1)
case .status: height = .absolute(160); width = .fractionalWidth(1)
case .creationResult: height = .absolute(380); width = .fractionalWidth(1)
case .shootResult: height = .absolute(420); width = .fractionalWidth(1)
case .creationResult, .shootResult: height = .estimated(100); width = .fractionalWidth(1)
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
@@ -402,7 +419,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
&& (section == .points || (section == .routes && !self.viewModel.spots.isEmpty))
if showsHeading {
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : 64)),
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : DronePreparationHeadingView.preferredHeight(
title: self.viewModel.selectedSpot.map { "\($0.name)的航线" } ?? "拍摄航线",
detail: "共 \(self.viewModel.routes.count) 条", width: environment.container.effectiveContentSize.width - 32))),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
}
return layout
@@ -3,7 +3,7 @@ import UIKit
/// 组装真实拍摄任务页;构造时不发请求,页面出现后才读取同一任务。
@MainActor
enum DroneDockShootingTaskEntry {
/// 使用已有任务读取状态,Release 可手动图传;不注入任务创建或飞控服务。
/// 使用已有任务读取状态;Release 注入已授权的真实控制,Debug 保持只读。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
let client = NetworkServices.shared.apiClient
@@ -14,7 +14,10 @@ enum DroneDockShootingTaskEntry {
currentContext: { DroneDockHomeViewController.currentContext() })
return DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
context: context, taskID: taskID, order: order,
service: DroneDockShootingAPI(client: NetworkServices.shared.apiClient),
service: DroneDockShootingAPI(client: client),
startService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockStartShootAPI(client: client),
commandService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockCommandAPI(client: client),
resummonService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockShootAPI(client: client),
currentContext: { DroneDockHomeViewController.currentContext() }
), liveViewModel: live)
}
@@ -1,7 +1,7 @@
import SnapKit
import UIKit
/// 拍摄任务页:正式入口读取状态并手动开启图传,飞控仅在隔离模拟入口注入。
/// 拍摄任务页:前台轮询状态、手动图传;Release 开放已授权控制,Debug 仅模拟控制。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
@@ -23,6 +23,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var bottomInset: CGFloat = -1
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private let simulationRecordsProvider: (@MainActor () -> String)?
private let shootingPollDelay: @Sendable (UInt64) async throws -> Void
private var pollTask: Task<Void, Never>?
private var pollGeneration = 0
private var refreshTask: Task<Void, Never>?
private var startTask: Task<Void, Never>?
private var commandTask: Task<Void, Never>?
@@ -41,12 +44,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil) {
simulationRecordsProvider: (@MainActor () -> String)? = nil,
shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
context: viewModel.context, taskID: viewModel.taskID,
currentContext: { DroneDockHomeViewController.currentContext() })
self.simulationRecordsProvider = simulationRecordsProvider
self.shootingPollDelay = shootingPollDelay
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
@@ -61,6 +66,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit {
pollTask?.cancel()
refreshTask?.cancel()
startTask?.cancel()
commandTask?.cancel()
@@ -186,10 +192,11 @@ final class DroneDockShootingTaskViewController: BaseViewController {
name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// 每次完整进入任务页只查询一次,不定时重读同一任务。
/// 完整进入任务页立即读取,随后仅在前台可见时轮询同一任务。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
logEvent("page.appeared")
isApplicationActive = UIApplication.shared.applicationState == .active
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
@@ -199,6 +206,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
logEvent("page.disappeared")
cancelRefresh()
stopLive()
}
@@ -227,6 +235,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func primaryActionTriggered() {
logEvent("action.primary", fields: ["action": String(describing: viewModel.presentation.action),
"enabled": viewModel.presentation.isActionEnabled])
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
@@ -265,12 +275,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
present(alert, animated: true)
}
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
private func refreshTaskIfVisible() {
/// 前台可见时串行读取;轮询失败保留旧快照,下个周期再读,不重复弹出提示。
private func refreshTaskIfVisible(isPolling: Bool = false) {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
!isResummoningAction, !viewModel.isResummoning else { return }
cancelScheduledPoll()
logEvent("shooting.refresh", fields: ["trigger": isPolling ? "poll" : "page_or_manual", "live_battery": 0])
requestGeneration &+= 1
let generation = requestGeneration
isRequesting = true
@@ -283,13 +295,39 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
if self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.scheduleNextPoll()
if !isPolling, self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
}
}
}
/// 每次读取或控制流程结束后仅安排一个可取消的延时,不持有页面等待计时结束。
private func scheduleNextPoll() {
cancelScheduledPoll()
guard isPageVisible, isApplicationActive, viewModel.canContinuePolling,
!isRequesting, !isStartingAction, !isSendingSafetyAction, !isResummoningAction else { return }
let generation = pollGeneration
let delay = shootingPollDelay
let interval = viewModel.pollIntervalNanoseconds
logEvent("poll.scheduled", fields: ["delay_ms": interval / 1_000_000])
pollTask = Task { @MainActor [weak self] in
do { try await delay(interval) } catch { return }
guard !Task.isCancelled, let self, self.pollGeneration == generation else { return }
self.pollTask = nil
self.refreshTaskIfVisible(isPolling: true)
}
}
private func cancelScheduledPoll() {
if pollTask != nil { logEvent("poll.cancelled") }
pollGeneration &+= 1
pollTask?.cancel()
pollTask = nil
}
private func cancelRefresh() {
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
@@ -310,6 +348,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
private func startShootingIfAllowed() {
guard !isStartingAction, !isSendingSafetyAction, !isResummoningAction, viewModel.canStartShooting else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isStartingAction = true
@@ -322,6 +361,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.startTask = nil
self.isStartingAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.startErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
@@ -330,11 +370,12 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
}
/// 重召唤只在显式模拟入口开放;点击后锁定按钮,使用原任务 ID,并由状态回查更新页面。
/// 重召唤使用原任务 ID,回执后再查询状态,避免从受理结果推断设备已到达。
private func resummonIfAllowed() {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
guard allowsControlActions, isPageVisible, isApplicationActive,
!isResummoningAction, !isStartingAction, !isSendingSafetyAction,
!isRequesting, viewModel.canResummon else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isResummoningAction = true
@@ -347,12 +388,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.resummonTask = nil
self.isResummoningAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.resummonErrorMessage {
self.showToast(error)
} else if self.viewModel.hasSubmittedResummon, let error = self.viewModel.errorMessage {
self.showToast("模拟重召唤已受理,状态刷新失败:\(error)")
self.showToast("重召唤已受理,状态刷新失败:\(error)")
} else if self.viewModel.hasSubmittedResummon {
self.showToast("本地模拟重召唤已受理,未发送设备指令")
self.showToast(self.simulationRecordsProvider != nil
? "本地模拟重召唤已受理,未发送设备指令" : "重召唤请求已受理,请等待任务状态更新")
} else if let error = self.viewModel.errorMessage {
self.showToast(error)
}
@@ -363,6 +406,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func refreshLiveIfVisible(automatically: Bool = false) {
guard !automatically || liveViewModel.loadsAutomatically else { return }
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
logEvent("live.request", fields: ["automatic": automatically])
liveGeneration &+= 1
let generation = liveGeneration
liveTask = Task { @MainActor [weak self] in
@@ -385,16 +429,20 @@ final class DroneDockShootingTaskViewController: BaseViewController {
feedPlaceholder.apply(liveViewModel)
}
/// 仅模拟入口响应安全按钮;返航会中断任务,先明确展示其含义再提交一次。
/// 返航会中断任务,先明确展示其含义再提交一次;Debug 只开放隔离模拟入口。
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)])
guard allowsControlActions, isPageVisible, isApplicationActive,
presentedViewController == nil, !isSendingSafetyAction, !isStartingAction,
!isResummoningAction, !isRequesting, viewModel.canSendCommand(command) else { return }
if command == .returnHome {
let alert = UIAlertController(title: "立即返航(本地模拟)",
message: "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。", preferredStyle: .alert)
let simulated = simulationRecordsProvider != nil
let alert = UIAlertController(title: simulated ? "立即返航(本地模拟)" : "立即返航",
message: simulated
? "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。"
: "返航会中断本次任务。取消返航也不会恢复已经中断的任务。确定立即返航?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "模拟返航", style: .destructive) { [weak self] _ in
alert.addAction(UIAlertAction(title: simulated ? "模拟返航" : "立即返航", style: .destructive) { [weak self] _ in
self?.sendSafetyCommand(command)
})
present(alert, animated: true)
@@ -405,9 +453,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
guard allowsControlActions, isPageVisible, isApplicationActive,
!isSendingSafetyAction, !isStartingAction, !isResummoningAction, !isRequesting,
viewModel.canSendCommand(command) else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isSendingSafetyAction = true
@@ -420,12 +469,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.commandTask = nil
self.isSendingSafetyAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.commandErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
self.showToast("模拟指令已受理,状态刷新失败:\(error)")
self.showToast("指令已受理,状态刷新失败:\(error)")
} else {
self.showToast("本地模拟指令已受理,未发送设备指令")
self.showToast(self.simulationRecordsProvider != nil
? "本地模拟指令已受理,未发送设备指令" : "指令已受理,请等待任务状态更新")
}
}
}
@@ -445,6 +496,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
@objc private func applicationWillResignActive() {
logEvent("app.inactive")
isApplicationActive = false
cancelRefresh()
stopLive()
@@ -453,9 +505,22 @@ final class DroneDockShootingTaskViewController: BaseViewController {
@objc private func applicationDidBecomeActive() {
guard !isApplicationActive else { return }
isApplicationActive = true
logEvent("app.active")
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
}
private func logEvent(_ name: String, fields: [String: Any] = [:]) {
var fields = fields
fields["source"] = simulationRecordsProvider == nil ? "task_page" : "local_simulation"
fields["scenic_id"] = viewModel.context.scenicID
fields["order_number"] = viewModel.order.orderNumber
DroneDockDiagnostics.event(name, taskID: viewModel.taskID, fields: fields)
}
private var allowsControlActions: Bool {
simulationRecordsProvider != nil || !DeviceCommandDebugPolicy.blocksFlightRequests
}
}
/// 以可选择的 JSON 文本展示本地模拟请求与回执,避免与真实接口联调混淆。
@@ -555,10 +620,11 @@ private final class DroneDockTaskSafetyView: UIView {
/// 保持两列固定布局,暂停/继续与返航/取消由快照中的指令白名单决定。
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool) {
let commands = model.availableSafetyCommands
let allowsControls = isSimulation || !DeviceCommandDebugPolicy.blocksFlightRequests
pauseCommand = commands.contains(.resume) ? .resume : .pause
returnCommand = commands.contains(.cancelReturn) ? .cancelReturn : .returnHome
header.text = model.commandOutcomeUnknown ? "安全控制 · 结果待核对"
: model.isSendingCommand ? "安全控制 · 本地模拟发送中"
: model.isSendingCommand ? (isSimulation ? "安全控制 · 本地模拟发送中" : "安全控制 · 指令发送中")
: isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制"
for (button, command) in [(pauseButton, pauseCommand), (returnButton, returnCommand)] {
let title: String
@@ -569,10 +635,10 @@ private final class DroneDockTaskSafetyView: UIView {
case .returnHome: title = "立即返航"; subtitle = "中断任务"
case .cancelReturn: title = "取消返航"; subtitle = "不恢复已中断任务"
}
let enabled = isSimulation && isInteractive && model.canSendCommand(command)
let detail = model.activeCommand == command ? "本地模拟发送中…"
let enabled = allowsControls && isInteractive && model.canSendCommand(command)
let detail = model.activeCommand == command ? (isSimulation ? "本地模拟发送中…" : "指令发送中…")
: model.commandOutcomeUnknown ? "结果待核对"
: !isSimulation || !commands.contains(command) ? "暂不可用" : subtitle
: !allowsControls || !commands.contains(command) ? "暂不可用" : subtitle
button.apply(title: title, subtitle: detail, enabled: enabled)
button.setControlSymbol(command == .resume ? "play.circle" : command == .pause ? "pause.circle"
: command == .cancelReturn ? "xmark.circle" : "arrow.uturn.backward")
@@ -1,12 +1,11 @@
import SnapKit
import UIKit
/// 在准备页展示任务创建或召唤请求的回执,保留 data 原文结构并支持滚动与选择文本。
/// 准备页业务失败卡片,完整换行展示原因,不展示成功回执或接口 JSON。
@MainActor
final class DroneDockTaskCreationResultCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let responseView = UITextView()
private let detailLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
@@ -14,23 +13,13 @@ final class DroneDockTaskCreationResultCell: UICollectionViewCell {
contentView.layer.cornerRadius = 10
titleLabel.numberOfLines = 0
detailLabel.numberOfLines = 0
responseView.backgroundColor = .clear
responseView.isEditable = false
responseView.isSelectable = true
responseView.alwaysBounceVertical = true
responseView.textContainerInset = .zero
responseView.textContainer.lineFragmentPadding = 0
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
[titleLabel, detailLabel, responseView].forEach(contentView.addSubview)
titleLabel.textColor = DroneDockStyle.warning
[titleLabel, detailLabel].forEach(contentView.addSubview)
titleLabel.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview().inset(12)
}
detailLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(6)
make.leading.trailing.equalTo(titleLabel)
}
responseView.snp.makeConstraints { make in
make.top.equalTo(detailLabel.snp.bottom).offset(12)
make.top.equalTo(titleLabel.snp.bottom).offset(8)
make.leading.trailing.equalTo(titleLabel)
make.bottom.equalToSuperview().inset(12)
}
@@ -39,42 +28,10 @@ final class DroneDockTaskCreationResultCell: UICollectionViewCell {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 成功保留完整 data,失败显示真实错误,不构造任务 ID 或成功响应。
func apply(task: DroneDockCreatedTask?, errorMessage: String?, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
if let task {
titleLabel.text = "任务已创建 · ID \(task.taskID)"
titleLabel.textColor = DroneDockStyle.success
detailLabel.text = "tasks/create 返回的 data"
responseView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
if responseView.text != task.dataJSON { responseView.text = task.dataJSON }
} else {
titleLabel.text = outcomeUnknown ? "任务创建结果待确认" : "任务创建未成功"
titleLabel.textColor = DroneDockStyle.warning
detailLabel.text = outcomeUnknown ? "请先核对订单任务,避免重复创建" : "接口返回的错误信息"
responseView.font = .systemFont(ofSize: 14)
responseView.text = errorMessage
}
responseView.textColor = DroneDockStyle.text
}
/// 展示 shoot 回执;提交成功不代表无人机已到达,结果未知不能引导直接重发。
func applyShoot(taskID: Int?, dataJSON: String?, errorMessage: String?, isLoading: Bool,
hasSucceeded: Bool, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.shootResponse"
let suffix = taskID.map { " · ID \($0)" } ?? ""
let title: String
if isLoading { title = "正在召唤无人机" }
else if hasSucceeded { title = "召唤请求已提交" }
else { title = outcomeUnknown ? "召唤结果待核对" : "召唤请求未成功" }
titleLabel.text = title + suffix
titleLabel.textColor = hasSucceeded ? DroneDockStyle.success : errorMessage == nil ? DroneDockStyle.text : DroneDockStyle.warning
if isLoading { detailLabel.text = "正在为已创建的任务提交召唤请求" }
else if hasSucceeded { detailLabel.text = "shoot 返回信息;飞行进度以任务状态为准" }
else { detailLabel.text = outcomeUnknown ? "请先核对任务状态,避免重复发送召唤" : "任务已保留,可重试召唤" }
responseView.font = dataJSON == nil ? .systemFont(ofSize: 14) : .monospacedSystemFont(ofSize: 12, weight: .regular)
let text = dataJSON ?? errorMessage ?? (hasSucceeded ? "接口已返回业务成功,未提供可展示的 data。" : "")
if responseView.text != text { responseView.text = text }
responseView.textColor = DroneDockStyle.text
/// 只接收面向用户的错误模型,成功 data 不进入视图层。
func apply(failure: DroneDockPreparationFailure, identifier: String) {
titleLabel.text = failure.title
detailLabel.text = failure.message
detailLabel.accessibilityIdentifier = identifier
}
}
@@ -58,7 +58,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
roomConfig.isAutoSubscribeVideo = false
let user = ByteRTCUserInfo()
user.userId = configuration.userID
DroneDockDiagnostics.event("rtc.join_requested", fields: ["engine_session": generation.uuidString])
let result = room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: roomConfig)
DroneDockDiagnostics.event("rtc.join_returned", fields: ["engine_session": generation.uuidString, "code": result])
guard result == 0 else {
onEvent(.failed("图传进房失败(\(result))")); stop(); return
}
@@ -93,6 +95,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
}
private func receive(_ event: DroneDockVolcEvent, roomID: String) {
// 不把 SDK 回调对象、房间 ID、用户 ID 或 extraInfo 原样写入日志。
DroneDockDiagnostics.event("rtc.callback", fields: ["engine_session": generation.uuidString, "result": event.diagnosticValue])
switch event {
case .published(let id, let sourceRoom, let index, let published):
guard sourceRoom == roomID, index == 0 else { return }
@@ -107,6 +111,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
canvas.renderMode = .fit
let renderResult = engine?.setRemoteVideoCanvas(id, withCanvas: canvas)
let subscribeResult = room?.subscribeStreamVideo(id, subscribe: true)
DroneDockDiagnostics.event("rtc.subscribe_returned", fields: ["engine_session": generation.uuidString,
"render_code": renderResult as Any? ?? NSNull(), "subscribe_code": subscribeResult as Any? ?? NSNull()])
if renderResult != 0 || subscribeResult != 0 { onEvent?(.failed("图传订阅失败,请重试")) }
case .frame(let id):
guard streamID == id else { return }
@@ -114,6 +120,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
onEvent?(.firstFrame)
case .failed(let code): onEvent?(.failed("图传连接失败(\(code)),请重试"))
case .expired: onEvent?(.expired)
case .roomState: break
}
}
}
@@ -124,6 +131,18 @@ private enum DroneDockVolcEvent: Sendable {
case frame(String)
case failed(Int)
case expired
case roomState(Int)
/// 仅输出事件种类及错误码,不含 SDK 身份和凭证。
var diagnosticValue: String {
switch self {
case .published(_, _, let index, let published): return "published(index=\(index),published=\(published))"
case .frame: return "first_frame"
case .failed(let code): return "failed(code=\(code))"
case .expired: return "expired"
case .roomState(let code): return "room_state(code=\(code))"
}
}
}
/// SDK 回调桥接;所有 UI 与引擎操作由上层切回主 Actor 后执行。
@@ -138,6 +157,7 @@ private final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, Byte
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String,
state: Int, extraInfo: String) {
emit(.roomState(state))
if state != 0 { emit(.failed(state)) }
}
@@ -108,21 +108,24 @@ final class DronePreparationPointCell: UICollectionViewCell {
thumbnail.backgroundColor = DroneDockStyle.background
thumbnail.layer.cornerRadius = 5
thumbnail.clipsToBounds = true
[thumbnail, nameLabel, countLabel].forEach(contentView.addSubview)
nameLabel.numberOfLines = 0
nameLabel.lineBreakMode = .byWordWrapping
nameLabel.accessibilityIdentifier = "drone.preparation.point.name"
let labels = UIStackView(arrangedSubviews: [nameLabel, countLabel])
labels.axis = .vertical
labels.spacing = 6
[thumbnail, labels].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(8)
make.centerY.equalToSuperview()
make.size.equalTo(48)
}
nameLabel.snp.makeConstraints { make in
make.bottom.equalTo(contentView.snp.centerY).offset(-3)
labels.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.top.greaterThanOrEqualToSuperview().offset(8)
make.bottom.lessThanOrEqualToSuperview().inset(8)
make.leading.equalTo(thumbnail.snp.trailing).offset(8)
make.trailing.equalToSuperview().inset(6)
}
countLabel.snp.makeConstraints { make in
make.top.equalTo(contentView.snp.centerY).offset(3)
make.leading.equalTo(nameLabel)
make.trailing.equalToSuperview().inset(5)
make.trailing.equalToSuperview().inset(8)
}
isAccessibilityElement = true
}
@@ -130,6 +133,18 @@ final class DronePreparationPointCell: UICollectionViewCell {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 横向同组卡片采用最长名称所需的高度,名称完整换行且不压缩字号。
static func preferredHeight(names: [String], width: CGFloat) -> CGFloat {
let label = DroneDockStyle.label(size: 13, weight: .semibold)
label.numberOfLines = 0
let nameWidth = max(1, width - 72)
let nameHeight = names.map { name -> CGFloat in
label.text = name
return label.sizeThatFits(CGSize(width: nameWidth, height: .greatestFiniteMagnitude)).height
}.max() ?? 0
return max(64, ceil(nameHeight) + 6 + ceil(UIFont.systemFont(ofSize: 11).lineHeight) + 16)
}
/// 展示点位名称与次数,已拍摄的点位仍保持可选择。
func apply(point: DroneShootingPoint, selected: Bool) {
thumbnail.kf.cancelDownloadTask()
@@ -145,7 +160,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
accessibilityIdentifier = "drone.preparation.point.\(point.id)"
}
/// 展示已购点位与可用性;点位已拍次数缺失时保持未知占位。
/// 展示已购点位与可用性;无拍摄记录时显示“未拍摄”。
func apply(spot: DroneDockPurchasedSpot, selected: Bool) {
nameLabel.text = spot.name
thumbnail.kf.cancelDownloadTask()
@@ -160,7 +175,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
if spot.available != true {
countLabel.text = spot.available == false ? "拍摄点不可用" : "可用性待确认"
} else {
countLabel.text = "已拍摄 — 次"
countLabel.text = "未拍摄"
}
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white
contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor
@@ -331,13 +346,16 @@ final class DronePreparationHeadingView: UICollectionReusableView {
stack.axis = .horizontal
stack.alignment = .firstBaseline
stack.spacing = 12
titleLabel.numberOfLines = 0
titleLabel.accessibilityIdentifier = "drone.preparation.heading.title"
addSubview(stack)
stack.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(4)
make.trailing.equalToSuperview()
make.centerY.equalToSuperview().offset(3)
}
titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
detailLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
accessibilityTraits = .header
isAccessibilityElement = true
}
@@ -352,6 +370,16 @@ final class DronePreparationHeadingView: UICollectionReusableView {
detailLabel.isHidden = detail == nil
accessibilityLabel = [title, detail].compactMap { $0 }.joined(separator: ",")
}
/// 为长点位名称预留完整标题高度,右侧航线数量保持可见。
static func preferredHeight(title: String, detail: String, width: CGFloat) -> CGFloat {
let label = DroneDockStyle.label(size: 18, weight: .semibold)
label.numberOfLines = 0
label.text = title
let detailWidth = (detail as NSString).size(withAttributes: [.font: UIFont.systemFont(ofSize: 13)]).width
let titleWidth = max(1, width - 4 - ceil(detailWidth) - 24)
return max(64, ceil(label.sizeThatFits(CGSize(width: titleWidth, height: .greatestFiniteMagnitude)).height) + 26)
}
}
/// 无点位或无航线时保留就地提示,不增加额外的选择弹窗。
@@ -5,8 +5,8 @@ import XCTest
/// 验证禁飞调试在进入传输层之前拦截真实操作,所有探针本身也不联网。
@MainActor
final class DeviceCommandDebugPolicyTests: XCTestCase {
/// 飞行限制不再由 Debug/Release 决定,正式包也不得用于创建待飞任务或飞控。
func testFlightRestrictionIsIndependentOfLivePlaybackBuildMode() {
/// 用户授权 Release 真机操作,当前模拟器 Debug 测试仍必须禁止真实飞控。
func testDebugKeepsFlightRestriction() {
XCTAssertTrue(DeviceCommandDebugPolicy.blocksFlightRequests)
}
/// 即使切到生产地址或未来新增机场动作,默认传输也不能发送设备操作。
@@ -0,0 +1,165 @@
import Foundation
import XCTest
@testable import suixinkan
/// Release 共用日志通路的原值、请求关联和异常覆盖;全部使用内存传输。
@MainActor
final class DroneDockDiagnosticsTests: XCTestCase {
/// 每个已接入业务接口均输出完整请求和响应,重复轮询也不去重;普通日志开关不屏蔽机巢诊断。
func testAllModuleEndpointsLogPayloadAndRepeatedResponses() async throws {
let prefix = "/api/yf-handset-app/photog/multi-plane/"
let paths = ["orders", "today-stats", "projects", "pay-code", "receipts", "project-info",
"tasks/create", "orders/detail", "tasks", "tasks/film", "orders/confirm-code"].map { prefix + $0 }
+ ["home", "plane-status", "shoot", "shooting", "start-shoot", "command", "live", "status"].map { "/api/app/airport/" + $0 }
+ ["/api/app/scenic-media/sessions", "/api/app/scenic-media/session-detail"]
let text = String(repeating: "完整业务数据", count: 300)
let response = try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": ["detail": text]])
for path in paths {
let session = MockURLSession(responses: [response, response])
var logs: [String] = []
var debug: [String] = []
let client = APIClient(environment: .testing, session: session, debugLogSink: { debug.append($0) },
droneDockLogSink: { logs.append($0) })
for _ in 0..<2 {
let _: DroneDockHomeJSONValue = try await client.send(APIRequest(
method: .post, path: path, queryItems: [.init(name: "scenic_id", value: "123")],
body: ["task_id": 501], logsPayload: false))
}
let objects = try logs.map { try XCTUnwrap(JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any]) }
let starts = objects.filter { $0["event"] as? String == "request.started" }
let responses = objects.filter { $0["event"] as? String == "response.received" }
XCTAssertEqual(starts.count, 2, path)
XCTAssertEqual(responses.count, 2, path)
XCTAssertEqual(Set(starts.compactMap { $0["request_id"] as? String }).count, 2)
XCTAssertEqual((starts.first?["body"] as? [String: Int])?["task_id"], 501)
XCTAssertEqual(starts.first?["query"] as? [[String: String]], [["scenic_id": "123"]])
let envelope = try XCTUnwrap(responses.first?["body"] as? [String: Any])
XCTAssertEqual((envelope["data"] as? [String: String])?["detail"], text)
XCTAssertTrue(debug.isEmpty, path)
}
}
/// STS 按用户要求输出完整配置及临时凭证,且不改写业务响应。
func testSharedSTSLogsConfigurationAndCredentials() async throws {
let payload = Data(#"{"code":100000,"data":{"base_url":"https://example.com","endpoint":"oss-test","region":"cn-test","bucket":"test-bucket","expire_seconds":3600,"credentials":{"access_key_id":"SECRET_KEY","access_key_secret":"SECRET_SECRET","security_token":"SECRET_TOKEN"}}}"#.utf8)
var logs: [String] = []
var debug: [String] = []
let client = APIClient(environment: .testing, session: MockURLSession(responses: [payload]),
debugLogSink: { debug.append($0) }, droneDockLogSink: { logs.append($0) })
let result = try await UploadAPI(client: client).aliyunOSSBucket(bucket: "default")
XCTAssertEqual(result.credentials.accessKeyId, "SECRET_KEY")
XCTAssertTrue(debug.isEmpty)
let text = logs.joined()
for secret in ["SECRET_KEY", "SECRET_SECRET", "SECRET_TOKEN"] { XCTAssertTrue(text.contains(secret)) }
XCTAssertTrue(text.contains("test-bucket"))
XCTAssertTrue(text.contains("3600"))
XCTAssertTrue(text.contains("response.received"))
XCTAssertTrue(text.contains("default"))
}
/// 文件日志保留完整签名地址、大小、状态及关联 ID。
func testFileTransferTraceRetainsCorrelationAndSignedAddress() throws {
let trace = DroneDockFileTransferTrace(operation: "file_download", method: "GET",
remoteURL: URL(string: "https://example.test/private-name.mp4?signature=SECRET"))
let start = trace.message("request.started")
let end = trace.message("response.received", fields: ["http_status": 200, "bytes": 1024])
let objects = try [start, end].map { try XCTUnwrap(JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any]) }
XCTAssertEqual(objects[0]["request_id"] as? String, objects[1]["request_id"] as? String)
XCTAssertEqual(objects[1]["http_status"] as? Int, 200)
XCTAssertEqual(objects[1]["bytes"] as? Int, 1024)
XCTAssertTrue(end.contains("example.test"))
XCTAssertTrue((start + end).contains("SECRET"))
XCTAssertTrue((start + end).contains("private-name"))
}
/// 请求 Header、RTC URL 和嵌套字段均按原值记录;实际请求和响应保持不变。
func testLiveResponseIsCompleteAndCorrelatedWithoutChangingPayload() async throws {
let body: [String: Any] = ["code": 100000, "data": [
"order_flight_task_id": 501, "playable": true,
"play": ["url_type": "volc", "url": "app_id=one&token=SECRET_RTC&room_id=room"],
"token": "SECRET_BODY", "phone": "13912345678", "airport_sn": "SECRET_SN",
"nested": [["Authorization": "SECRET_NESTED"]]
]]
let session = MockURLSession(responses: [try JSONSerialization.data(withJSONObject: body)])
var logs: [String] = []
var debug: [String] = []
let client = APIClient(environment: .testing, session: session, debugLogSink: { debug.append($0) },
droneDockLogSink: { logs.append($0) })
client.bindAuthTokenProvider { "SECRET_AUTH" }
let result: DroneDockHomeJSONValue = try await client.send(APIRequest(
method: .get, path: "/api/app/airport/live", queryItems: [.init(name: "id", value: "501")], logsPayload: false))
XCTAssertTrue(String(describing: result).contains("SECRET_RTC"), "日志不修改业务响应")
XCTAssertEqual(session.requests.first?.value(forHTTPHeaderField: "token"), "SECRET_AUTH")
XCTAssertTrue(debug.isEmpty, "机巢日志不重复进入旧日志通路")
let text = logs.joined()
for value in ["SECRET_RTC", "SECRET_BODY", "13912345678", "SECRET_SN", "SECRET_NESTED", "SECRET_AUTH"] {
XCTAssertTrue(text.contains(value), value)
}
XCTAssertTrue(text.contains("volc"))
XCTAssertTrue(text.contains("501"))
XCTAssertTrue(text.contains("local_simulation"))
let objects = try logs.map { try XCTUnwrap(JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any]) }
XCTAssertEqual(objects.compactMap { $0["event"] as? String }, ["request.started", "response.received", "response.decoded"])
XCTAssertEqual(Set(objects.compactMap { $0["request_id"] as? String }).count, 1)
XCTAssertTrue(objects.allSatisfy { $0["elapsed_ms"] != nil })
let response = try XCTUnwrap(objects.first { $0["event"] as? String == "response.received" })
XCTAssertTrue(NSDictionary(dictionary: try XCTUnwrap(response["body"] as? [String: Any])).isEqual(to: body))
XCTAssertNotNil(response["response_headers"])
XCTAssertFalse(text.contains("<redacted>"))
}
/// 区分服务端业务拒绝、HTTP 错误、解析失败、网络失败和主动取消。
func testErrorOutcomesAreVisible() async throws {
let cases: [(MockURLSession, String)] = [
(.init(responses: [try TestJSON.errorEnvelope(code: 100099, msg: "条件不满足")]), "business_rejected"),
(.init(responses: [Data("bad gateway".utf8)], statusCode: 502), "response.rejected"),
(.init(responses: [Data("invalid JSON".utf8)]), "decode_failed"),
(.init(results: [.failure(URLError(.timedOut))]), "request.failed"),
(.init(results: [.failure(URLError(.cancelled))]), "request.cancelled")
]
for (session, expected) in cases {
var logs: [String] = []
let client = APIClient(environment: .testing, session: session, droneDockLogSink: { logs.append($0) })
do {
let _: DroneDockHomeJSONValue = try await client.send(APIRequest(method: .get, path: "/api/app/airport/shooting"))
XCTFail("应失败")
} catch {}
XCTAssertTrue(logs.joined().contains(expected), expected)
}
}
/// Debug 本地拦截也能定位,日志明确说明请求未发送。
func testBlockedRequestIsLoggedBeforeTransport() async throws {
let session = DiagnosticsUnreachableSession()
var logs: [String] = []
let client = APIClient(environment: .production, session: session, droneDockLogSink: { logs.append($0) })
do {
let _: DroneDockHomeJSONValue = try await client.send(APIRequest(method: .post, path: "/api/app/airport/shoot"))
XCTFail("Debug 禁止发送")
} catch { XCTAssertTrue(error is DeviceCommandDebugBlockedError) }
XCTAssertEqual(session.calls, 0)
XCTAssertEqual(logs.count, 1)
XCTAssertTrue(logs[0].contains("request.blocked"))
XCTAssertTrue(logs[0].contains("\"sent\":false"))
}
/// 长中文 JSON 按字节分段后可以无损拼接,不额外截断业务字段。
func testChunkingAndFreeTextPreservation() {
let text = String(repeating: "中文😀\n", count: 1_000)
let chunks = DroneDockDiagnostics.chunks(text)
XCTAssertEqual(chunks.joined(), text)
XCTAssertTrue(chunks.allSatisfy { $0.utf8.count <= 600 })
let logged = DroneDockDiagnostics.json(["message": "token=ABC https://example.test/a?signature=DEF 13912345678"])
for secret in ["ABC", "DEF", "13912345678"] { XCTAssertTrue(logged.contains(secret)) }
XCTAssertFalse(DroneDockDiagnostics.includes(path: "/api/login"))
}
}
/// 无网络能力的普通传输替身,用于验证拦截发生在任何传输之前。
private final class DiagnosticsUnreachableSession: URLSessionProtocol {
private(set) var calls = 0
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
calls += 1
throw URLError(.notConnectedToInternet)
}
}
@@ -0,0 +1,41 @@
import XCTest
@testable import suixinkan
/// 报备提示仅来自明确错误语义,不凭同一个通用业务码猜测原因。
final class DroneDockPreparationFailureTests: XCTestCase {
/// 创建与召唤均可提示报备,保留具体原因与处理指引。
func testExplicitFilingErrorsProvideGuidance() {
for message in ["未报备,禁止飞行", "当前航线未完成报备", "报备已过期", "请先备案"] {
for stage in [DroneDockPreparationFailure.Stage.creation, .summon] {
let value = DroneDockPreparationFailure(message: message, stage: stage, outcomeUnknown: false)
XCTAssertTrue(value.requiresFiling)
XCTAssertEqual(value.title, "请先完成飞行报备")
XCTAssertTrue(value.message.contains(message))
XCTAssertTrue(value.message.contains("确认生效后再重试"))
}
}
}
/// 用户提供的已结束任务回执属于召唤失败,不能展示为未报备或自动重启。
func testEndedTaskAndOtherRejectionsAreNotMisclassifiedAsFiling() {
let ended = "任务已结束,无法召唤;失败后请传 restart=true 重新召唤"
let value = DroneDockPreparationFailure(message: ended, stage: .summon, outcomeUnknown: false)
XCTAssertFalse(value.requiresFiling)
XCTAssertEqual(value.title, "任务已结束")
XCTAssertFalse(value.message.contains("restart=true"))
for message in ["无人机忙碌", "已报备,无人机离线", "次数已用完"] {
let failure = DroneDockPreparationFailure(message: message, stage: .creation, outcomeUnknown: false)
XCTAssertFalse(failure.requiresFiling)
XCTAssertEqual(failure.title, "任务创建失败")
XCTAssertEqual(failure.message, message)
}
}
/// 结果未知不引导直接重试,即使说明文字包含报备关键字。
func testUnknownOutcomeKeepsReconciliationGuidance() {
let value = DroneDockPreparationFailure(message: "报备未确认;创建结果待核对", stage: .creation, outcomeUnknown: true)
XCTAssertFalse(value.requiresFiling)
XCTAssertEqual(value.title, "任务创建结果待核对")
XCTAssertFalse(value.message.contains("再重试"))
}
}
@@ -5,6 +5,89 @@ import XCTest
/// 验证准备页购买快照、独立设备状态、点位航线选择与错误恢复。
@MainActor
final class DroneDockPreparationViewTests: XCTestCase {
/// 长点位名称完整换行,卡片与航线标题均按实际文本增高。
func testLongPointNameFitsCardAndRouteHeading() async throws {
let name = "测试景区东南观景平台通往山顶步道的全景航拍打卡点"
var spots = DroneDockPreparationViewFixtures.purchasedSpots()
spots[0]["scenic_spot_name"] = name
let (controller, _) = try DroneDockPreparationViewFixtures.controller(
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
responses: [DroneDockPreparationViewFixtures.projectEnvelope(spots: spots)])
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.selectedSpot?.name == name }
let list = try collection(in: controller)
let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 0, section: 1)))
let label = try XCTUnwrap(find(in: cell, id: "drone.preparation.point.name") as? UILabel)
XCTAssertEqual(label.text, name)
XCTAssertEqual(label.numberOfLines, 0)
XCTAssertGreaterThan(cell.bounds.height, 64)
XCTAssertGreaterThanOrEqual(label.bounds.height + 1,
label.sizeThatFits(CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)).height)
let header = try XCTUnwrap(list.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader,
at: IndexPath(item: 0, section: 2)))
let title = try XCTUnwrap(find(in: header, id: "drone.preparation.heading.title") as? UILabel)
XCTAssertEqual(title.text, name + "的航线")
XCTAssertEqual(title.numberOfLines, 0)
XCTAssertGreaterThanOrEqual(title.bounds.height + 1,
title.sizeThatFits(CGSize(width: title.bounds.width, height: .greatestFiniteMagnitude)).height)
XCTAssertLessThanOrEqual(title.convert(title.bounds, to: header).maxX, header.bounds.maxX + 1)
capture(window, name: "准备页-长打卡点名称完整换行")
}
/// 创建未报备时明确弹窗,保留选择且不会继续召唤。
func testFilingFailureShowsAlertWithoutSummoning() async throws {
let creation = DroneDockTaskCreationTestService(result: .failure(APIError.serverCode(100099, "当前航线未报备")))
let shoot = DroneDockShootTestService(result: .success(try DroneDockShootTestData.response()))
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
let (controller, _) = try DroneDockPreparationViewFixtures.controller(
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
responses: [project, project], creationService: creation, shootService: shoot)
let window = makeWindow(root: controller)
defer { controller.dismiss(animated: false); close(window) }
let primary = try button(in: controller.view, id: "drone.preparation.summon")
try await settle(window) { primary.isEnabled }
primary.sendActions(for: .touchUpInside)
try await settle(window) { controller.presentedViewController is UIAlertController }
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
XCTAssertEqual(alert.title, "请先完成飞行报备")
XCTAssertTrue(alert.message?.contains("确认生效后再重试") == true)
XCTAssertEqual(controller.viewModel.selectedSpotID, 101)
XCTAssertEqual(controller.viewModel.selectedRouteID, 201)
XCTAssertTrue(shoot.requests.isEmpty)
XCTAssertEqual(creation.requests.count, 1)
capture(window, name: "准备页-未报备提示-本地模拟")
}
/// 创建成功不显示 data;已结束任务的召唤失败仅提供显式查看,不自动跳转或再次 POST。
func testEndedTaskShowsFailureWithoutSuccessJSONAndOpensOnlyOnTap() async throws {
let creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response()))
let shoot = DroneDockShootTestService(result: .failure(APIError.serverCode(100099,
"任务已结束,无法召唤;失败后请传 restart=true 重新召唤")))
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
let (controller, _) = try DroneDockPreparationViewFixtures.controller(
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
responses: [project, project], creationService: creation, shootService: shoot)
let window = makeWindow(root: controller)
defer { close(window) }
let primary = try button(in: controller.view, id: "drone.preparation.summon")
try await settle(window) { primary.isEnabled }
primary.sendActions(for: .touchUpInside)
try await settle(window) { controller.viewModel.summonRequiresTaskReview && primary.isEnabled }
XCTAssertTrue(controller.navigationController?.topViewController === controller)
XCTAssertEqual(primary.title(for: .normal), "查看拍摄任务")
let list = try collection(in: controller)
XCTAssertEqual(list.numberOfItems(inSection: 4), 0, "创建成功不再增加回执区")
XCTAssertNil(find(in: controller.view, id: "drone.preparation.creationResponse"))
XCTAssertFalse(visibleTexts(in: controller.view).contains { $0.contains("task_id") || $0.contains("restart=true") })
XCTAssertEqual(controller.viewModel.summonFailure?.requiresFiling, false)
capture(window, name: "准备页-任务已结束提示-本地模拟")
primary.sendActions(for: .touchUpInside)
try await settle(window) { controller.navigationController?.topViewController is DroneDockPreparationTaskDestinationStub }
XCTAssertEqual((controller.navigationController?.topViewController as? DroneDockPreparationTaskDestinationStub)?.taskID, 501)
XCTAssertEqual(creation.requests.count, 1)
XCTAssertEqual(shoot.requests, [501])
}
private weak var previousKeyWindow: UIWindow?
/// 禁飞准备页只通过显式入口打开独立模拟订单,不放开原订单的创建和召唤。
@@ -395,6 +478,10 @@ final class DroneDockPreparationViewTests: XCTestCase {
XCTAssertEqual(projectSession.requests.count, 2)
navigation.popViewController(animated: false)
try await settle(window) { navigation.topViewController === controller && projectSession.requests.count == 3 && summon.isEnabled }
XCTAssertEqual(list.numberOfItems(inSection: 4), 0)
XCTAssertEqual(list.numberOfItems(inSection: 5), 0)
XCTAssertNil(find(in: controller.view, id: "drone.preparation.creationResponse"))
XCTAssertNil(find(in: controller.view, id: "drone.preparation.shootResponse"))
XCTAssertEqual(summon.title(for: .normal), "查看拍摄任务")
XCTAssertEqual(navigation.viewControllers.count, 1, "返回不会自动再次跳转")
summon.sendActions(for: .touchUpInside)
@@ -469,8 +556,8 @@ final class DroneDockPreparationViewTests: XCTestCase {
let summon = try button(in: controller.view, id: "drone.preparation.summon")
try await settle(window) { summon.isEnabled }
summon.sendActions(for: .touchUpInside)
try await settle(window) { self.visibleTexts(in: controller.view).contains("任务创建未成功") && summon.isEnabled }
let response = try XCTUnwrap(find(in: controller.view, id: "drone.preparation.creationResponse") as? UITextView)
try await settle(window) { self.visibleTexts(in: controller.view).contains("任务创建失败") && summon.isEnabled }
let response = try XCTUnwrap(find(in: controller.view, id: "drone.preparation.creationResponse") as? UILabel)
XCTAssertEqual(response.text, "测试航线暂不可用")
XCTAssertEqual(creation.requests.count, 1)
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
@@ -499,7 +586,7 @@ final class DroneDockPreparationViewTests: XCTestCase {
try await settle(window) { controller.viewModel.shootErrorMessage != nil && primary.isEnabled }
XCTAssertEqual(primary.title(for: .normal), "重试召唤")
XCTAssertEqual(controller.viewModel.createdTask?.taskID, 501)
let failedText = try XCTUnwrap(find(in: controller.view, id: "drone.preparation.shootResponse") as? UITextView)
let failedText = try XCTUnwrap(find(in: controller.view, id: "drone.preparation.shootResponse") as? UILabel)
XCTAssertEqual(failedText.text, "测试无人机忙碌")
try button(in: controller.view, id: "drone.preparation.refreshSummon").sendActions(for: .touchUpInside)
try await settle(window) { controller.viewModel.errorMessage != nil && primary.isEnabled }
+12 -8
View File
@@ -132,14 +132,15 @@ final class DroneDockRTCPlaybackTests: XCTestCase {
player.stop()
}
/// 已允许手动图传的页面进场、回前台均不自动调用 live。
/// 状态轮询、页面进场和回前台均不自动调用 live。
func testTaskPageRequiresExplicitTapAndDoesNotRestartOnForeground() async throws {
let (live, service) = try makeModel(response: DroneDockRTCFixture.response(play: ["url_type": "agora"]))
let context = DroneDockShootingTaskTestData.context()
let read = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.response()))
let model = DroneDockShootingTaskViewModel(context: context, taskID: 501,
order: try DroneDockShootingTaskTestData.order(), service: read, currentContext: { context })
let controller = DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live)
let controller = DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live,
shootingPollDelay: { _ in try await Task.sleep(for: .milliseconds(40)) })
let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first
let previous = scene?.windows.first { $0.isKeyWindow }
let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds)
@@ -148,6 +149,7 @@ final class DroneDockRTCPlaybackTests: XCTestCase {
defer { window.isHidden = true; window.rootViewController = nil; previous?.makeKeyAndVisible() }
try await Task.sleep(for: .milliseconds(250))
XCTAssertEqual(service.count, 0)
XCTAssertGreaterThan(read.requests.count, 1, "已发生 shooting 轮询,live 仍未被调用")
XCTAssertTrue(read.requests.allSatisfy { !$0.liveBattery })
let button = try XCTUnwrap(descendants(controller.view).first {
$0.accessibilityIdentifier == "drone.task.remote.live.request"
@@ -164,15 +166,17 @@ final class DroneDockRTCPlaybackTests: XCTestCase {
XCTAssertFalse(model.canResummon)
}
/// API 请求日志隐藏整个响应正文,避免 querystring 中的 Token 落入控制台。
func testLiveAPIResponseLogDoesNotContainRTCSecrets() async throws {
let payload: [String: Any] = ["order_flight_task_id": 501, "play": ["url": "token=DO-NOT-LOG"]]
/// 按用户要求完整记录 live 原始回执,SDK 播放流程不受日志调整影响。
func testLiveAPIResponseLogContainsOriginalRTCParameters() async throws {
let payload: [String: Any] = ["order_flight_task_id": 501, "play": ["url": "token=TEST-RTC-TOKEN"]]
let session = MockURLSession(responses: [try DroneDockLiveTestData.envelope(payload)])
var logs = ""
let client = APIClient(environment: .testing, session: session, debugLogSink: { logs += $0 })
let client = APIClient(environment: .testing, session: session, debugLogSink: { logs += $0 },
droneDockLogSink: { logs += $0 })
_ = try await DroneDockLiveAPI(client: client).live(taskID: 501)
XCTAssertFalse(logs.contains("DO-NOT-LOG"))
XCTAssertTrue(logs.contains("sensitive payload omitted"))
XCTAssertTrue(logs.contains("TEST-RTC-TOKEN"))
XCTAssertFalse(logs.contains("<redacted>"))
XCTAssertTrue(logs.contains("response.received"))
}
private func makeModel(response: DroneDockLiveResponse? = nil) throws -> (DroneDockLiveViewModel, RTCParameterProbe) {
@@ -5,6 +5,23 @@ import XCTest
/// 验证创建后复用任务召唤,以及成功、拒绝、未知结果与生命周期防重复规则。
@MainActor
final class DroneDockShootViewModelTests: XCTestCase {
/// 后端明确任务已结束后,仅允许查看原任务;刷新或再次调用不能重发首次召唤。
func testEndedTaskAllowsReviewWithoutRepeatedSummonOrCreation() async throws {
let fixture = try ShootFlowFixture()
fixture.shoot.result = .failure(APIError.serverCode(100099, "任务已结束,无法召唤;失败后请传 restart=true 重新召唤"))
await fixture.model.refresh()
await fixture.model.prepareAndSummon()
XCTAssertTrue(fixture.model.summonRequiresTaskReview)
XCTAssertTrue(fixture.model.canOpenShootingTask)
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
XCTAssertEqual(fixture.model.primaryButtonTitle, "查看拍摄任务")
XCTAssertEqual(fixture.model.summonFailure?.requiresFiling, false)
XCTAssertNil(fixture.model.shootResponse)
await fixture.model.refresh()
await fixture.model.prepareAndSummon()
XCTAssertEqual(fixture.creation.requests.count, 1)
XCTAssertEqual(fixture.shoot.requests, [501])
}
/// 只有拿到张工创建的任务 ID 后才召唤,成功仅表示请求被接受。
func testFirstActionCreatesThenSummonsSameTask() async throws {
let fixture = try ShootFlowFixture()
@@ -31,7 +48,7 @@ final class DroneDockShootViewModelTests: XCTestCase {
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
XCTAssertFalse(fixture.model.canCreateTask)
XCTAssertEqual(fixture.model.primaryButtonTitle, "查看拍摄任务")
XCTAssertEqual(fixture.model.admissionMessage, "任务 501 的召唤请求已提交,请等待任务状态更新")
XCTAssertEqual(fixture.model.admissionMessage, "召唤请求已提交,请等待任务状态更新")
XCTAssertFalse(fixture.model.admissionMessage.contains("已起飞"))
XCTAssertFalse(fixture.model.admissionMessage.contains("已到达"))
}
@@ -150,7 +167,7 @@ final class DroneDockShootViewModelTests: XCTestCase {
await fixture.model.refresh()
await fixture.model.createTask()
XCTAssertTrue(fixture.shoot.requests.isEmpty)
XCTAssertEqual(fixture.model.admissionMessage, "任务 501 已创建,等待召唤")
XCTAssertEqual(fixture.model.admissionMessage, "任务已创建,等待召唤")
XCTAssertTrue(fixture.model.isPrimaryActionEnabled)
await fixture.model.prepareAndSummon()
XCTAssertEqual(fixture.projects.requests, 2)
@@ -5,6 +5,16 @@ import XCTest
/// 验证真实任务页只读刷新保留快照、同任务重入和身份隔离,不接入飞控。
@MainActor
final class DroneDockShootingTaskViewModelTests: XCTestCase {
/// 缺省/无效间隔回退到五秒,合法建议限制在两至三十秒,避免紧密请求或溢出。
func testPollingIntervalUsesBoundedServerHint() async throws {
for (hint, expected) in [(0, 5_000), (-1, 5_000), (1, 2_000), (8_000, 8_000), (Int.max, 30_000)] {
let fixture = try ShootingTaskFixture(response: DroneDockShootingTaskTestData.response(
changes: ["plane_status": ["poll_hint_ms": hint]]))
XCTAssertEqual(fixture.model.pollIntervalNanoseconds, 5_000_000_000)
await fixture.model.refresh()
XCTAssertEqual(fixture.model.pollIntervalNanoseconds, UInt64(expected) * 1_000_000)
}
}
/// 进入、刷新和返回始终读取传入的同一任务,构造本身不发请求。
func testRefreshAndReturnReadSameTaskWithoutLiveBattery() async throws {
let fixture = try ShootingTaskFixture()
@@ -2,7 +2,7 @@ import UIKit
import XCTest
@testable import suixinkan
/// 验证真实任务页按进入、恢复前台和手动操作单次读取,不定时轮询或自动重试。
/// 验证任务页前台串行轮询、旧快照保留与生命周期取消;网络均为隔离替身。
@MainActor
final class DroneDockShootingTaskViewTests: XCTestCase {
private weak var previousKeyWindow: UIWindow?
@@ -10,7 +10,8 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
/// 构造和加载视图不请求,完整出现后才使用传入的同一任务 ID 读取。
func testFirstRequestWaitsUntilPageAppears() async throws {
let service = try TaskViewReadService()
let controller = try makeController(service: service)
let clock = TaskViewPollClock()
let controller = try makeController(service: service, pollDelay: { try await clock.wait($0) })
XCTAssertTrue(service.requests.isEmpty)
controller.loadViewIfNeeded()
XCTAssertTrue(service.requests.isEmpty)
@@ -23,9 +24,67 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
XCTAssertEqual(controller.title, "拍摄任务")
XCTAssertEqual(controller.navigationItem.rightBarButtonItem?.accessibilityIdentifier, "drone.task.remote.navigationRefresh")
XCTAssertFalse(controller.navigationItem.hidesBackButton)
// 超过历史默认五秒间隔,停留本页仍只能保留首次 GET。
try await Task.sleep(nanoseconds: 5_300_000_000)
XCTAssertEqual(service.requests, [501])
XCTAssertEqual(clock.intervals, [5_000_000_000])
clock.advance()
try await settle(window) { service.requests.count == 2 && clock.pendingCount == 1 }
XCTAssertEqual(service.requests, [501, 501])
XCTAssertEqual(clock.intervals, [5_000_000_000, 5_000_000_000])
}
/// 轮询期间不并发,旧快照可见;普通失败下一周期恢复,不清空页面。
func testPollRetainsSnapshotSerializesRequestsAndRecoversFailure() async throws {
let clock = TaskViewPollClock()
let service = try TaskViewReadService()
let controller = try makeController(service: service, pollDelay: { try await clock.wait($0) })
let window = makeWindow(root: controller)
defer { service.cancelAll(); close(window) }
try await settle(window) { clock.pendingCount == 1 }
let previous = controller.viewModel.dataJSON
service.suspendNext = true
clock.advance()
try await settle(window) { service.requests.count == 2 && controller.viewModel.isLoading }
XCTAssertEqual(controller.viewModel.dataJSON, previous)
XCTAssertEqual(clock.pendingCount, 0, "请求结束后才启动下一次计时")
try tapNavigationRefresh(controller)
XCTAssertEqual(service.requests.count, 2)
service.finish()
try await settle(window) { clock.pendingCount == 1 }
service.nextError = APIError.networkFailed("模拟断网")
clock.advance()
try await settle(window) { controller.viewModel.errorMessage != nil && clock.pendingCount == 1 }
XCTAssertEqual(controller.viewModel.dataJSON, previous)
clock.advance()
try await settle(window) { service.requests.count == 4 && controller.viewModel.errorMessage == nil }
}
/// 离页、后台取消计时;前台恢复立即读取,账号/景区变化后不再轮询旧任务。
func testPollStopsOffscreenInBackgroundAndOnIdentityChange() async throws {
let clock = TaskViewPollClock()
let scope = TaskViewScope()
let service = try TaskViewReadService()
let controller = try makeController(service: service, scope: scope, pollDelay: { try await clock.wait($0) })
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { clock.pendingCount == 1 }
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
try await settle(window) { clock.pendingCount == 0 }
clock.advance()
XCTAssertEqual(service.requests.count, 1)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
try await settle(window) { service.requests.count == 2 && clock.pendingCount == 1 }
let navigation = try XCTUnwrap(controller.navigationController)
navigation.pushViewController(UIViewController(), animated: false)
try await settle(window) { clock.pendingCount == 0 }
clock.advance()
XCTAssertEqual(service.requests.count, 2)
navigation.popViewController(animated: false)
try await settle(window) { service.requests.count == 3 && clock.pendingCount == 1 }
scope.scenicID = 999
clock.advance()
try await settle(window) { controller.viewModel.errorMessage != nil && clock.pendingCount == 0 }
XCTAssertEqual(service.requests.count, 3)
XCTAssertNil(controller.viewModel.response)
XCTAssertFalse(controller.viewModel.canContinuePolling)
}
/// 展示后端标题、套餐和六项带单位读数,不沿用演示值或假控制。
@@ -131,7 +190,7 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
XCTAssertEqual(try button(in: controller.view).title(for: .normal), "重新读取")
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "—")
try await Task.sleep(nanoseconds: 140_000_000)
XCTAssertEqual(session.requests.count, 1, "失败后等待明确点击,不自动重试")
XCTAssertEqual(session.requests.count, 1, "失败后等待下一周期或明确点击,不立即密集重试")
try button(in: controller.view).sendActions(for: .touchUpInside)
try await settle(window) { controller.viewModel.response != nil && session.requests.count == 2 }
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
@@ -410,12 +469,14 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
}
private func makeController(service: any DroneDockShootingServing, scope: TaskViewScope? = nil,
pollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) },
materialsFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) throws -> DroneDockShootingTaskViewController {
let scope = scope ?? TaskViewScope()
let order = try JSONDecoder().decode(DroneDockHomeOrder.self, from: Data(#"{"order_number":"TEST-TASK-501","project_id":101,"project_name":"入口五次套餐","user_phone":"130****0501"}"#.utf8))
let model = DroneDockShootingTaskViewModel(context: scope.value, taskID: 501, order: order,
service: service, currentContext: { scope.value })
return DroneDockShootingTaskViewController(viewModel: model, materialsControllerFactory: materialsFactory)
return DroneDockShootingTaskViewController(viewModel: model, materialsControllerFactory: materialsFactory,
shootingPollDelay: pollDelay)
}
private func makeWindow(root: UIViewController) -> UIWindow {
@@ -481,6 +542,35 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
}
}
/// 手动推进轮询时间,并真正响应取消,避免测试依赖真实的五秒计时。
@MainActor
private final class TaskViewPollClock {
private var pending: [(UUID, CheckedContinuation<Void, Error>)] = []
private(set) var intervals: [UInt64] = []
var pendingCount: Int { pending.count }
func wait(_ interval: UInt64) async throws {
let id = UUID()
try Task.checkCancellation()
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
intervals.append(interval)
pending.append((id, continuation))
}
} onCancel: {
Task { @MainActor in
guard let index = self.pending.firstIndex(where: { $0.0 == id }) else { return }
self.pending.remove(at: index).1.resume(throwing: CancellationError())
}
}
}
func advance() {
guard !pending.isEmpty else { return }
pending.removeFirst().1.resume()
}
}
/// 独立任务页 JSON 数据,所有设备、订单和摘要均为匿名测试值。
private enum TaskViewData {
static func payload() -> [String: Any] {
@@ -5,6 +5,20 @@ import XCTest
/// 验证准备页只创建待飞任务、保留真实回执,并阻止重复提交不确定请求。
@MainActor
final class DroneDockTaskCreationViewModelTests: XCTestCase {
/// 未报备时保留选择、不伪造任务,不调用召唤;明确业务拒绝可在处理后手动重试。
func testFilingRejectionPreservesSelectionAndDoesNotSummon() async throws {
let fixture = try TaskCreationFixture()
fixture.creation.result = .failure(APIError.serverCode(100099, "当前航线未报备"))
await fixture.model.refresh()
fixture.model.selectSpot(id: 202)
await fixture.model.prepareAndSummon()
XCTAssertNil(fixture.model.createdTask)
XCTAssertNil(fixture.model.shootResponse)
XCTAssertEqual(fixture.model.selectedSpotID, 202)
XCTAssertEqual(fixture.model.creationFailure?.requiresFiling, true)
XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown)
XCTAssertTrue(fixture.model.isPrimaryActionEnabled)
}
/// 单独建任务只受购买条件约束,不因无设备状态或离线而错误拦截。
func testValidPurchaseAllowsCreationWithoutPlanePermission() async throws {
let fixture = try TaskCreationFixture()
@@ -3,250 +3,141 @@ import XCTest
@testable import suixinkan
#if DEBUG
/// 使用内存响应核对空境库控制台日志,防止授权地址泄漏或日志改写真实业务数据。
/// 使用内存响应核对空境库完整日志;普通模块仍保留原有日志策略。
@MainActor
final class ScenicMaterialsRequestLoggingTests: XCTestCase {
/// 列表日志保留景区、分页和筛选参数,并输出可读的原始业务 JSON。
func testSessionsLogsParametersAndFormattedResponse() async throws {
/// 空境库使用统一机巢日志,保留分页筛选、请求头和完整响应。
func testSessionsLogsParametersAndCompleteResponse() async throws {
let payload = Data(#"{"code":100000,"msg":"success","data":{"list":[],"groups":[],"total":0,"page":2,"page_size":30,"retention_days":90,"retention_tips":"素材保留 90 天,请及时下载","filter":{"air_line_id":123,"date_from":"2026-10-01","date_to":"2026-10-29"},"filter_options":{"air_lines":[]}}}"#.utf8)
let session = MockURLSession(responses: [payload])
var logs: [String] = []
let client = APIClient(environment: .testing, session: session, debugLogSink: { logs.append($0) })
client.bindAuthTokenProvider { "private-request-header-token" }
var legacy: [String] = []
let client = APIClient(environment: .testing, session: session, debugLogSink: { legacy.append($0) },
droneDockLogSink: { logs.append($0) })
client.bindAuthTokenProvider { "test-header-token" }
let result = try await ScenicMaterialsAPI(client: client).sessions(query: ScenicMaterialsQuery(
scenicID: 271, page: 2, pageSize: 30, airLineID: 123,
dateFrom: "2026-10-01", dateTo: "2026-10-29"
))
XCTAssertEqual(logs.count, 2)
let requestLog = try XCTUnwrap(logs.first)
XCTAssertTrue(requestLog.contains("[API][景区空境库][Request] GET"))
XCTAssertTrue(requestLog.contains("/api/app/scenic-media/sessions"))
XCTAssertTrue(requestLog.contains("params:"))
for parameter in ["scenic_id=271", "page=2", "page_size=30", "retention_days=90",
"air_line_id=123", "date_from=2026-10-01", "date_to=2026-10-29"] {
XCTAssertTrue(requestLog.contains(parameter), "缺少查询参数:\(parameter)")
}
let responseLog = try XCTUnwrap(logs.last)
XCTAssertTrue(responseLog.contains("[API][景区空境库][Response] GET"))
XCTAssertTrue(responseLog.contains("status=200"))
XCTAssertTrue(responseLog.contains("\n \""), "响应 JSON 应格式化显示")
let loggedEnvelope = try loggedJSON(responseLog)
XCTAssertEqual(loggedEnvelope["code"] as? Int, 100000)
let loggedData = try XCTUnwrap(loggedEnvelope["data"] as? [String: Any])
XCTAssertEqual(loggedData["retention_tips"] as? String, result.retentionTips)
XCTAssertEqual(loggedData["page"] as? Int, 2)
XCTAssertNotNil(loggedData["filter_options"] as? [String: Any])
XCTAssertFalse(logs.joined().contains("private-request-header-token"))
XCTAssertEqual(session.requests.first?.value(forHTTPHeaderField: "token"), "private-request-header-token")
XCTAssertEqual(result.page, 2)
XCTAssertTrue(result.list.isEmpty)
dateFrom: "2026-10-01", dateTo: "2026-10-29"))
XCTAssertTrue(legacy.isEmpty)
XCTAssertEqual(logs.count, 3)
let request = try event("request.started", in: logs)
XCTAssertEqual(request["method"] as? String, "GET")
XCTAssertEqual(request["path"] as? String, "/api/app/scenic-media/sessions")
let query = try XCTUnwrap(request["query"] as? [[String: String]])
XCTAssertEqual(query.reduce(into: [String: String]()) { $0.merge($1) { _, new in new } }, [
"scenic_id": "271", "page": "2", "page_size": "30", "retention_days": "90",
"air_line_id": "123", "date_from": "2026-10-01", "date_to": "2026-10-29"])
let headers = try XCTUnwrap(request["request_headers"] as? [String: String])
XCTAssertTrue(headers.values.contains("test-header-token"))
let response = try event("response.received", in: logs)
XCTAssertEqual(response["http_status"] as? Int, 200)
let envelope = try XCTUnwrap(response["body"] as? [String: Any])
let data = try XCTUnwrap(envelope["data"] as? [String: Any])
XCTAssertEqual(data["retention_tips"] as? String, result.retentionTips)
XCTAssertEqual(data["page"] as? Int, 2)
XCTAssertEqual(session.requests.count, 1)
}
/// 递归脱敏字段及 URL 的鉴权信息,但 DTO 保留原始字段供播放和下载使用。
func testDetailRedactsNestedCredentialsAndSignedURLsWithoutChangingResponse() async throws {
let signedURL = "https://url-private-user:url-private-password@media.example.com/scenic/clip.mp4?signature=url-private-signature&token=url-private-token#url-private-fragment"
let credentialFields = [
"token": "nested-private-token",
"Authorization": "nested-private-authorization",
"signature": "nested-private-signature",
"credential": "nested-private-credential",
"security_token": "nested-private-security-token",
"access_key": "nested-private-access-key",
"password": "nested-private-password",
"Cookie": "nested-private-cookie",
]
let payload = try JSONSerialization.data(withJSONObject: [
"code": 100000,
"msg": "success",
"data": [
"scenic_media_id": 501,
"materials": [[
"file_label": "片段一",
"selectable": true,
"oss_url": signedURL,
"nested": ["items": [credentialFields]],
]],
],
])
let session = MockURLSession(responses: [payload])
/// 完整签名 URL、嵌套凭证和业务字段保持原样,日志不改写 DTO。
func testDetailPreservesNestedCredentialsAndSignedURL() async throws {
let signedURL = "https://test-user:test-password@media.example.com/clip.mp4?signature=test-signature#fragment"
let body: [String: Any] = ["code": 100000, "data": ["materials": [[
"file_label": "片段一", "oss_url": signedURL,
"nested": ["items": [["token": "test-token", "Authorization": "test-authorization"]]]
]]]]
let session = MockURLSession(responses: [try JSONSerialization.data(withJSONObject: body)])
var logs: [String] = []
let api = ScenicMaterialsAPI(client: APIClient(
environment: .testing, session: session, debugLogSink: { logs.append($0) }
))
let api = ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session,
droneDockLogSink: { logs.append($0) }))
let result = try await api.sessionDetail(scenicMediaID: 501)
XCTAssertEqual(logs.count, 2)
XCTAssertTrue(logs[0].contains("scenic_media_id=501"))
let combined = logs.joined(separator: "\n")
for secret in Array(credentialFields.values) + ["url-private-user", "url-private-password",
"url-private-signature", "url-private-token", "url-private-fragment"] {
XCTAssertFalse(combined.contains(secret), "日志泄漏敏感值:\(secret)")
}
let loggedEnvelope = try loggedJSON(try XCTUnwrap(logs.last))
let loggedData = try XCTUnwrap(loggedEnvelope["data"] as? [String: Any])
let materials = try XCTUnwrap(loggedData["materials"] as? [[String: Any]])
XCTAssertEqual(materials.first?["oss_url"] as? String, "https://media.example.com/scenic/clip.mp4")
XCTAssertEqual(materials.first?["file_label"] as? String, "片段一")
XCTAssertEqual(materials.first?["selectable"] as? Bool, true)
let response = try event("response.received", in: logs)
let logged = try XCTUnwrap(response["body"] as? [String: Any])
XCTAssertTrue(NSDictionary(dictionary: logged).isEqual(to: body))
XCTAssertEqual(result.materials.first?["oss_url"], .string(signedURL))
let expectedNested = ScenicMaterialsJSONValue.object([
"items": .array([.object(credentialFields.mapValues { .string($0) })]),
])
XCTAssertEqual(result.materials.first?["nested"], expectedNested)
XCTAssertEqual(session.requests.first?.url?.path, "/api/app/scenic-media/session-detail")
XCTAssertFalse(logs.joined().contains("<redacted>"))
}
/// HTTP 成功但业务拒绝时,仍能从控制台看到业务码及服务端原因。
func testBusinessFailureStillLogsResponseJSON() async throws {
let payload = try TestJSON.errorEnvelope(code: 100099, msg: "请使用门店账号登录")
let session = MockURLSession(responses: [payload])
var logs: [String] = []
let api = ScenicMaterialsAPI(client: APIClient(
environment: .testing, session: session, debugLogSink: { logs.append($0) }
))
do {
_ = try await api.sessionDetail(scenicMediaID: 501)
XCTFail("业务失败必须继续向调用者抛出")
} catch let APIError.serverCode(code, message) {
XCTAssertEqual(code, 100099)
XCTAssertEqual(message, "请使用门店账号登录")
}
let responseLog = try XCTUnwrap(logs.last)
XCTAssertTrue(responseLog.contains("[Response]"))
XCTAssertTrue(responseLog.contains("status=200"))
let envelope = try loggedJSON(responseLog)
XCTAssertEqual(envelope["code"] as? Int, 100099)
XCTAssertEqual(envelope["msg"] as? String, "请使用门店账号登录")
}
/// HTTP 失败也在抛错前记录状态和 JSON,不因失败绕过脱敏。
func testHTTPFailureStillLogsStatusAndRedactedJSON() async throws {
let payload = Data(#"{"code":100099,"msg":"服务暂不可用","token":"http-private-token","data":null}"#.utf8)
let session = MockURLSession(responses: [payload], statusCode: 503)
var logs: [String] = []
let api = ScenicMaterialsAPI(client: APIClient(
environment: .testing, session: session, debugLogSink: { logs.append($0) }
))
do {
_ = try await api.sessionDetail(scenicMediaID: 501)
XCTFail("HTTP 失败必须继续向调用者抛出")
} catch let APIError.httpStatus(status, message) {
XCTAssertEqual(status, 503)
XCTAssertEqual(message, "服务暂不可用")
}
let responseLog = try XCTUnwrap(logs.last)
XCTAssertTrue(responseLog.contains("[Response]"))
XCTAssertTrue(responseLog.contains("status=503"))
XCTAssertFalse(logs.joined().contains("http-private-token"))
let envelope = try loggedJSON(responseLog)
XCTAssertEqual(envelope["msg"] as? String, "服务暂不可用")
XCTAssertNotNil(envelope["token"])
}
/// 传输错误输出错误域和错误码,不记录可能夹带凭证的 localizedDescription。
func testNetworkFailureLogsErrorCodeWithoutPrivateDescription() async throws {
let error = URLError(.timedOut, userInfo: [
NSLocalizedDescriptionKey: "network-private-description",
NSURLErrorFailingURLStringErrorKey: "https://example.com/clip.mp4?signature=network-private-signature",
])
let session = MockURLSession(results: [.failure(error)])
var logs: [String] = []
let api = ScenicMaterialsAPI(client: APIClient(
environment: .testing, session: session, debugLogSink: { logs.append($0) }
))
do {
_ = try await api.sessionDetail(scenicMediaID: 501)
XCTFail("网络失败必须继续向调用者抛出")
} catch let APIError.networkFailed(message) {
XCTAssertEqual(message, "请求超时,请稍后重试")
}
XCTAssertEqual(logs.count, 2)
let failureLog = try XCTUnwrap(logs.last)
XCTAssertTrue(failureLog.contains("[API][景区空境库][Failure] GET"))
XCTAssertTrue(failureLog.contains("NSURLErrorDomain"))
XCTAssertTrue(failureLog.contains("-1001"))
XCTAssertFalse(logs.joined().contains("network-private-description"))
XCTAssertFalse(logs.joined().contains("network-private-signature"))
}
/// Swift 取消和 URLSession 取消统一记录取消事件,保持 CancellationError 语义。
func testCancellationLogsEventForBothCancellationTypes() async throws {
let errors: [Error] = [CancellationError(), URLError(.cancelled)]
for error in errors {
let session = MockURLSession(results: [.failure(error)])
/// 业务和 HTTP 拒绝在抛错前完整记录回包。
func testRejectedResponsesKeepStatusAndOriginalBody() async throws {
for status in [200, 503] {
let body = Data(#"{"code":100099,"msg":"服务暂不可用","token":"test-token","data":null}"#.utf8)
var logs: [String] = []
let api = ScenicMaterialsAPI(client: APIClient(
environment: .testing, session: session, debugLogSink: { logs.append($0) }
))
let client = APIClient(environment: .testing, session: MockURLSession(responses: [body], statusCode: status),
droneDockLogSink: { logs.append($0) })
do {
_ = try await api.sessionDetail(scenicMediaID: 501)
XCTFail("取消必须继续向调用者抛出")
} catch is CancellationError {}
XCTAssertEqual(logs.count, 2)
let cancellationLog = try XCTUnwrap(logs.last)
XCTAssertTrue(cancellationLog.contains("[API][景区空境库][Cancelled] GET"))
XCTAssertTrue(cancellationLog.contains("scenic_media_id=501"))
XCTAssertFalse(logs.joined().contains("[Failure]"))
XCTAssertFalse(logs.joined().contains("[Response]"))
_ = try await ScenicMaterialsAPI(client: client).sessionDetail(scenicMediaID: 501)
XCTFail("必须保留业务错误")
} catch {}
let response = try event("response.received", in: logs)
XCTAssertEqual(response["http_status"] as? Int, status)
XCTAssertEqual((response["body"] as? [String: Any])?["token"] as? String, "test-token")
XCTAssertNotNil(try event("response.rejected", in: logs))
}
}
/// 请求校验失败时没有真正的网络请求,也不输出误导性的请求或响应日志。
/// 网络失败记录原始说明和出错地址,仍向页面返回原有错误语义。
func testNetworkFailureKeepsOriginalDescriptionAndURL() async throws {
let address = "https://example.com/clip.mp4?signature=test-signature"
let error = URLError(.timedOut, userInfo: [NSLocalizedDescriptionKey: "test-network-description",
NSURLErrorFailingURLStringErrorKey: address])
var logs: [String] = []
let client = APIClient(environment: .testing, session: MockURLSession(results: [.failure(error)]),
droneDockLogSink: { logs.append($0) })
do {
_ = try await ScenicMaterialsAPI(client: client).sessionDetail(scenicMediaID: 501)
XCTFail("网络失败必须抛出")
} catch let APIError.networkFailed(message) { XCTAssertEqual(message, "请求超时,请稍后重试") }
let failure = try event("request.failed", in: logs)
XCTAssertEqual(failure["code"] as? Int, -1001)
XCTAssertEqual(failure["message"] as? String, "test-network-description")
XCTAssertEqual(failure["failing_url"] as? String, address)
}
/// 两种取消都只有请求和取消事件,不伪造响应。
func testCancellationLogsEventForBothCancellationTypes() async throws {
for error in [CancellationError(), URLError(.cancelled)] as [Error] {
var logs: [String] = []
let client = APIClient(environment: .testing, session: MockURLSession(results: [.failure(error)]),
droneDockLogSink: { logs.append($0) })
do {
_ = try await ScenicMaterialsAPI(client: client).sessionDetail(scenicMediaID: 501)
XCTFail("取消必须抛出")
} catch is CancellationError {}
XCTAssertEqual(logs.count, 2)
XCTAssertNotNil(try event("request.cancelled", in: logs))
XCTAssertFalse(logs.joined().contains("response.received"))
}
}
/// 无效参数在发起请求前被拒绝,不产生虚假网络日志。
func testInvalidRequestsProduceNoLogsOrNetworkCalls() async {
let session = MockURLSession(responses: [])
var logs: [String] = []
let api = ScenicMaterialsAPI(client: APIClient(
environment: .testing, session: session, debugLogSink: { logs.append($0) }
))
do {
_ = try await api.sessions(query: ScenicMaterialsQuery(scenicID: 0))
XCTFail("无效景区必须在网络前被拒绝")
} catch {}
let api = ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session,
droneDockLogSink: { logs.append($0) }))
do { _ = try await api.sessions(query: ScenicMaterialsQuery(scenicID: 0)); XCTFail("应拒绝") } catch {}
for id in [0, -1] {
do {
_ = try await api.sessionDetail(scenicMediaID: id)
XCTFail("无效场次必须在网络前被拒绝")
} catch {}
do { _ = try await api.sessionDetail(scenicMediaID: id); XCTFail("应拒绝") } catch {}
}
XCTAssertTrue(session.requests.isEmpty)
XCTAssertTrue(logs.isEmpty)
}
/// 无法结构化脱敏的 HTML 或纯文本仅记录大小,避免错误页带出授权地址。
func testNonJSONResponseOmitsBodyAndReportsByteCount() async throws {
let payload = Data("<html>non-json-private-token https://example.com/clip.mp4?signature=non-json-private-signature</html>".utf8)
let session = MockURLSession(responses: [payload], statusCode: 502)
/// HTML 等文本响应也完整显示,便于排查网关错误。
func testNonJSONResponsePreservesFullText() async throws {
let body = "<html>test-token https://example.com/clip.mp4?signature=test-signature</html>"
var logs: [String] = []
let api = ScenicMaterialsAPI(client: APIClient(
environment: .testing, session: session, debugLogSink: { logs.append($0) }
))
let client = APIClient(environment: .testing, session: MockURLSession(responses: [Data(body.utf8)], statusCode: 502),
droneDockLogSink: { logs.append($0) })
do { _ = try await ScenicMaterialsAPI(client: client).sessionDetail(scenicMediaID: 501); XCTFail("应失败") }
catch let APIError.httpStatus(status, _) { XCTAssertEqual(status, 502) }
XCTAssertEqual(try event("response.received", in: logs)["body"] as? String, body)
}
do {
_ = try await api.sessionDetail(scenicMediaID: 501)
XCTFail("错误页必须继续向调用者抛出")
} catch let APIError.httpStatus(status, _) {
XCTAssertEqual(status, 502)
}
let responseLog = try XCTUnwrap(logs.last)
XCTAssertTrue(responseLog.contains("status=502"))
XCTAssertTrue(responseLog.contains("\(payload.count) bytes"))
XCTAssertFalse(logs.joined().contains("non-json-private-token"))
XCTAssertFalse(logs.joined().contains("non-json-private-signature"))
XCTAssertFalse(logs.joined().contains("<html>"))
/// 根据事件名读取结构化机巢日志。
private func event(_ name: String, in logs: [String]) throws -> [String: Any] {
let objects = try logs.map(loggedJSON)
return try XCTUnwrap(objects.first { $0["event"] as? String == name })
}
/// 模块标签不能覆盖关闭正文日志的选项,请求与响应仍只记录概要。
+30 -12
View File
@@ -1,10 +1,28 @@
# 机巢工作台页面接口对接记录
> 更新日期:2026-10-30
> **当前禁飞限制(优先于下文历史联调记录):**按用户最新要求,调试不得向真实无人机下发指令。Debug 准备页禁止真实创建和召唤;统一网络层在传输前阻断 `tasks/create`、机场操作请求(包括 `shoot/start-shoot/command/live` 及未确认的新接口)。状态 GET 仅允许已确认的 `home/plane-status/shooting/status`,其中实时采集参数强制为 `live_battery=0` 或 `live_metrics=0`。只有完全不联网的 Mock 传输可以验证原始请求合同。下文任务 6、11 的真实召唤均发生于此限制之前,不作为继续真实联调的授权。
> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;按用户最新要求,`shooting` 已取消定时轮询,仅在进入页面、页面可见时返回前台或手动刷新时各读取一次同一任务。准备页 `plane-status` 保持轮询。最新 2026-10-29 17:18–17:19 模拟器实操新建任务 11,再以 `{id:11,restart:false}` 召唤;两个接口均成功,绑定飞机 61、航线任务 1931。17:19:04 首次查询允许开始,17:19:59 手动回查已为航线执行失败、禁止拍摄,当前待朱工定位 1931 失败原因与自动派机条件(见 7.7.3)。任务 6 / 航线 1926 的先前失败记录保留。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;`start-shoot` 已实现纯本地模拟(见 7.6.2),真实开拍入口保持禁用;`command` 已实现纯本地模拟(见 7.6.3),真实控制保持禁用;图传已于 2026-11-02 接入火山 RTC 参数与播放器(Release 手动开启,Debug 保持拦截,真实画面待用户联调,见 7.6.5);2026-10-30 已完成真实成片上传、保存及回查,见 9.4。
> 更新日期:2026-11-02
> **最新 Release 授权(覆盖下文历史禁飞范围):**用户已明确回复“开放 Release 真实操作,Debug 保持拦截”。Release 开放真实创建、召唤、开拍、安全控制及手动图传,使用现有身份、门禁和防重校验;Debug 仍拦截。代理仅用模拟器/隔离替身验证,真实操作由用户自行测试。
> **Debug 禁飞限制(Release 以本页最新授权为准):**按用户最新要求,调试不得向真实无人机下发指令。Debug 准备页禁止真实创建和召唤;统一网络层在传输前阻断 `tasks/create`、机场操作请求(包括 `shoot/start-shoot/command/live` 及未确认的新接口)。状态 GET 仅允许已确认的 `home/plane-status/shooting/status`,其中实时采集参数强制为 `live_battery=0` 或 `live_metrics=0`。只有完全不联网的 Mock 传输可以验证原始请求合同。下文任务 6、11 的真实召唤均发生于此限制之前,不作为继续真实联调的授权。
> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;2026-11-02 按用户要求恢复 `shooting` 前台轮询:进入及回前台立即读取,之后每次请求结束按 `poll_hint_ms` 延时再读,默认 5 秒、限制 2~30 秒;离页/后台停止,刷新保留旧快照。准备页 `plane-status` 保持轮询。最新 2026-10-29 17:18–17:19 模拟器实操新建任务 11,再以 `{id:11,restart:false}` 召唤;两个接口均成功,绑定飞机 61、航线任务 1931。17:19:04 首次查询允许开始,17:19:59 手动回查已为航线执行失败、禁止拍摄,当前待朱工定位 1931 失败原因与自动派机条件(见 7.7.3)。任务 6 / 航线 1926 的先前失败记录保留。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;`start-shoot` 已实现纯本地模拟(见 7.6.2),真实开拍入口保持禁用;`command` 已实现纯本地模拟(见 7.6.3),真实控制保持禁用;图传已于 2026-11-02 接入火山 RTC 参数与播放器(Release 手动开启,Debug 保持拦截,真实画面待用户联调,见 7.6.5);2026-10-30 已完成真实成片上传、保存及回查,见 9.4。
> 用途:记录每个页面实际调用的接口、提供人、调用时机、请求参数和返回 JSON,供 iOS 与后端持续联调。
## 2026-11-02:任务状态轮询与 Release 日志
- `shooting` 恢复轮询,只读同一 `task_id`,始终 `live_battery=0`。默认五秒,后端 `plane_status.poll_hint_ms` 限制为 2~30 秒;从上次请求结束后计时,操作提交期间暂停。
- 离页、后台取消请求和计时,返回前台立即读取;普通失败保留旧数据并在下一周期重试,身份失效停止旧任务读取。轮询不会调用 `live`、创建任务或重发飞控请求。
- 新增 Debug/Release 共用的 `[DroneDock]` 系统日志,包含请求关联、完整响应、业务状态、页面生命周期和 RTC 回调。使用说明见 [Release 日志与轮询](docs/9.9.1/Release机巢日志与轮询-2026-11-02.md)。历史“不轮询”记录仅描述当时版本。
- 按后续要求扩大到机巢全部业务接口:机场、张工 multi-plane、景区空境库和共用 STS 均逐次打印请求与完整 JSON 响应,包含重复轮询;文件上传/下载另记录传输摘要。控制台统一过滤 `[DroneDock]`,或按 `path`、`request_id` 定位。
- 最新用户要求取消控制台脱敏:请求头、URL、JSON/文本响应原样记录,包含 RTC/STS 字段;不再替换 `<redacted>`。仅影响日志,不改变 UI 脱敏展示、文档历史示例或 Debug 禁飞限制。
## 2026-11-02:准备页长名称与提交反馈
- 点位卡片的名称完整换行,整行按最长名称统一增高;当前点位的航线标题同样完整换行,保留右侧航线数量。
- 创建和召唤成功后不在正式准备页显示回执 JSON、任务 ID 或大块调试结果。任务身份及原始 data 仍供流程、控制台日志使用,订单次数摘要照常更新。
- 创建失败、召唤失败分别显示业务原因;结果未知继续提示核对且锁定重复提交。明确包含未报备、报备未生效/失败/过期等文字时,显示“请先完成飞行报备”提醒,保留已选点位和航线,不继续召唤。
- 用户提供的真实日志是 `shoot` 返回 `code=100099`、`msg=任务已结束,无法召唤;失败后请传 restart=true 重新召唤`,不是 `tasks/create` 未报备。不能仅凭 `100099` 判定报备问题。该场景保留原任务,按钮改为“查看拍摄任务”,必须明确点击才导航;不自动重发首次召唤、不自动 `restart=true`。
- 尚未收到真实“未报备”响应或专用错误码,当前按明确中文错误语义兼容,使用隔离替身验证;真实错误码合同后续可补充。
- 验证:准备页相关 89 项模拟器测试全部通过;已检查长名称、未报备弹窗和任务已结束提示的截图。Release 无签名编译通过。本轮未创建真实任务、召唤无人机或开启图传。
## 1. 阅读说明
- **底部安全控制模拟入口**:`--dock-command-mock` 直接进入模拟拍摄中;支持暂停、继续、返航及取消返航,右上角查看完整请求与回执。只在内存处理,详见 7.6.3。
@@ -40,7 +58,7 @@
| 收款记录页 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/receipts` | 已接入,支持分页 |
| 拍摄准备页:已购套餐、点位、航线、次数 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/project-info` | 已接入 |
| 拍摄准备页:机巢连接、推荐无人机状态与电量 | 朱工 | `GET /api/app/airport/plane-status` | 已接入,页面可见且 App 活跃时轮询 |
| 拍摄准备页:创建待飞任务并展示回执 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/tasks/create` | 已实测成功;最新 16:03:01 创建 task_id=6,剩余 5,随后调用 shoot |
| 拍摄准备页:创建待飞任务 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/tasks/create` | 已实测成功;最新 16:03:01 创建 task_id=6,剩余 5,随后调用 shoot |
| 拍摄准备页:对已创建任务确认并召唤 | 朱工 | `POST /api/app/airport/shoot` | 16:03:31 真实成功,id=6 且省略 plane_id;回执绑定飞机 61、航线任务 1926,业务成功后进入同任务页 |
| 拍摄任务页:任务摘要、六项读数与阶段状态 | 朱工 | `GET /api/app/airport/shooting` | 已接入,取消定时轮询;进入、可见时返回前台或手动刷新各读一次;16:04:52 任务 6 的航线执行失败、门禁阻止拍摄 |
| 拍摄任务页:开始拍摄 | 朱工 | `POST /api/app/airport/start-shoot` | 已实现纯内存 Mock;真实入口禁用,84 项相关测试通过,见 7.6.2 |
@@ -604,7 +622,7 @@ API:[DroneDockPreparationAPI.swift](suixinkan/Features/DroneDock/API/DroneDock
2. 准备页出现后分别请求张工 `project-info` 和朱工 `plane-status`,购买配置与设备状态独立更新;不请求定位,也不调用 `workbench`。
3. 页面下拉或点击“刷新状态”重新读取两个接口。无人机状态还在页面可见且 App 活跃时持续轮询,每次响应完成后等待 `poll_hint_ms` 建议间隔再请求,默认 5 秒并限制在 5~60 秒;不叠加未完成请求。
4. 离开页面或 App 失去活跃状态时取消状态请求与轮询,返回前台且页面可见时重新读取。状态接口失败会清除旧设备状态并显示未知,不清空已购配置或改变所选点位、航线。
5. 用户首次明确点击“确认并召唤”后,先重新请求 `project-info` 复核权限、次数和所选点位航线,再发送一次 `tasks/create`;创建成功后自动以返回的 `task_id` 作为朱工 `shoot.id` 提交召唤。召唤业务成功后自动跳转到拍摄任务页,传递同一个任务 ID、订单和景区身份。准备页仍保留两份回执。详见第 7.5~7.7 节。
5. 用户首次明确点击“确认并召唤”后,先重新请求 `project-info` 复核权限、次数和所选点位航线,再发送一次 `tasks/create`;创建成功后自动以返回的 `task_id` 作为朱工 `shoot.id` 提交召唤。召唤业务成功后自动跳转到拍摄任务页,传递同一个任务 ID、订单和景区身份。内部仍保留两份回执,正式准备页不展示成功 JSON。详见第 7.5~7.7 节。
6. 已有创建回执时保留该任务 ID。`shoot` 明确业务拒绝后允许“重试召唤”,只重试同任务的 `shoot`,不重建任务;召唤成功或结果未知时锁定再次提交。从任务页返回后,准备页按钮显示“查看拍摄任务”,再次点击只进入该任务,不重复创建或召唤。进入准备页、购买刷新和无人机轮询均不自动创建任务或发送召唤;`shooting` 由任务页出现后读取。
| 页面内容 | 权威数据来源 |
@@ -615,7 +633,7 @@ API:[DroneDockPreparationAPI.swift](suixinkan/Features/DroneDock/API/DroneDock
| 样片元数据 | `air_lines[].samples` 已解析保留,当前准备页尚未新增样片播放入口 |
| 机巢连接 | 朱工 `plane-status.connected`;true 已连接、false 未连接、缺失或请求失败待确认 |
| 无人机工作状态与电量 | 优先使用朱工 `plane-status.recommend.status_text`;不按设备列表自行重选推荐设备 |
| 待飞任务 ID 与创建结果 | 张工 `tasks/create.task_id` 及完整 `data` JSON;仅明确点击后创建 |
| 待飞任务 ID 与创建结果 | 张工 `tasks/create.task_id` 及 `data`(内部使用与控制台日志,不在页面展示 JSON);仅明确点击后创建 |
| 召唤提交结果 | 朱工 `shoot` 的业务成功/错误及实际 `data` JSON;已取得任务 6 成功样本,订单飞行任务 ID 读取 `order_flight_task.id`,见 7.7.2 |
| 任务状态与后续飞行阶段 | 拍摄任务页读取朱工 `shooting` 的任务摘要、`ui/execute_gate`、`current_plane` 和六项读数;准备页不直接读取,见 7.6 |
| 实际飞行执行 | 当前只接召唤提交,不执行 `start-shoot/command`;连接成功、空闲、`can_fly=true` 或召唤受理均不能表示已到达、已起飞或拍摄完成 |
@@ -941,7 +959,7 @@ API:[DroneDockPlaneStatusAPI.swift](suixinkan/Features/DroneDock/API/DroneDock
`POST /api/yf-handset-app/photog/multi-plane/tasks/create`
**创建已实测成功:11:56:26 创建任务 1;16:03:01 按用户明确要求重新创建一次,返回任务 6。** 当前流程使用创建回执 ID 调用朱工 `shoot`;任务 6 于 16:03:31 的召唤接口业务成功,16:04:52 回查显示航线执行失败,详见 7.7.2。成功后自动进入拍摄任务页的客户端流程由网络替身验证;准备页保留两份回执,返回后可查看原任务。新任务 6 是用户明确要求的一次新建,不是对任务 2 失败的自动重建或重试。本轮未调用 `start-shoot/command`。
**创建已实测成功:11:56:26 创建任务 1;16:03:01 按用户明确要求重新创建一次,返回任务 6。** 当前流程使用创建回执 ID 调用朱工 `shoot`;任务 6 于 16:03:31 的召唤接口业务成功,16:04:52 回查显示航线执行失败,详见 7.7.2。成功后自动进入拍摄任务页的客户端流程由网络替身验证;内部保留两份回执,正式准备页不展示成功 JSON,返回后可查看原任务。新任务 6 是用户明确要求的一次新建,不是对任务 2 失败的自动重建或重试。本轮未调用 `start-shoot/command`。
| 参数 | 必填 | 当前来源 |
| --- | --- | --- |
@@ -967,7 +985,7 @@ ID 必须为正整数。请求仅包含上述四项,不传 `project_id`、无
1. 已成功加载当前订单购买配置,身份和订单项目对应;`can_create_task=true`、总次数有效且大于 0、剩余次数大于 0;所选点位与航线的 `available` 均明确为 true 时,允许首次点击。先创建待飞任务再提交召唤,不以 `plane-status` 的连接、电量或 `can_fly` 作为创建门槛。
2. 点击后立即禁用重复提交并冻结点位航线,重新读取张工 `project-info`。如权限或次数已失效,则不发送 POST;原选择已失效时提示重新选择,不把此次点击自动转交给另一条航线。
3. 预检通过后只发送一次 `tasks/create`。响应校验任务 ID 及订单归属,页面展示返回的 `data`,保留未建模字段;不拼造 `code/msg/time` 或飞行状态。创建后的次数以返回的最新订单摘要为准,客户端不自行扣次。
3. 预检通过后只发送一次 `tasks/create`。响应校验任务 ID 及订单归属,内部保留返回的 `data` 及未建模字段,正式页面不展示 JSON;不拼造 `code/msg/time` 或飞行状态。创建后的次数以返回的最新订单摘要为准,客户端不自行扣次。
4. 创建成功后自动以同一个 `task_id` 请求 `shoot`,提交期间显示“正在召唤无人机…”并禁用重复点击。已创建任务始终保留创建回执及防重建锁;召唤重试也不会再发送 `tasks/create`。普通购买刷新、设备轮询、同实例离开返回均不清除此锁。
5. 创建被后端明确业务拒绝时展示其错误,允许用户再次点击;购买预检失败尚未发出 POST,可重试。创建 POST 超时、网络/HTTP/解码错误,以及提交后取消或离开而结果未知时,显示“结果待核对”并保留防重复锁,不自动重发,也不继续调用 `shoot`。需先核对订单任务,再决定后续处理;本轮不增加未知创建结果的自动核对接口或任务重建流程。
6. 账号、Token、景区或门店变化后拒绝迟到回执,旧页面实例不能恢复创建入口。
@@ -1208,7 +1226,7 @@ HTTP 200,完整业务响应:
}
```
客户端仅在已注入开拍服务、最近一次读取成功、就绪状态无冲突、`execute_gate.can_execute=true`、`ui.primary_action=start_shoot`、已绑定正数飞机 ID,且没有进行中/已成功/结果未知的开拍请求时启用按钮。POST 成功并核对任务、订单、景区与飞机身份后,单次 GET 同一任务 `shooting`,不恢复轮询。刷新期间保留旧快照,直到回查成功再更新页面,不把 POST 成功直接当成设备开始拍摄。
客户端仅在已注入开拍服务、最近一次读取成功、就绪状态无冲突、`execute_gate.can_execute=true`、`ui.primary_action=start_shoot`、已绑定正数飞机 ID,且没有进行中/已成功/结果未知的开拍请求时启用按钮。POST 成功并核对任务、订单、景区与飞机身份后,单次 GET 同一任务 `shooting`,然后恢复前台可见时的状态轮询(2026-11-02)。刷新期间保留旧快照,直到回查成功再更新页面,不把 POST 成功直接当成设备开始拍摄。
连续点击只发送一次;明确业务拒绝可手动重试,超时、响应无法确认、发送后取消等锁定重复提交,只允许状态回查。页面离开或身份变化后丢弃迟到回执。底部安全控制的真实请求仍被禁用;2026-10-30 新增纯本地模拟指令流程,见 7.6.3。
@@ -1252,7 +1270,7 @@ HTTP 200,完整业务响应:
}
```
当前正式入口不注入指令服务;Debug 网络层继续拦截所有真实 command。模拟页仅在快照 `ui.commands` 明确给出白名单指令、任务及锁定飞机有效时启用;不将开拍 `execute_gate.can_execute` 当成暂停/返航许可。回执必须回显同一任务和指令,成功后只 GET 同一任务一次;无轮询,不用受理回执直接替代状态快照。
当前正式入口不注入指令服务;Debug 网络层继续拦截所有真实 command。模拟页仅在快照 `ui.commands` 明确给出白名单指令、任务及锁定飞机有效时启用;不将开拍 `execute_gate.can_execute` 当成暂停/返航许可。回执必须回显同一任务和指令,成功后 GET 同一任务一次并恢复前台状态轮询;不自动重发控制指令,不用受理回执直接替代状态快照。
提交期间按钮互斥并保留旧 UI。明确拒绝可手动重试;超时、异常回执、发出后取消等结果未知时锁定控制操作,仍可手动只读刷新。迟滞快照下已受理的同项指令不会重发;账号/景区变化时拒绝旧响应。返航前确认;模拟返航按文档标记任务中断,取消返航也不会恢复任务、重新创建或自动开拍。
@@ -1592,7 +1610,7 @@ GET /api/yf-handset-app/photog/multi-plane/tasks?scenic_id=271&order_number=TEST
`GET /api/app/config/get-sts-token?bucket=default`
复用现有 `UploadAPI`,使用同一登录 Token。以下为**依据张工文档及现有模型整理的格式示例,非本次实测**;所有凭证均为占位值,控制台不输出真实 STS 响应体。
复用现有 `UploadAPI`,使用同一登录 Token。以下为**依据张工文档及现有模型整理的格式示例,非本次实测**;所有凭证均为占位值;按 2026-11-02 最新用户要求,控制台会输出完整 STS 响应体。
```json
{
@@ -1725,7 +1743,7 @@ UI 验证:确认页 5 项与共用交付流程 8 项回归全部通过,导
| 页面/功能 | 当前实现状态 | 文档中的后续候选接口与提供人 | 返回 JSON 记录 |
| --- | --- | --- | --- |
| 历史演示订单页 `DroneShootingOrdersViewController` | 仅演示流程继续使用本地数据;正式首页“查看全部”已进入真实 `DroneDockOrdersViewController` | 正式页张工 `GET /orders` 已接入,见 4.4 | 演示数据不能作为接口实测证据 |
| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台或导航栏/中间刷新各只读一次,无下拉刷新或定时轮询;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;`/airport/start-shoot` 已实现纯本地模拟、真实入口禁用;`/airport/command` 已实现纯本地模拟、真实入口禁用;图传 `/airport/live` 已预接请求及本地播放,待补真实播放合同;失败重召唤 `shoot restart=true` 已完成本地模拟,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;开始拍摄模拟回执见 7.6.2;尚无真实开始拍摄或控制成功记录 |
| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台立即读取,随后串行轮询同一任务,导航栏支持手动刷新,无下拉刷新;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;`/airport/start-shoot` 已实现纯本地模拟、真实入口禁用;`/airport/command` 已实现纯本地模拟、真实入口禁用;图传 `/airport/live` 已预接请求及本地播放,待补真实播放合同;失败重召唤 `shoot restart=true` 已完成本地模拟,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;开始拍摄模拟回执见 7.6.2;尚无真实开始拍摄或控制成功记录 |
| 历史素材演示/下载 `DroneMaterialsViewController`、`DroneMaterialPreviewViewController` | 仅演示流程保留;正式入口已切换真实素材库,正式下载与保存相册见 8.3 | 张工返回有效原素材 URL,由客户端直接下载;历史演示仍不代表真实下载 | 正式页面响应见第 8 节 |
| 历史交付演示 `DroneDeliveryUploadViewController`、`DroneDeliveryReviewViewController` | 仅演示流程保留;正式上传使用第 9 节新共用页,正式游客确认使用 9.5 新页 | 张工 `POST /orders/confirm-code`、`GET /orders/detail` 已实现 | 正式上传记录见第 9 节;游客确认暂无真实扫码回执,模拟结果见 9.5 |
| 收款页“线下收款” | 跳转既有 `OfflineCollectionRegistrationViewController` | 复用原通用线下收款模块,不属于本次机巢类型 25 专用接口接入 | 本文未审计该旧模块 JSON,不将它记为新接口已打通 |