import Foundation /// 订单确认邀请结果;图片是微信小程序码,不能再次编码为普通二维码。 struct DroneDockConfirmationCode: Decodable, Equatable, Sendable { /// 完整订单号,用于核对确认码的归属。 let orderNumber: String /// 生成成功仅表示等待游客确认,不表示订单已经完成。 let confirmStatus: Int /// 后端原样返回的小程序码图片地址。 let confirmURL: String private let validatedImageURL: URL /// 已校验的 HTTP(S) 图片地址,可直接交给图片加载组件。 var imageURL: URL { validatedImageURL } /// 张工生成确认码的响应字段。 private enum CodingKeys: String, CodingKey { case orderNumber = "order_number", confirmStatus = "confirm_status", confirmURL = "confirm_url" } /// 必要字段缺失、错误订单身份或不可展示地址均保留为失败,避免伪造确认码。 init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) orderNumber = try container.decode(String.self, forKey: .orderNumber) guard !orderNumber.isEmpty, orderNumber.count <= 128, orderNumber == orderNumber.trimmingCharacters(in: .whitespacesAndNewlines), orderNumber.rangeOfCharacter(from: .controlCharacters) == nil else { throw DecodingError.dataCorruptedError(forKey: .orderNumber, in: container, debugDescription: "确认码缺少有效订单号") } if let value = try? container.decode(Int.self, forKey: .confirmStatus) { confirmStatus = value } else if let text = try? container.decode(String.self, forKey: .confirmStatus), let value = Int(text) { confirmStatus = value } else { throw DecodingError.dataCorruptedError(forKey: .confirmStatus, in: container, debugDescription: "确认码缺少有效确认状态") } guard confirmStatus == 1 else { throw DecodingError.dataCorruptedError(forKey: .confirmStatus, in: container, debugDescription: "确认码未处于待游客确认状态") } confirmURL = try container.decode(String.self, forKey: .confirmURL) guard confirmURL.count <= 2048, confirmURL.rangeOfCharacter(from: .whitespacesAndNewlines.union(.controlCharacters)) == nil, let components = URLComponents(string: confirmURL), ["http", "https"].contains(components.scheme?.lowercased() ?? ""), let host = components.host, !host.isEmpty, components.user == nil, components.password == nil, let url = components.url else { throw DecodingError.dataCorruptedError(forKey: .confirmURL, in: container, debugDescription: "确认码图片地址无效") } validatedImageURL = url } }