import Foundation /// 课程附件允许在 App 内预览的文件格式,旧版 DOC 不作为 DOCX 处理。 enum TrainingDocumentKind: String, Sendable { case pdf, docx, txt, md /// 优先使用附件名称中的格式;无扩展名时才参考 URL 和 MIME。 static func resolve(name: String, mimeType: String, url: URL) throws -> Self { let namedExtension = (name as NSString).pathExtension.lowercased() let fileExtension = namedExtension.isEmpty ? url.pathExtension.lowercased() : namedExtension if !fileExtension.isEmpty { guard let kind = Self(rawValue: fileExtension) else { throw TrainingDocumentError.unsupported } return kind } switch mimeType.lowercased().split(separator: ";").first.map(String.init) { case "application/pdf": return .pdf case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": return .docx case "text/plain": return .txt case "text/markdown", "text/x-markdown": return .md default: throw TrainingDocumentError.unsupported } } } /// 单次预览持有的私有临时文件,离开页面或切换附件后明确清理。 struct TrainingLocalDocument: Sendable { let fileURL: URL let kind: TrainingDocumentKind let name: String let temporaryDirectory: URL? /// 只清理由下载器为本次预览创建的目录。 func removeTemporaryFile() { if let temporaryDirectory { try? FileManager.default.removeItem(at: temporaryDirectory) } } } /// 下载替身与正式实现共用的入口;不依赖视图或 App 登录客户端。 protocol TrainingDocumentLoading: Sendable { /// 原样读取授权链接,返回预览器可使用的本地文件。 func load(attachment: TrainingAttachmentInfo, link: TrainingAttachmentLink) async throws -> TrainingLocalDocument } /// 文件预览失败的可恢复原因。 enum TrainingDocumentError: LocalizedError { case unsupported, invalidURL, tooLarge, empty, invalidResponse, invalidFile var errorDescription: String? { switch self { case .unsupported: return "暂不支持此文件格式,请使用 PDF、DOCX、TXT 或 MD" case .invalidURL: return "附件访问地址无效,请重试" case .tooLarge: return "附件超过 30 MB,暂时无法预览" case .empty: return "附件内容为空" case .invalidResponse: return "附件下载失败,请重试" case .invalidFile: return "附件格式不正确或文件已损坏" } } } /// 独立的无凭证文件下载器,不复用带 Token 的业务网络会话。 final class TrainingDocumentLoader: TrainingDocumentLoading, @unchecked Sendable { static let maximumBytes = 30 * 1_024 * 1_024 private let session: URLSession /// 使用短期、无 Cookie、无凭证存储的下载会话。 init() { let configuration = URLSessionConfiguration.ephemeral configuration.httpCookieStorage = nil configuration.httpShouldSetCookies = false configuration.urlCredentialStorage = nil configuration.urlCache = nil configuration.timeoutIntervalForRequest = 60 configuration.timeoutIntervalForResource = 120 session = URLSession(configuration: configuration) } /// 下载时保留 URL 的完整签名参数;文件名不会参与磁盘路径拼接。 func load(attachment: TrainingAttachmentInfo, link: TrainingAttachmentLink) async throws -> TrainingLocalDocument { guard Self.isAllowed(link.url) else { throw TrainingDocumentError.invalidURL } let kind = try TrainingDocumentKind.resolve(name: attachment.name, mimeType: attachment.mimeType, url: link.url) guard attachment.sizeBytes <= Self.maximumBytes else { throw TrainingDocumentError.tooLarge } var request = URLRequest(url: link.url, cachePolicy: .reloadIgnoringLocalCacheData) request.httpShouldHandleCookies = false let delegate = TrainingDocumentDownloadDelegate() let download: URL let response: URLResponse do { (download, response) = try await session.download(for: request, delegate: delegate) } catch { if delegate.exceededSize { throw TrainingDocumentError.tooLarge } throw error } defer { try? FileManager.default.removeItem(at: download) } try Task.checkCancellation() guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), let finalURL = http.url, Self.isAllowed(finalURL) else { throw TrainingDocumentError.invalidResponse } let size = (try FileManager.default.attributesOfItem(atPath: download.path)[.size] as? NSNumber)?.intValue ?? 0 guard size > 0 else { throw TrainingDocumentError.empty } guard size <= Self.maximumBytes, response.expectedContentLength <= Self.maximumBytes else { throw TrainingDocumentError.tooLarge } let directory = FileManager.default.temporaryDirectory.appendingPathComponent("training-preview-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) do { let target = directory.appendingPathComponent("document.\(kind.rawValue)") try FileManager.default.moveItem(at: download, to: target) try Task.checkCancellation() return TrainingLocalDocument(fileURL: target, kind: kind, name: attachment.name, temporaryDirectory: directory) } catch { try? FileManager.default.removeItem(at: directory) throw error } } /// 授权文件与重定向均只允许有效 HTTP/HTTPS 地址。 static func isAllowed(_ url: URL) -> Bool { ["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host?.isEmpty == false && url.user == nil && url.password == nil } deinit { session.invalidateAndCancel() } } /// 下载过程中限制体积;重定向不允许进入本地协议或携带账号口令。 private final class TrainingDocumentDownloadDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { private let lock = NSLock() private var sizeExceeded = false var exceededSize: Bool { lock.withLock { sizeExceeded } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if totalBytesWritten > TrainingDocumentLoader.maximumBytes || totalBytesExpectedToWrite > TrainingDocumentLoader.maximumBytes { lock.withLock { sizeExceeded = true } downloadTask.cancel() } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {} func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { guard let url = request.url, TrainingDocumentLoader.isAllowed(url) else { completionHandler(nil); return } var safe = request safe.setValue(nil, forHTTPHeaderField: "Authorization") safe.setValue(nil, forHTTPHeaderField: "Cookie") safe.setValue(nil, forHTTPHeaderField: "Referer") safe.httpShouldHandleCookies = false completionHandler(safe) } }