feat(training): 支持课程附件预览与整页阅读
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user