feat: 接入景区空境库真实素材并统一交付入口
接通场次详情、分页、视频时长与大小,修复日期筛选越界并增加脱敏日志。统一订单与素材库交付方式弹窗,保留任务预选和上传批次,补充模拟器回归测试与接口记录。
This commit is contained in:
@@ -23,6 +23,7 @@ final class APIClient {
|
||||
private let encoder: JSONEncoder
|
||||
private let decoder: JSONDecoder
|
||||
private let notificationCenter: NotificationCenter
|
||||
private let debugLogSink: (String) -> Void
|
||||
private var authTokenProvider: (() -> String?)?
|
||||
|
||||
private let environment: APIEnvironment
|
||||
@@ -37,13 +38,15 @@ final class APIClient {
|
||||
decoder: JSONDecoder = JSONDecoder(),
|
||||
appVersion: String = AppClientInfo.appVersion(),
|
||||
osType: String = AppClientInfo.osType,
|
||||
notificationCenter: NotificationCenter = .default
|
||||
notificationCenter: NotificationCenter = .default,
|
||||
debugLogSink: @escaping (String) -> Void = { print($0) }
|
||||
) {
|
||||
self.environment = environment
|
||||
self.session = session
|
||||
self.encoder = encoder
|
||||
self.decoder = decoder
|
||||
self.notificationCenter = notificationCenter
|
||||
self.debugLogSink = debugLogSink
|
||||
self.appVersion = appVersion.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? "1.0.0"
|
||||
self.osType = osType.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? AppClientInfo.osType
|
||||
}
|
||||
@@ -69,26 +72,29 @@ final class APIClient {
|
||||
let request = try DeviceCommandDebugPolicy.prepare(
|
||||
makeURLRequest(apiRequest, tokenOverride: tokenOverride),
|
||||
isLocalSimulation: session is any LocalSimulationURLSession)
|
||||
logRequest(request, includeBody: apiRequest.logsPayload)
|
||||
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")
|
||||
logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory)
|
||||
throw CancellationError()
|
||||
} catch let error as URLError {
|
||||
if error.code == .cancelled {
|
||||
logCancelled(for: request, reason: "URLError.cancelled")
|
||||
logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory)
|
||||
throw CancellationError()
|
||||
}
|
||||
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
|
||||
throw APIError.networkFailed(networkErrorMessage(for: error))
|
||||
} catch {
|
||||
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
|
||||
throw APIError.networkFailed(error.localizedDescription)
|
||||
}
|
||||
|
||||
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload)
|
||||
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)
|
||||
@@ -374,8 +380,12 @@ final class APIClient {
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印请求信息(含 GET 查询参数与 POST 请求体,对齐 Android Ktor `LogLevel.BODY`)。
|
||||
private func logRequest(_ request: URLRequest, includeBody: Bool = true) {
|
||||
private func logRequest(_ request: URLRequest, includeBody: Bool = true, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.request(request, category: category, includeBody: includeBody))
|
||||
return
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
var lines = ["[API][Request] \(method) \(url)"]
|
||||
@@ -396,27 +406,47 @@ final class APIClient {
|
||||
lines.append("body:\n\(body)")
|
||||
}
|
||||
|
||||
print(lines.joined(separator: "\n"))
|
||||
debugLogSink(lines.joined(separator: "\n"))
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印响应状态和响应体。
|
||||
private func logResponse(for request: URLRequest, response: URLResponse, data: Data, includeBody: Bool = true) {
|
||||
private func logResponse(for request: URLRequest, response: URLResponse, data: Data,
|
||||
includeBody: Bool = true, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.response(for: request, response: response, data: data,
|
||||
category: category, includeBody: includeBody))
|
||||
return
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
let statusCode = (response as? HTTPURLResponse).map { String($0.statusCode) } ?? "unknown"
|
||||
let body = includeBody ? Self.debugResponseBody(from: data) : "<sensitive payload omitted>"
|
||||
print("[API][Response] \(method) \(url) status=\(statusCode)\n\(body)")
|
||||
debugLogSink("[API][Response] \(method) \(url) status=\(statusCode)\n\(body)")
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印被取消的请求信息。
|
||||
private func logCancelled(for request: URLRequest, reason: String) {
|
||||
private func logCancelled(for request: URLRequest, reason: String, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.event("Cancelled", for: request, category: category) + " reason=\(reason)")
|
||||
return
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
print("[API][Cancelled] \(method) \(url) reason=\(reason)")
|
||||
debugLogSink("[API][Cancelled] \(method) \(url) reason=\(reason)")
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 记录已开启模块日志的传输失败,只输出错误域和错误码,避免错误描述夹带凭证。
|
||||
private func logFailure(for request: URLRequest, error: Error, category: String?) {
|
||||
#if DEBUG
|
||||
guard let category else { return }
|
||||
let error = error as NSError
|
||||
debugLogSink(APIRedactedLog.event("Failure", for: request, category: category)
|
||||
+ " error=\(error.domain)(\(error.code))")
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import Foundation
|
||||
|
||||
/// 按模块生成可读的调试日志;只处理输出副本,不修改网络请求和业务响应。
|
||||
nonisolated enum APIRedactedLog {
|
||||
private static let urlPattern = try? NSRegularExpression(pattern: #"https?://[^\s"<>]+"#, options: [.caseInsensitive])
|
||||
|
||||
/// 输出方法、地址、查询参数及可选 JSON 请求体,不输出鉴权 Header。
|
||||
static func request(_ request: URLRequest, category: String, includeBody: Bool) -> String {
|
||||
var lines = [event("Request", for: request, category: category)]
|
||||
if let url = request.url,
|
||||
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems,
|
||||
!items.isEmpty {
|
||||
lines.append("params: " + items.map {
|
||||
"\($0.name)=\(isSensitive($0.name) ? "<redacted>" : redactURLs(in: $0.value ?? ""))"
|
||||
}.joined(separator: "&"))
|
||||
}
|
||||
if includeBody, let data = request.httpBody {
|
||||
lines.append("body:\n" + body(data))
|
||||
}
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
/// 输出 HTTP 状态及格式化的脱敏 JSON,包括业务失败或非 2xx 响应。
|
||||
static func response(for request: URLRequest, response: URLResponse, data: Data,
|
||||
category: String, includeBody: Bool) -> String {
|
||||
let status = (response as? HTTPURLResponse).map { String($0.statusCode) } ?? "unknown"
|
||||
let payload = includeBody ? body(data) : "<sensitive payload omitted>"
|
||||
return event("Response", for: request, category: category) + " status=\(status)\n" + payload
|
||||
}
|
||||
|
||||
/// 生成请求、响应、失败和取消共用的模块标签与安全地址。
|
||||
static func event(_ event: String, for request: URLRequest, category: String) -> String {
|
||||
let url = request.url.map { redactedURL($0, keepsQuery: true) } ?? "<invalid url>"
|
||||
return "[API][\(category)][\(event)] \(request.httpMethod ?? "REQUEST") \(url)"
|
||||
}
|
||||
|
||||
/// 非 JSON 正文可能包含凭证或服务端调试页面,不把原始文本写入控制台。
|
||||
private static func body(_ data: Data) -> String {
|
||||
guard !data.isEmpty else { return "<empty body>" }
|
||||
guard let object = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]),
|
||||
let formatted = try? JSONSerialization.data(withJSONObject: redact(object),
|
||||
options: [.prettyPrinted, .sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes]),
|
||||
let text = String(data: formatted, encoding: .utf8) else {
|
||||
return "<non-JSON body omitted: \(data.count) bytes>"
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
/// 递归处理嵌套对象与数组,保留普通字段、空值及 JSON 类型。
|
||||
private static func redact(_ value: Any) -> Any {
|
||||
if let object = value as? [String: Any] {
|
||||
return Dictionary(uniqueKeysWithValues: object.map { key, value in
|
||||
(key, isSensitive(key) ? "<redacted>" : redact(value))
|
||||
})
|
||||
}
|
||||
if let array = value as? [Any] { return array.map(redact) }
|
||||
if let text = value as? String { return redactURLs(in: text) }
|
||||
return value
|
||||
}
|
||||
|
||||
/// 兼容 snake_case、大小写及 OSS/S3 常用签名字段。
|
||||
private static func isSensitive(_ key: String) -> Bool {
|
||||
let normalized = key.lowercased().filter { $0.isLetter || $0.isNumber }
|
||||
return ["token", "authorization", "signature", "credential", "accesskey", "secret", "password", "cookie"]
|
||||
.contains { normalized.contains($0) }
|
||||
}
|
||||
|
||||
/// JSON 字段或消息中的 URL 只保留资源路径,不记录有效期、签名及其他查询值。
|
||||
private static func redactURLs(in text: String) -> String {
|
||||
guard let pattern = urlPattern else { return text }
|
||||
var result = text
|
||||
for match in pattern.matches(in: text, range: NSRange(text.startIndex..., in: text)).reversed() {
|
||||
guard let range = Range(match.range, in: result) else { continue }
|
||||
let replacement = URL(string: String(result[range])).map { redactedURL($0, keepsQuery: false) }
|
||||
?? "<redacted URL>"
|
||||
result.replaceSubrange(range, with: replacement)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// 请求地址保留业务查询值;正文中的资源地址删除完整查询,兼容未来签名参数。
|
||||
private static func redactedURL(_ url: URL, keepsQuery: Bool) -> String {
|
||||
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return "<redacted URL>" }
|
||||
components.user = nil
|
||||
components.password = nil
|
||||
components.fragment = nil
|
||||
if keepsQuery {
|
||||
components.queryItems = components.queryItems?.map {
|
||||
URLQueryItem(name: $0.name, value: isSensitive($0.name) ? "<redacted>" : $0.value.map(redactURLs))
|
||||
}
|
||||
} else {
|
||||
components.query = nil
|
||||
}
|
||||
return components.string ?? "<redacted URL>"
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@ nonisolated struct APIRequest<Response: Decodable> {
|
||||
var body: AnyEncodable?
|
||||
/// 敏感请求关闭正文日志,避免验证码和注销资产进入调试日志。
|
||||
var logsPayload: Bool
|
||||
/// 为指定模块输出带标签的脱敏日志;隐藏凭证字段和响应中媒体 URL 的查询参数。
|
||||
var redactedLogCategory: String?
|
||||
|
||||
/// 创建一个 API 请求,并把可编码请求体擦除为统一的 AnyEncodable。
|
||||
init<Body: Encodable>(
|
||||
@@ -31,7 +33,8 @@ nonisolated struct APIRequest<Response: Decodable> {
|
||||
queryItems: [URLQueryItem] = [],
|
||||
headers: [String: String] = [:],
|
||||
body: Body? = Optional<EmptyPayload>.none,
|
||||
logsPayload: Bool = true
|
||||
logsPayload: Bool = true,
|
||||
redactedLogCategory: String? = nil
|
||||
) {
|
||||
self.method = method
|
||||
self.path = path
|
||||
@@ -39,6 +42,7 @@ nonisolated struct APIRequest<Response: Decodable> {
|
||||
self.headers = headers
|
||||
self.body = body.map(AnyEncodable.init)
|
||||
self.logsPayload = logsPayload
|
||||
self.redactedLogCategory = redactedLogCategory
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user