feat(training): 接入真实培训接口与学习答题恢复
This commit is contained in:
@@ -0,0 +1,444 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式课程按需读取与有效前台读时;页面在操作完成后主动读取状态并刷新。
|
||||
final class TrainingRemoteReadingViewModel {
|
||||
/// 当前本人任务标识。
|
||||
let taskID: String
|
||||
/// 已加载的轻量任务规则与快照引用。
|
||||
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 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
|
||||
/// 已经读取过附件第一页,避免反复取相同元信息。
|
||||
private(set) var hasLoadedAttachments = false
|
||||
/// 是否正在累计本次会话的可见读时。
|
||||
private(set) var isReading = false
|
||||
/// 当前会话本地累计秒数;新会话始终从零开始。
|
||||
private(set) var activeSecondsTotal = 0
|
||||
/// 最近一次阅读保存失败,可用原请求安全重试。
|
||||
private(set) var readingErrorMessage: String?
|
||||
/// 会话恢复提示,与当前操作资格分开展示。
|
||||
private(set) var readingNotice: String?
|
||||
/// 身份已经切换,所有迟到结果都应被丢弃。
|
||||
private(set) var isInvalidated = false
|
||||
|
||||
private let service: any TrainingDataServing
|
||||
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?
|
||||
private var acceptedActiveSecondsTotal = 0
|
||||
private var nextSequence = 1
|
||||
private var pendingHeartbeat: PendingHeartbeat?
|
||||
private var finalRequested = false
|
||||
private var wantsReading = false
|
||||
private var isSessionBusy = false
|
||||
private var sessionWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var readingClock = TrainingReadingClock()
|
||||
private var lastVisibleUptime: TimeInterval = 0
|
||||
|
||||
/// 一次冻结的幂等心跳;重试时序号、累计秒数与 final 均不能变更。
|
||||
private struct PendingHeartbeat {
|
||||
let sessionID: String
|
||||
let sequence: Int
|
||||
let activeSecondsTotal: Int
|
||||
let final: Bool
|
||||
}
|
||||
|
||||
/// 注入正式数据源、身份校验与时钟,不让 ViewModel 依赖 UIKit 或共享登录视图。
|
||||
init(
|
||||
taskID: String,
|
||||
service: any TrainingDataServing,
|
||||
now: @escaping @Sendable () -> Date = { Date() },
|
||||
validateIdentity: @escaping @MainActor @Sendable () -> Bool = { true }
|
||||
) {
|
||||
self.taskID = taskID
|
||||
self.service = service
|
||||
self.now = now
|
||||
self.validateIdentity = validateIdentity
|
||||
}
|
||||
|
||||
/// 页面展示的内容或保存错误,不用中文文案判断恢复分支。
|
||||
var errorMessage: String? { readingErrorMessage ?? contentErrorMessage }
|
||||
|
||||
/// 显示未确认读时的倒计时,但只有服务器确认后才允许开始考试。
|
||||
var remainingSeconds: Int {
|
||||
guard let progress else { return task?.requiredReadingSeconds ?? 0 }
|
||||
let unconfirmed = max(0, activeSecondsTotal - acceptedActiveSecondsTotal)
|
||||
return max(0, progress.requiredReadingSeconds - progress.readingSeconds - unconfirmed)
|
||||
}
|
||||
|
||||
/// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。
|
||||
var canStudy: Bool { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated }
|
||||
|
||||
/// 首次只取元信息、目录第一页、首节正文和小型进度,不预取附件或其他小节正文。
|
||||
func load() async {
|
||||
guard !isLoading, !isInvalidated else { return }
|
||||
let epoch = generation
|
||||
isLoading = true
|
||||
contentErrorMessage = nil
|
||||
defer { if generation == epoch { isLoading = false } }
|
||||
do {
|
||||
let detail = try await service.task(id: taskID)
|
||||
try await checkIdentity(epoch)
|
||||
guard detail.summary.learning.canViewCourse else {
|
||||
throw TrainingRemoteError.forbidden("当前任务不能查看课程")
|
||||
}
|
||||
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 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)
|
||||
try await checkIdentity(epoch)
|
||||
task = detail
|
||||
course = info
|
||||
sections = page.items
|
||||
sectionCursor = page.nextCursor
|
||||
hasMoreSections = page.hasMore
|
||||
currentSectionID = first.id
|
||||
currentSection = body
|
||||
bodies[body.id] = body
|
||||
progress = saved
|
||||
} 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)
|
||||
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 }
|
||||
let epoch = generation
|
||||
isLoading = true
|
||||
defer { if generation == epoch { isLoading = false } }
|
||||
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) }
|
||||
}
|
||||
|
||||
/// 仅用户点击加载更多时读取目录下一页,不为展示一个小节遍历全部目录。
|
||||
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) }
|
||||
}
|
||||
|
||||
/// 首次打开附件目录才读取第一页;后续页也由用户主动请求。
|
||||
func loadAttachments(loadMore: Bool = false) async {
|
||||
guard !isLoadingAttachments, let course, !isInvalidated else { return }
|
||||
if hasLoadedAttachments && !loadMore { return }
|
||||
if loadMore && (!hasMoreAttachments || attachmentCursor == nil) { return }
|
||||
let epoch = generation
|
||||
isLoadingAttachments = true
|
||||
defer { if generation == epoch { isLoadingAttachments = false } }
|
||||
do {
|
||||
let page = try await service.attachments(courseID: course.id, taskID: taskID, cursor: loadMore ? attachmentCursor : nil, limit: 20)
|
||||
try await checkIdentity(epoch)
|
||||
let existing = Set(attachments.map(\.id))
|
||||
if !loadMore { attachments = page.items }
|
||||
else { attachments.append(contentsOf: page.items.filter { !existing.contains($0.id) }) }
|
||||
attachmentCursor = page.nextCursor
|
||||
hasMoreAttachments = page.hasMore
|
||||
hasLoadedAttachments = true
|
||||
contentErrorMessage = nil
|
||||
} catch { saveContentError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 点击附件时取得可直接交给系统浏览器的有效 HTTPS 链接,不附 App Token。
|
||||
func authorizeAttachment(id: String) async -> TrainingAttachmentLink? {
|
||||
guard !isAuthorizingAttachment, let course, !isInvalidated else { return nil }
|
||||
let epoch = generation
|
||||
isAuthorizingAttachment = true
|
||||
defer { if generation == epoch { isAuthorizingAttachment = false } }
|
||||
do {
|
||||
let link = try await service.attachmentURL(courseID: course.id, attachmentID: id, taskID: taskID)
|
||||
try await checkIdentity(epoch)
|
||||
guard link.url.scheme?.lowercased() == "https", link.url.host != nil, link.expiresAt > now() else {
|
||||
throw TrainingRemoteError.paramInvalid("附件访问地址无效或已过期,请重试")
|
||||
}
|
||||
contentErrorMessage = nil
|
||||
return link
|
||||
} catch { saveContentError(error, epoch: epoch); return nil }
|
||||
}
|
||||
|
||||
/// 正文已经在前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。
|
||||
func startReading(at uptime: TimeInterval) async {
|
||||
guard currentSection != 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 }
|
||||
isSessionBusy = true
|
||||
defer { finishSessionOperation(epoch: epoch) }
|
||||
do {
|
||||
try await checkIdentity(epoch)
|
||||
if pendingHeartbeat != nil || finalRequested {
|
||||
try await sendHeartbeats(epoch: epoch)
|
||||
}
|
||||
if session == nil && canStudy { try await createSession(epoch: epoch) }
|
||||
if wantsReading, session != nil, canStudy {
|
||||
readingErrorMessage = nil
|
||||
readingClock.resume(at: uptime)
|
||||
isReading = true
|
||||
} else if session != nil { try await sendHeartbeats(epoch: epoch) }
|
||||
} catch { await handleReadingError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 由前台定时器驱动,每次最多记一秒;到间隔或门槛才发送网络心跳。
|
||||
func recordVisibleTime(at uptime: TimeInterval) async {
|
||||
lastVisibleUptime = uptime
|
||||
guard isReading, wantsReading, canStudy, !isSessionBusy, pendingHeartbeat == nil,
|
||||
readingClock.takeSecond(at: uptime) else { return }
|
||||
activeSecondsTotal += 1
|
||||
let interval = max(1, session?.heartbeatIntervalSeconds ?? 5)
|
||||
if activeSecondsTotal - acceptedActiveSecondsTotal >= interval || remainingSeconds == 0 {
|
||||
await flush(final: remainingSeconds == 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// 页面隐藏、锁屏、正文切换或附件打开时同步停止计时,丢弃未满一秒片段。
|
||||
func pauseReading() {
|
||||
wantsReading = false
|
||||
finalRequested = true
|
||||
isReading = false
|
||||
readingClock.pause()
|
||||
}
|
||||
|
||||
/// 保存已累计片段;先重试冻结的旧请求,再用新序号发送最终关闭请求。
|
||||
func flush(final: Bool = false) async {
|
||||
if final { pauseReading() }
|
||||
let epoch = generation
|
||||
await waitForSessionOperation(epoch: epoch)
|
||||
guard generation == epoch, !isInvalidated, session != nil else { return }
|
||||
isSessionBusy = true
|
||||
defer { finishSessionOperation(epoch: epoch) }
|
||||
do {
|
||||
try await checkIdentity(epoch)
|
||||
try await sendHeartbeats(epoch: epoch)
|
||||
readingErrorMessage = nil
|
||||
} catch { await handleReadingError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 身份切换使所有异步操作失效,清理旧账号内容和未确认片段。
|
||||
func invalidate() {
|
||||
generation += 1
|
||||
isInvalidated = true
|
||||
pauseReading()
|
||||
clearSession()
|
||||
task = nil
|
||||
course = nil
|
||||
sections = []
|
||||
currentSection = nil
|
||||
currentSectionID = nil
|
||||
attachments = []
|
||||
bodies = [:]
|
||||
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
|
||||
resumeSessionWaiters()
|
||||
}
|
||||
|
||||
private func createSession(epoch: Int) async throws {
|
||||
let requestID = sessionRequestID ?? UUID().uuidString
|
||||
sessionRequestID = requestID
|
||||
let value = try await service.startReading(taskID: taskID, requestID: requestID)
|
||||
try await checkIdentity(epoch)
|
||||
session = value
|
||||
progress = value.progress
|
||||
activeSecondsTotal = 0
|
||||
acceptedActiveSecondsTotal = 0
|
||||
nextSequence = 1
|
||||
finalRequested = !wantsReading || !canStudy
|
||||
}
|
||||
|
||||
private func sendHeartbeats(epoch: Int) async throws {
|
||||
while let session {
|
||||
if pendingHeartbeat == nil {
|
||||
guard finalRequested || activeSecondsTotal > acceptedActiveSecondsTotal else { return }
|
||||
pendingHeartbeat = PendingHeartbeat(sessionID: session.sessionID, sequence: nextSequence,
|
||||
activeSecondsTotal: activeSecondsTotal, final: finalRequested)
|
||||
}
|
||||
guard let pending = pendingHeartbeat else { return }
|
||||
let response = try await service.heartbeat(sessionID: pending.sessionID, sequence: pending.sequence,
|
||||
activeSecondsTotal: pending.activeSecondsTotal, final: pending.final)
|
||||
try await checkIdentity(epoch)
|
||||
guard response.sessionID == pending.sessionID, response.acceptedSequence == pending.sequence,
|
||||
response.acceptedActiveSecondsTotal >= acceptedActiveSecondsTotal,
|
||||
response.acceptedActiveSecondsTotal <= pending.activeSecondsTotal else {
|
||||
throw TrainingRemoteError.sessionConflict("学习上报确认与请求不一致")
|
||||
}
|
||||
progress = response.progress
|
||||
acceptedActiveSecondsTotal = response.acceptedActiveSecondsTotal
|
||||
nextSequence = pending.sequence + 1
|
||||
pendingHeartbeat = nil
|
||||
if response.sessionClosed || pending.final {
|
||||
clearSession()
|
||||
return
|
||||
}
|
||||
if response.progress.readingCompleted || !response.progress.canStudy { pauseReading() }
|
||||
if !finalRequested { return }
|
||||
}
|
||||
}
|
||||
|
||||
private func clearSession() {
|
||||
session = nil
|
||||
sessionRequestID = nil
|
||||
pendingHeartbeat = nil
|
||||
activeSecondsTotal = 0
|
||||
acceptedActiveSecondsTotal = 0
|
||||
nextSequence = 1
|
||||
finalRequested = false
|
||||
isReading = false
|
||||
readingClock.pause()
|
||||
}
|
||||
|
||||
private func waitForSessionOperation(epoch: Int) async {
|
||||
while isSessionBusy, generation == epoch, !isInvalidated {
|
||||
await withCheckedContinuation { sessionWaiters.append($0) }
|
||||
}
|
||||
}
|
||||
|
||||
private func finishSessionOperation(epoch: Int) {
|
||||
guard generation == epoch else { return }
|
||||
isSessionBusy = false
|
||||
resumeSessionWaiters()
|
||||
}
|
||||
|
||||
private func resumeSessionWaiters() {
|
||||
let waiters = sessionWaiters
|
||||
sessionWaiters = []
|
||||
waiters.forEach { $0.resume() }
|
||||
}
|
||||
|
||||
private func checkIdentity(_ epoch: Int) async throws {
|
||||
guard generation == epoch, !isInvalidated, !Task.isCancelled else { throw CancellationError() }
|
||||
guard await validateIdentity() else {
|
||||
invalidate()
|
||||
throw TrainingRemoteError.identityChanged
|
||||
}
|
||||
}
|
||||
|
||||
private func saveContentError(_ 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
|
||||
}
|
||||
contentErrorMessage = mapped.localizedDescription
|
||||
}
|
||||
|
||||
private func handleReadingError(_ error: Error, epoch: Int) async {
|
||||
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
|
||||
}
|
||||
isReading = false
|
||||
readingClock.pause()
|
||||
readingErrorMessage = mapped.localizedDescription
|
||||
guard code == 150104 || code == 150105 || code == 150102 else { return }
|
||||
do {
|
||||
let saved = try await service.progress(taskID: taskID)
|
||||
try await checkIdentity(epoch)
|
||||
let shouldResume = wantsReading && code != 150102
|
||||
clearSession()
|
||||
progress = saved
|
||||
wantsReading = shouldResume
|
||||
if code == 150104 || code == 150105 {
|
||||
readingErrorMessage = nil
|
||||
readingNotice = "学习会话已恢复,继续阅读即可"
|
||||
}
|
||||
if shouldResume, canStudy {
|
||||
try await createSession(epoch: epoch)
|
||||
if wantsReading, canStudy {
|
||||
readingClock.resume(at: lastVisibleUptime)
|
||||
isReading = true
|
||||
readingErrorMessage = nil
|
||||
readingNotice = "学习会话已恢复,继续阅读即可"
|
||||
} else if session != nil { try await sendHeartbeats(epoch: epoch) }
|
||||
}
|
||||
} catch {
|
||||
guard generation == epoch, !isInvalidated else { return }
|
||||
let mapped = TrainingRemoteError.map(error)
|
||||
let code = (mapped as? TrainingRemoteError)?.code
|
||||
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 { invalidate() }
|
||||
else { readingErrorMessage = mapped.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user