feat(training): 支持课程附件预览与整页阅读

This commit is contained in:
2026-10-20 13:36:58 +08:00
parent 091d17ff21
commit b149295e66
53 changed files with 4233 additions and 632 deletions
@@ -0,0 +1,147 @@
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)
}
}
@@ -8,26 +8,28 @@ final class TrainingRemoteReadingViewModel {
private(set) var task: TrainingTaskDetail?
/// 已加载的课程元信息,不包含全部正文。
private(set) var course: TrainingCourseInfo?
/// 用户已请求的小节目录,首次最多二十项。
private(set) var sections: [TrainingSectionInfo] = []
/// 当前选择的小节正式正文。
private(set) var currentSection: TrainingSectionContent?
/// 当前小节标识,正文加载失败时供重试使用。
private(set) var currentSectionID: String?
/// 用户已请求的附件元信息,不包含文件内容。
private(set) var attachments: [TrainingAttachmentInfo] = []
/// 当前选中文档,授权或预览失败时仍保留,供用户重试。
private(set) var currentAttachment: TrainingAttachmentInfo?
/// 当前文档经任务授权的访问地址,不附带 App Token。
private(set) var currentAttachmentLink: TrainingAttachmentLink?
/// 每次选择或重试生成新票据,拒绝同一个附件的旧下载或渲染回调。
private(set) var attachmentPreviewID: UUID?
/// 只有当前附件已成功渲染后才可累计有效阅读。
private(set) var isAttachmentRendered = false
/// 当前附件授权或预览错误,不被进度刷新清除。
private(set) var attachmentErrorMessage: String?
/// 仅用于附件分页的提示,不阻挡当前已经显示的文档或有效阅读。
private(set) var attachmentListErrorMessage: String?
/// 最新后端确认的学习进度与资格。
private(set) var progress: TrainingProgressSnapshot?
/// 首次加载或切换正文期间阻止重复内容操作。
/// 首次加载或切换附件期间阻止重复内容操作。
private(set) var isLoading = false
/// 小节目录下一页正在加载。
private(set) var isLoadingSections = false
/// 附件目录下一页正在加载。
private(set) var isLoadingAttachments = false
/// 附件链接正在授权。
private(set) var isAuthorizingAttachment = false
/// 小节目录是否还有用户可主动读取的页面。
private(set) var hasMoreSections = false
/// 附件目录是否还有用户可主动读取的页面。
private(set) var hasMoreAttachments = false
/// 已经读取过附件第一页,避免反复取相同元信息。
@@ -47,9 +49,7 @@ final class TrainingRemoteReadingViewModel {
private let validateIdentity: @MainActor @Sendable () -> Bool
private let now: @Sendable () -> Date
private var generation = 0
private var sectionCursor: String?
private var attachmentCursor: String?
private var bodies: [String: TrainingSectionContent] = [:]
private var contentErrorMessage: String?
private var session: TrainingStudySession?
private var sessionRequestID: String?
@@ -85,7 +85,10 @@ final class TrainingRemoteReadingViewModel {
}
/// 页面展示的内容或保存错误,不用中文文案判断恢复分支。
var errorMessage: String? { readingErrorMessage ?? contentErrorMessage }
var errorMessage: String? { readingErrorMessage ?? attachmentErrorMessage ?? contentErrorMessage }
/// 当前附件标识,预览失败时用于重试同一份文档。
var currentAttachmentID: String? { currentAttachment?.id }
/// 显示未确认读时的倒计时,但只有服务器确认后才允许开始考试。
var remainingSeconds: Int {
@@ -97,16 +100,19 @@ final class TrainingRemoteReadingViewModel {
/// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。
var canStudy: Bool { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated }
/// 同课程快照中已读取的正文可直接复用,页面无需为缓存切换显示请求进度。
func isSectionCached(id: String) -> Bool { bodies[id] != nil }
/// 首次只取元信息、目录第一页、首节正文和小型进度,不预取附件或其他小节正文。
/// 首次只读课程元信息、附件第一页与进度,并为首个附件授权;不请求小节标题或 HTML。
func load() async {
guard !isLoading, !isInvalidated else { return }
let epoch = generation
isLoading = true
contentErrorMessage = nil
attachmentErrorMessage = nil
attachmentListErrorMessage = nil
resetAttachmentPreview()
pauseReading()
defer { if generation == epoch { isLoading = false } }
await flush(final: true)
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
do {
let detail = try await service.task(id: taskID)
try await checkIdentity(epoch)
@@ -115,80 +121,74 @@ final class TrainingRemoteReadingViewModel {
}
let courseID = detail.summary.courseSnapshotID
async let metadata = service.course(id: courseID, taskID: taskID)
async let directory = service.sections(courseID: courseID, taskID: taskID, cursor: nil, limit: 20)
async let documents = service.attachments(courseID: courseID, taskID: taskID, cursor: nil, limit: 20)
async let savedProgress = service.progress(taskID: taskID)
let (info, page, saved) = try await (metadata, directory, savedProgress)
try await checkIdentity(epoch)
guard let first = page.items.first else { throw TrainingRemoteError.contentMissing("暂无课程内容") }
let body = try await service.section(courseID: courseID, sectionID: first.id, taskID: taskID)
let (info, page, saved) = try await (metadata, documents, savedProgress)
try await checkIdentity(epoch)
guard saved.canViewCourse else { throw TrainingRemoteError.forbidden("当前任务不能查看课程") }
task = detail
course = info
sections = page.items
sectionCursor = page.nextCursor
hasMoreSections = page.hasMore
currentSectionID = first.id
currentSection = body
bodies[body.id] = body
attachments = page.items
attachmentCursor = page.nextCursor
hasMoreAttachments = page.hasMore
hasLoadedAttachments = true
progress = saved
if let first = attachments.first {
await prepareAttachment(first, epoch: epoch)
}
} catch { saveContentError(error, epoch: epoch) }
}
/// 返回已缓存课程时只刷新本人资格与进度,保留正文和目录缓存。
/// 返回已缓存课程时只刷新本人资格与进度,保留文档和预览错误。
func refreshProgress() async {
let epoch = generation
guard !isInvalidated else { return }
do {
let value = try await service.progress(taskID: taskID)
try await checkIdentity(epoch)
guard value.canViewCourse else { throw TrainingRemoteError.forbidden("当前任务不能查看课程") }
progress = value
if !value.canStudy || value.readingCompleted { pauseReading() }
contentErrorMessage = nil
} catch { saveContentError(error, epoch: epoch) }
}
/// 切章节立即暂停;只读取选中正文,已经看过的同快照正文直接复用。
func selectSection(id: String) async {
guard !isLoading, !isInvalidated, let course else { return }
/// 选择或重试附件时先关闭旧读时片段,再为选中的文档重新授权。
func selectAttachment(id: String) async {
guard !isLoading, !isInvalidated,
let attachment = attachments.first(where: { $0.id == id }) else { return }
let epoch = generation
isLoading = true
defer { if generation == epoch { isLoading = false } }
resetAttachmentPreview()
pauseReading()
await flush(final: true)
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
contentErrorMessage = nil
currentSectionID = id
currentSection = nil
do {
let body: TrainingSectionContent
if let cached = bodies[id] { body = cached }
else { body = try await service.section(courseID: course.id, sectionID: id, taskID: taskID) }
try await checkIdentity(epoch)
currentSection = body
bodies[id] = body
} catch { saveContentError(error, epoch: epoch) }
await prepareAttachment(attachment, epoch: epoch)
}
/// 仅用户点击加载更多时读取目录下一页,不为展示一个小节遍历全部目录。
func loadMoreSections() async {
guard !isLoadingSections, hasMoreSections, let cursor = sectionCursor, let course, !isInvalidated else { return }
let epoch = generation
isLoadingSections = true
defer { if generation == epoch { isLoadingSections = false } }
do {
let page = try await service.sections(courseID: course.id, taskID: taskID, cursor: cursor, limit: 20)
try await checkIdentity(epoch)
let existing = Set(sections.map(\.id))
sections.append(contentsOf: page.items.filter { !existing.contains($0.id) })
sectionCursor = page.nextCursor
hasMoreSections = page.hasMore
contentErrorMessage = nil
} catch { saveContentError(error, epoch: epoch) }
/// 当前文档真正展示完成才打开读时门禁;过期页面或旧下载回调不能恢复学习。
@discardableResult
func markAttachmentRendered(id: String, previewID: UUID) -> Bool {
guard !isInvalidated, !isLoading, currentAttachmentID == id,
attachmentPreviewID == previewID, currentAttachmentLink != nil,
attachmentErrorMessage == nil else { return false }
isAttachmentRendered = true
return true
}
/// 首次打开附件目录才读取第一页;后续页也由用户主动请求。
/// 文档下载或渲染失败立即停止累计,页面随后通过已有保存管线关闭会话。
func reportAttachmentFailure(id: String, previewID: UUID, message: String) {
guard !isInvalidated, currentAttachmentID == id, attachmentPreviewID == previewID else { return }
isAttachmentRendered = false
attachmentErrorMessage = message
pauseReading()
}
/// 后续附件页仅由用户主动读取;已有第一页不重复获取。
func loadAttachments(loadMore: Bool = false) async {
guard !isLoadingAttachments, let course, !isInvalidated else { return }
guard !isLoading, !isLoadingAttachments, let course, !isInvalidated else { return }
if hasLoadedAttachments && !loadMore { return }
if loadMore && (!hasMoreAttachments || attachmentCursor == nil) { return }
let epoch = generation
@@ -203,11 +203,11 @@ final class TrainingRemoteReadingViewModel {
attachmentCursor = page.nextCursor
hasMoreAttachments = page.hasMore
hasLoadedAttachments = true
contentErrorMessage = nil
} catch { saveContentError(error, epoch: epoch) }
attachmentListErrorMessage = nil
} catch { saveAttachmentListError(error, epoch: epoch) }
}
/// 点击附件时取得有效 HTTP/HTTPS 链接,原样交给系统浏览器,不附 App Token。
/// 获取同一附件的有效 HTTP/HTTPS 授权地址,保持签名参数原样,不附 App Token。
func authorizeAttachment(id: String) async -> TrainingAttachmentLink? {
guard !isAuthorizingAttachment, let course, !isInvalidated else { return nil }
let epoch = generation
@@ -217,23 +217,42 @@ final class TrainingRemoteReadingViewModel {
let link = try await service.attachmentURL(courseID: course.id, attachmentID: id, taskID: taskID)
try await checkIdentity(epoch)
let scheme = link.url.scheme?.lowercased()
guard scheme == "http" || scheme == "https", link.url.host?.isEmpty == false,
guard link.id == id, scheme == "http" || scheme == "https", link.url.host?.isEmpty == false,
link.url.user == nil, link.url.password == nil, link.expiresAt > now() else {
throw TrainingRemoteError.paramInvalid("附件访问地址无效或已过期,请重试")
}
contentErrorMessage = nil
attachmentErrorMessage = nil
return link
} catch { saveContentError(error, epoch: epoch); return nil }
} catch { saveAttachmentError(error, epoch: epoch); return nil }
}
/// 正文已经在前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。
private func prepareAttachment(_ attachment: TrainingAttachmentInfo, epoch: Int) async {
currentAttachment = attachment
attachmentErrorMessage = nil
let previewID = UUID()
attachmentPreviewID = previewID
let link = await authorizeAttachment(id: attachment.id)
guard generation == epoch, !isInvalidated, !Task.isCancelled,
attachmentPreviewID == previewID, currentAttachmentID == attachment.id else { return }
currentAttachmentLink = link
}
private func resetAttachmentPreview() {
currentAttachment = nil
currentAttachmentLink = nil
attachmentPreviewID = nil
isAttachmentRendered = false
attachmentErrorMessage = nil
}
/// 附件已渲染且前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。
func startReading(at uptime: TimeInterval) async {
guard currentSection != nil, canStudy else { return }
guard isAttachmentRendered, currentAttachmentLink != nil, canStudy else { return }
let epoch = generation
wantsReading = true
lastVisibleUptime = uptime
await waitForSessionOperation(epoch: epoch)
guard generation == epoch, !isInvalidated, wantsReading, canStudy, currentSection != nil else { return }
guard generation == epoch, !isInvalidated, wantsReading, canStudy, isAttachmentRendered else { return }
isSessionBusy = true
defer { finishSessionOperation(epoch: epoch) }
do {
@@ -242,7 +261,7 @@ final class TrainingRemoteReadingViewModel {
try await sendHeartbeats(epoch: epoch)
}
if session == nil && canStudy { try await createSession(epoch: epoch) }
if wantsReading, session != nil, canStudy {
if wantsReading, session != nil, canStudy, isAttachmentRendered {
readingErrorMessage = nil
readingClock.resume(at: uptime)
isReading = true
@@ -253,7 +272,7 @@ final class TrainingRemoteReadingViewModel {
/// 由前台定时器驱动,每次最多记一秒;到间隔或门槛才发送网络心跳。
func recordVisibleTime(at uptime: TimeInterval) async {
lastVisibleUptime = uptime
guard isReading, wantsReading, canStudy, !isSessionBusy, pendingHeartbeat == nil,
guard isReading, wantsReading, canStudy, isAttachmentRendered, !isSessionBusy, pendingHeartbeat == nil,
readingClock.takeSecond(at: uptime) else { return }
activeSecondsTotal += 1
let interval = max(1, session?.heartbeatIntervalSeconds ?? 5)
@@ -262,7 +281,7 @@ final class TrainingRemoteReadingViewModel {
}
}
/// 页面隐藏、锁屏、正文切换或附件打开时同步停止计时,丢弃未满一秒片段。
/// 页面隐藏、锁屏、文档切换或预览失败时同步停止计时,丢弃未满一秒片段。
func pauseReading() {
wantsReading = false
finalRequested = true
@@ -293,22 +312,17 @@ final class TrainingRemoteReadingViewModel {
clearSession()
task = nil
course = nil
sections = []
currentSection = nil
currentSectionID = nil
attachments = []
bodies = [:]
resetAttachmentPreview()
attachmentListErrorMessage = nil
progress = nil
contentErrorMessage = nil
readingErrorMessage = nil
readingNotice = nil
sectionCursor = nil
attachmentCursor = nil
hasMoreSections = false
hasMoreAttachments = false
hasLoadedAttachments = false
isLoading = false
isLoadingSections = false
isLoadingAttachments = false
isAuthorizingAttachment = false
isSessionBusy = false
@@ -406,6 +420,28 @@ final class TrainingRemoteReadingViewModel {
contentErrorMessage = mapped.localizedDescription
}
private func saveAttachmentError(_ error: Error, epoch: Int) {
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
let mapped = TrainingRemoteError.map(error)
let code = (mapped as? TrainingRemoteError)?.code
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
invalidate()
return
}
attachmentErrorMessage = mapped.localizedDescription
}
private func saveAttachmentListError(_ error: Error, epoch: Int) {
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
let mapped = TrainingRemoteError.map(error)
let code = (mapped as? TrainingRemoteError)?.code
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
invalidate()
return
}
attachmentListErrorMessage = mapped.localizedDescription
}
private func handleReadingError(_ error: Error, epoch: Int) async {
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
let mapped = TrainingRemoteError.map(error)
@@ -421,7 +457,7 @@ final class TrainingRemoteReadingViewModel {
do {
let saved = try await service.progress(taskID: taskID)
try await checkIdentity(epoch)
let shouldResume = wantsReading && code != 150102
let shouldResume = wantsReading && isAttachmentRendered && code != 150102
clearSession()
progress = saved
wantsReading = shouldResume
@@ -431,7 +467,7 @@ final class TrainingRemoteReadingViewModel {
}
if shouldResume, canStudy {
try await createSession(epoch: epoch)
if wantsReading, canStudy {
if wantsReading, canStudy, isAttachmentRendered {
readingClock.resume(at: lastVisibleUptime)
isReading = true
readingErrorMessage = nil